需要同步仅增量计数器吗?
我使用整数作为计数器。该整数只会增加,并且肯定有多个线程会同时增加它。当没有其他线程尝试访问其值时,在程序执行结束时读取该计数器的值。
我假设我不必为这种仅增量计数器使用锁或任何类型的同步。这是对的吗? 如果这有什么区别的话,我用 Java 编写代码。
I use an integer as counter. The integer will only be increased, and surely more than one thread will increase it at the same time. The value of this counter is read at the end of program execution when no other thread will try to access its value.
I assume that I don't have to use a lock or any kind of synchronization for this kind of increment-only counter. Is this right?
I code in Java if that makes any difference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只使用了
int
或long
变量,那么您将需要同步 - 增量涉及读/本地增量/写,这远非同步原子操作。 (即使变量是易失性
以避免内存模型过时问题,您仍然会拥有三个不同的操作,并且有可能在它们之间的任何对之间被抢占。)幸运的是,Java 提供了< a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html" rel="noreferrer">
AtomicInteger
和AtomicLong
可以在没有任何同步的情况下使用:If you just used an
int
orlong
variable then you would need synchronization - incrementing involves read / increment-locally / write, which is far from an atomic operation. (Even if the variable isvolatile
to avoid memory model concerns of staleness, you'd still have three distinct operations, with the possibility of being pre-empted between any pair of them.)Fortunately Java provides
AtomicInteger
andAtomicLong
which can be used without any synchronization: