yart yart - 1 year ago 61
Java Question

When do I need to use AtomicBoolean in Java?

How I can use AtomicBoolean and what is that class for?

Answer Source

When multiple threads need to check and change the boolean. For example:

if (!initialized) {
   initialized = true;

This is not thread-safe. You can fix it by using AtomicBoolean:

if (atomicInitialized.compareAndSet(false, true)) {