Clojure: atom vs agent vs ref

zhuchenghaoma 2019-06-25

First atom, agent and ref are work for mutable state and threads.

Atom

It is synchronous, and will retry when other thread change the state.

Use case: memoize.

Functions for agent: atom, deref, @, swap!, reset!

Agent

It is asynchronous.

It has :error-handler, and :error-mode. when validate failed, you need restrt the agent, or you can use :continue for error mode.

Use case: in memory log.

Functions for agent: agent, deref, @, send, send-off, send-via

Ref

It is coordinated and synchronous. Use a dosync to update a ref.

Use ensure when you want the value of the ref it returns won’t be changed by another transaction(dosync).

Functions: ref, ref-set, alter, dosync, ensure.

Use case: it is coordinated so use it when you have multiple values to change. And you can use agent instead of ref if you like.

Watchers and validators

Both atom, agent and ref have watchers and validators. The agent's validator is a little different, it has :error-handler and :error-mode.

Functions: set-validator!, add-watch, remove-watch

STM transactions

Software transactional memory,

Software Transactional Memory (STM) is a concurrency control technique
analogous to database transactions for controlling access to shared memory in concurrent computing. It is an alternative to lock based synchronization.

It is atomic, consistent, and isolated.

References

Seven Concurrency Models in Seven Weeks : When Threads Unravel
Atoms
Agents and Asynchronous Actions
Refs and Transactions
Clojure differences between Ref, Var, Agent, Atom, with examples

相关推荐