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:
Applied to your case this means that if you're using only
get()andset()methods ofAtomicBoolean, they can be safely replaced with read-writes tovolatile boolean.volatileis 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):