Multithreading – synchronous counter in clojure

If I want to keep a global counter (for example, count the number of incoming requests across multiple threads), the best way in Java is to use volatile int. suppose clojure is a better way (better throughput)?

Solution

I'll do this with atom in clojure:

(def counter (atom 0N))

;; increment the counter
(swap! counter inc)

;; read the counter
@counter
=> 1

This is completely thread safe and surprisingly high performance In addition, because it uses clojure's exact number processing, it is not vulnerable to integer overflow because volatile int can be

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>