Search code examples
javaconcurrencysynchronizationbooleanatomic

AtomicBoolean vs Synchronized block, whats the difference


I am trying to understand the difference between the two following code blocks

AtomicBoolean ab = new AtomicBoolean(false);  

using the following to get and set state. .
ab.get();
ab.set(X);

vs. 

private boolean ab = false;
private final Object myboollock = new Ojbect();

public void setAB(boolean state)
{
    synchronized(myboollock)
     {
          ab = state;
     }
}

public boolean getAB()
{
 synchronized(myboollock)
 {
         return ab;
 }
}

I need to thread protect a boolean, that is all, and have in the past used the later method, but would like to start to use Atomic objects, (if ) they are safe?,


Solution

  • There are a few subtle differences but seen from the outside the two code snippets behave similarly: if you call the set method, the change will be visible to other threads calling get subsequently.

    The main differences are:

    • performance: depending on the level of contention, you may get better performance with synchronized or AtomicBoolean
    • atomicity: if at some stage you want to do more than just setting the boolean value, a synchronized block will allow you to add instructions atomically but AtomicBoolean won't