My code contains some AtomicBoolean
fields. Only the get()
and set()
methods of these fields are called.
Can the types of these fields safely be replaced by primitive boolean?
I mean, assignment and access operations of primitive booleans are atomic operations in Java. And from that point of view I cannot see any reason to use AtomicBoolean
in my case.
In my understanding AtomicBoolean
would only make sense if methods like compareAndSet
are used, that combine a comparison and access. Am I wrong about that? Could you explain why?
Atomic variables are described as "better volatiles" in Java Concurrency in Practice (see section 15.3). Here is an extract from this book:
The atomic variable classes provide a generalization of
volatile
variables to support atomic conditional read-modify-write operations.AtomicInteger
represents anint
value, and providesget
andset
methods with the same memory semantics as reads and writes to avolatile int
.
Applied to your case this means that if you're using only get()
and set()
methods of AtomicBoolean
, they can be safely replaced with read-writes to volatile boolean
.
volatile
is needed to guarantee that all threads will see up-to-date value of the variable. Back to Java Concurrency in Practice (section 3.1.4):
When a field is declared
volatile
, the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations.Volatile
variables are not cached in registers or in caches where they are hidden from other processors, so a read of avolatile
variable always returns the most recent write by any thread.