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