Use Agents for Asynchronous Updates

Some applications have tasks that can proceed independently with minimal coordination between tasks. Clojure agents support this style of task.

Agents have much in common with refs. Like refs, you create an agent by wrapping some piece of initial state:

 ​(​agent​ initial-state)​

Create a counter agent that wraps an initial count of zero:

 ​(def counter (agent 0))​
 ​-> #'user/counter​

Once you have an agent, you can send the agent a function to update its state. send queues an update-fn to run later, on a thread in a thread pool:

 ​(​send​ ​agent​ update-fn & args)​

Sending to an agent is very much like commuting a ref. Tell the counter to inc:

 ​(send counter inc)​
 ​-> #<clojure.lang.Agent@23451c74: ...

Get Programming Clojure, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.