Need synchronization for an increment-only counter?
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
qinsoon
Updated on October 05, 2020Comments
-
qinsoon over 3 years
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.
-
JavaSa about 10 yearsAs usual , an awesome answer by Jon skeet. Jon did you write any book on Java programming as well , if so please let me know :) Recommendation of other books will be appreciated also
-
Jon Skeet about 10 years@JavaSa: No, I haven't written anything on Java. I'd thoroughly recommend Effective Java by Josh Bloch though.
-
JavaSa about 10 yearsThanks, do you have also a complimentary books suggestions to cover new features that has been new in Java since 2005? Lets say for java 7 and maybe Java 8
-
Jon Skeet about 10 years@JavaSa: No, I'm afraid it's a long time since I've actually read any Java books...
-
flow2k almost 7 years