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.