java 仅增量计数器需要同步吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7646269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:50:18  来源:igfitidea点击:

Need synchronization for an increment-only counter?

javasynchronizationcounterincrement

提问by qinsoon

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.

我假设我不必为这种仅增量计数器使用锁或任何类型的同步。这是正确的吗?如果这有什么不同,我用 Java 编码。

回答by Jon Skeet

If you just used an intor longvariable then you wouldneed synchronization - incrementing involves read / increment-locally / write, which is far from an atomic operation. (Even if the variable is volatileto 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.)

如果您只使用intlong变量,那么您需要同步 - 增量涉及读取/本地增量/写入,这远非原子操作。(即使变量是volatile为了避免过时的内存模型问题,您仍然有三个不同的操作,并且有可能在任何一对之间被抢占。)

Fortunately Java provides AtomicIntegerand AtomicLongwhich canbe used without any synchronization:

幸运的是Java提供了AtomicIntegerAtomicLong可以没有任何同步使用:

private final AtomicLong counter = new AtomicLong();

...

counter.incrementAndGet(); // No need for synchronization