Clojure: atom vs agent vs ref

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值