Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
716 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...