Java Concurrency Interview

Atomics and compare-and-swap question 64 of 180 junior

Can you replace volatile boolean running with AtomicBoolean, and should you?

For a stop flag that one thread sets and others read, volatile boolean is exactly right: one field, no allocation, and the visibility guarantee you need.

AtomicBoolean is for when the transition itself has to be atomic, which is the "do this exactly once" pattern:

if (shutdown.compareAndSet(false, true)) {
    // exactly one thread gets here, no matter how many call close()
    closeResources();
}

Reach for it when the answer to "what if two threads do this at once" is "one of them must win", and for a flag otherwise.

atomics volatile

Quiz yourself on Atomics and compare-and-swap Suggest a correction