开发者

Need synchronization for an increment-only counter?

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 Ja开发者_如何学Cva if that makes any difference.


If you just used an int or long variable then you would need 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.)

Fortunately Java provides AtomicInteger and AtomicLong which can be used without any synchronization:

private final AtomicLong counter = new AtomicLong();

...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜