philipbohun.com

Glojure by Example: Closing Channels

close! closes a channel. Values already buffered can still be received. Further receives return nil. Closing a closed channel throws.

(require '[clojure.core.async :as async])

(def jobs (async/chan 2))
(async/>! jobs 1)
(async/>! jobs 2)
(async/close! jobs)
(println (async/<! jobs))
(println (async/<! jobs))
(println (async/<! jobs))

A send after close fails. Catch it if the sender races with the closer. The error text from the runtime includes a stack, so this example prints its own message.

(try
  (async/>! jobs 3)
  (println "sent")
  (catch go/any _
    (println "send on a closed channel fails")))

The third receive is nil because the channel is closed and empty.

$ glj closing-channels.glj
1
2
nil
send on a closed channel fails

Next example: Walking Channels.