Asynchronous agents and state
While atoms are synchronous, agents are the asynchronous mechanism in Clojure to effect any change in the state. Every agent is associated with a mutable state. We pass a function (known as "action") to an agent with the optional additional arguments. This function gets queued for processing in another thread by the agent. All the agents share two common thread pools—one for the low-latency (potentially CPU-bound, cache-bound, or memory-bound) jobs, and one for the blocking (potentially I/O related or lengthy processing) jobs. Clojure provides the send
function for the low-latency actions, send-off
for blocking actions, and send-via
to have the action executed on the user-specified thread-pool, instead of either of the preconfigured thread pools. All of send
, send-off
, and send-via
return immediately. Here is how we can use them:
(def a (agent 0)) ;; invoke (inc 0) in another thread and set state of a to result (send a inc) @a ; returns 1 ;; invoke (+ 1 2 3...