When is it preferable to use volatile boolean in Java rather than AtomicBoolean? [duplicate]

The main difference between AtomicBoolean and volatile from a practical point of view is that the compare-and-set operation isn’t atomic with volatile variables.

 volatile boolean b;

 void foo() {
   if( b ) {
     //Here another thread might have already changed the value of b to false
     b = false;
   }
 }

But seeing as all your concurrent writes are idempotent and you only read from one thread, this shouldn’t be a problem.

Leave a Comment