The volatile
keyword is used:
long
and double
. (all other, primitive accesses are already guaranteed to be atomic!)The java.util.concurrent.atomic.*
classes are, according to the java docs:
A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:
boolean compareAndSet(expectedValue, updateValue);
The atomic classes are built around the atomic compareAndSet(...)
function that maps to an atomic CPU instruction. The atomic classes introduce the happen-before ordering as the volatile
variables do. (with one exception: weakCompareAndSet(...)
).
From the java docs:
When a thread sees an update to an atomic variable caused by a weakCompareAndSet, it does not necessarily see updates to any other variables that occurred before the weakCompareAndSet.
To your question:
Does this mean that whosoever takes lock on it, that will be setting its value first. And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?
You don't lock anything, what you are describing is a typical race condition that will happen eventually if threads access shared data without proper synchronization. As already mentioned declaring a variable volatile
in this case will only ensure that other threads will see the change of the variable (the value will not be cached in a register of some cache that is only seen by one thread).
What is the difference between
AtomicInteger
andvolatile int
?
AtomicInteger
provides atomic operations on an int
with proper synchronization (eg. incrementAndGet()
, getAndAdd(...)
, ...), volatile int
will just ensure the visibility of the int
to other threads.