AtomicBoolean vs Synchronized block, whats the difference
Asked Answered
E

2

11

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?,

Evening answered 26/1, 2015 at 17:18 Comment(3)
How about... reading the javadoc of AtomicBoolean? It describes the guarantees offered and the advantages over synchronization.Gonsalve
please point me to the java doc that explains "clearly" the advantages of one over the other. I can't find it in docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/…Evening
Look at the javadoc for the package java.util.concurrent.atomic : docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/…Marianamariand
T
7

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
Tramway answered 26/1, 2015 at 17:22 Comment(0)
C
10

If all you're trying to do is make getting and setting a single boolean value atomic, then yes - you can use AtomicBoolean instead without any synchronization.

Of course, synchronized allows a far wider range of uses, such as performing several actions within the block without losing the lock, or using it for wait/notify. So it's not like AtomicBoolean is a general alternative to synchronization - but in this case you can use it instead of synchronization.

Connacht answered 26/1, 2015 at 17:21 Comment(0)
T
7

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
Tramway answered 26/1, 2015 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.