synchronized counter in clojure

两盒软妹~` 提交于 2019-12-08 15:57:58

问题


If I want to keep a global counter (e.g. to count number of incoming requests across multiple threads), then the best way to do in java would be to use a volatile int. Assuming, clojure is being used is there a better (better throughput) way to do?


回答1:


I would do this with an atom in Clojure:

(def counter (atom 0N))

;; increment the counter
(swap! counter inc)

;; read the counter
@counter
=> 1

This is totally thread-safe, and surprisingly high performance. Also, since it uses Clojure's abitrary-precision numeric handling, it isn't vulnerable to integer overflows in the way that a volatile int can be.....




回答2:


Define a global counter as an agent

(def counter (agent 0))

To increase the value contained in the agent you send a function (in this case inc) to the agent:

(send counter inc)

To read the current value you can use deref or the @ reader macro:

@counter ;; same as (deref counter)

Agents are only one of several available reference types. You can read more about these things on the Clojure website:

  • High-level overview
  • Software transactional memory with refs
  • Asynchronous agents
  • Atoms


来源:https://stackoverflow.com/questions/7461562/synchronized-counter-in-clojure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!