Skip to content

Instantly share code, notes, and snippets.

@mjg123
Created October 21, 2011 22:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjg123/1305115 to your computer and use it in GitHub Desktop.
Save mjg123/1305115 to your computer and use it in GitHub Desktop.
Worker Queues in Clojure
In Rich Hickey's talk "Making simple easy" he recommends decoupling things so that if "A" wants to call a function in "B" there should be a queue of some kind in between so that A & B don't have to be aware of each other's existence. He calls this "complecting the when and the who", ie introducing unnecessary complexity.
So, how to implement in clojure? Here's my stab at it:
(defn new-q [] (java.util.concurrent.LinkedBlockingDeque.))
(defn offer!
"adds x to the back of queue q"
[q x] (.offer q x) q)
(defn take!
"takes from the front of queue q. if q is empty, block until something is offer!ed into it"
[q] (.take q))
;;------------
;; so now we can do like this
(def example-queue (new-q))
(future (println ">> " (take! q))) ; background thread, blocks waiting for something to print
(offer! q "HELLO WORLD") ; now the future-d thread is unblocked and ">> HELLO WORLD" is printed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment