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 an atomic operation(unless the variable is of type long
or double
). Operations variables of type long
or double
are only atomic if they declared with the volatile
keyword."
AtomicInteger
or AtomicLong
that provides methods like getAndDecrement()
, getAndIncrement()
and getAndSet()
which are atomic.
I got confused a bit with the above statement.. could you please clarify when to use AtomicInteger
or AtomicLong
classes.
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.