Atomics and compare-and-swap question 64 of 180 junior
Can you replace volatile boolean running with AtomicBoolean, and should you?
- No, they behave differently for a flag
- Correct: Yes, and for a plain set-and-read flag
volatileis the cheaper, clearer choice;AtomicBooleanearns its place when you needcompareAndSet - Yes, and
AtomicBooleanis always better - No,
AtomicBooleanis not thread safe
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.
Quiz yourself on Atomics and compare-and-swap Suggest a correction