yart yart - 1 month ago 11
Java Question

When do I need to use AtomicBoolean in Java?

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

Answer

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

if (!initialized) {
   initialize();
   initialized = true;
}

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

if (atomicInitialized.compareAndSet(false, true)) {
    initialize();
}