Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronized counter in clojure

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?

like image 337
142857 Avatar asked Sep 18 '11 12:09

142857


1 Answers

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.....

like image 196
mikera Avatar answered Sep 22 '22 04:09

mikera