Recently I was reading a tutorial, in that I came across a statement that says..
\"The Java language specification guarantees that reading or writing a variable is
Doing a = 28
(with a
being an int
) is an atomic operation. But doing a++
is not an atomic operation because it requires a read of the value of a, an incrementation, and a write to a of the result. As a result, if you used a++
to implement a thread-safe counter, you could have two threads reading the value concurrently (26 for example), then have both increment it and writing it concurrently, resulting in 27 as a result, instead of 28.
AtomicInteger solves this issue by providing atomic operations like the ones you listed. In my example, you would use incrementAndGet()
for example, which would guarantee the end value is 28 and not 27.