1

Volatile should be used when we are doing only read operation on variable, as value updated by one thread will be visible to the other even if the former thread looses CPU and exits the synchronized block. Is that correct? Atomic primitives will be used when one needs to use the atomic behaviuor. For example -

if (volatileBoolean) {
    volatileBoolean = !volatileBoolean;
}

Let's suppose value of volatileBoolean is true. One thread checks volatileBoolean as true and enters if block, second thread seeing the value of volatileBoolean as true, enters if block as well. Now, lets suppose first thread assigns false value (!volatileBoolean) to volatileBoolean variable and looses CPU, hence exits the if block. Second thread sees volatileBoolean as false, assigns it back to true.

Is this the case where AtomicBoolean should be used? If yes, why can't this be handled by using synchronized?

synchronized(this){
        if (volatileBoolean) {
            volatileBoolean = !volatileBoolean;
        }
}
assylias
  • 321,522
  • 82
  • 660
  • 783
Gaurav Seth
  • 186
  • 3
  • 11

4 Answers4

2

Is this the case where AtomicBoolean should be used?

Yes it is.

If yes, why can't this be handled by using synchronized?

It is functionnaly equivalent, but AtomicBoolean does not use a lock, which can be more efficient under moderate contention. See this other question - it looks at AtomicInteger but the conclusions are directly applicable to AromicBoolean too.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
0

Yes, this is the case where you would want to use AtomicBoolean. It is a pretty good and safe way to achieve synchronization of the kind you mentioned (instead of doing it yourself) and it is much faster. Also refer to this link for comparison with using volatile boolean as alternative.

Community
  • 1
  • 1
V_Singh
  • 729
  • 11
  • 22
0

Volatile should be used when we are doing only read operation on variable, as value updated by one thread will be visible to the other even if the former thread looses CPU and exits the synchronized block. Is that correct?

  • volatile does not have any dependency with synchronized block. volatile variables are not cached by thread. So changes by one thread will be visible to other threads.
  • So volatile variables can be used when write/update to the variable is done by single thread, and the update need to visible immediately to all other threads accessing the variable. volatile only ensures Visibility and not Atomicity.

Is this the case where AtomicBoolean should be used? If yes, why can't this be handled by using synchronized?

  • Yes, If you use synchronized block, we need not use volatile variable inside, as synchronized block will ensure Visibility and Atomicity for the shared data. Volatile reads are slightly more expensive than nonvolatile reads on most current processor architectures.

About AtomicBoolean

AtomicBoolean internally uses a volatile int, and CAS operations to provide Visibility and Atomicity.

AtomicBoolean.java

public class AtomicBoolean implements java.io.Serializable {
  
  private volatile int value;

   /**
    * Creates a new {@code AtomicBoolean} with the given initial value.
    *
    * @param initialValue the initial value
    */
   public AtomicBoolean(boolean initialValue) {
       value = initialValue ? 1 : 0;
   }

From Java Concurrency In Practice book, about volatile variables.

The Java language also provides an alternative, weaker form of synchronization, volatile variables, to ensure that updates to a variable are propagated predictably to otherthreads. When a field is declared volatile,the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations. Use volatile variables only when they simplify implementing and verifying your synchronization policy; avoid using volatile variables when verifying correctness would require subtle reasoning about visibility. Good uses of volatile variables include ensuring the visibility of their own state, that of the object they refer to, or indicating that an important lifecycle event (such as initialization or shutdown) has occurred.

Community
  • 1
  • 1
Albin
  • 371
  • 1
  • 4
  • 18
0

AtomicBoolean and any AtomicSomething is just implemented using volatile. The only difference is that those AtomicSomething contain a few methods for doing synchronization without synchronized keyword, eg compareAndSet or lazySet. So you should probably use AtomicBoolean in your case.

iirekm
  • 8,890
  • 5
  • 36
  • 46