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
Need synchronization for an increment-only counter?
提问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 int
or long
variable then you wouldneed synchronization - incrementing involves read / increment-locally / write, which is far from an atomic operation. (Even if the variable is volatile
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.)
如果您只使用int
或long
变量,那么您将需要同步 - 增量涉及读取/本地增量/写入,这远非原子操作。(即使变量是volatile
为了避免过时的内存模型问题,您仍然有三个不同的操作,并且有可能在任何一对之间被抢占。)
Fortunately Java provides AtomicInteger
and AtomicLong
which canbe used without any synchronization:
幸运的是Java提供了AtomicInteger
和AtomicLong
它可以没有任何同步使用:
private final AtomicLong counter = new AtomicLong();
...
counter.incrementAndGet(); // No need for synchronization