clojure中的同步计数器 [英] synchronized counter in clojure

查看:93
本文介绍了clojure中的同步计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想保留一个全局计数器(例如计算多个线程的传入请求数),那么在Java中最好的方法是使用volatile int。假设,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?

推荐答案

a Clojure中的a href =http://clojure.org/atoms> atom :

I would do this with an atom in Clojure:

(def counter (atom 0N))

;; increment the counter
(swap! counter inc)

;; read the counter
@counter
=> 1

这是完全线程安全的,性能令人惊讶。此外,由于它使用Clojure的abitrary-precision数字处理,它不容易受到整数溢出的方式volatile int可以是.....

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

这篇关于clojure中的同步计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆