Best concurrency questions in February 2011

volatile boolean vs. AtomicBoolean

13 votes

I've looked at the other volatile vs. Atomicxxxx questions in SO (including this one) and have read the description of java.util.current.atomic, and am not quite satisfied with the nuances.

If I'm trying to decide between using volatile boolean and AtomicBoolean, are there practical differences besides the atomic read-modify-write operations offered by AtomicBoolean? (e.g. compareAndSet() and getAndSet())

Suppose I have

volatile boolean flag;

Then one or more threads set the flag (but not clear it). If I have one thread that reads the flag, and if set, does an action, and then clears the flag, is volatile adequate?

Is there a higher cost to AtomicBoolean than volatile boolean, in terms of

  • memory space
  • performance hit (volatile boolean appears to require memory fencing, AtomicBoolean appears to require memory fencing + some minor locking on CAS operations as per the java.util.current.atomic description)

My gut call is to just go with AtomicBoolean and be safe, but I want to understand if there's ever a situation to use volatile boolean instead (e.g. if I had thousands of instances of them and performance were an issue).

Essentially all AtomicBoolean is is a volatile boolean in an object.

There will be a small overhead per object. Probably insignificant, but possibly more memory to get into cache.

If you need to use AtomicBooleanFieldUpdater then there is quite a lot of performance overhead. Can be okay if you aren't going to do it often (as attach in NIO).