yart yart - 1 year ago 68
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)) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download