如果我想保留一个全局计数器(例如,计算跨多个线程的传入请求数),那么在java中执行的最佳方法是使用volatile int。假设,正在使用clojure是否有更好的(更好的吞吐量)方法呢?
答案 0 :(得分:13)
我会在Clojure中使用atom执行此操作:
(def counter (atom 0N))
;; increment the counter
(swap! counter inc)
;; read the counter
@counter
=> 1
这完全是线程安全的,并且性能出奇的高。此外,由于它使用了Clojure的abitrary-precision数字处理,因此它不易受整数溢出的影响,因为volatile可以是......
答案 1 :(得分:7)