As mentioned from Java_author,
The Java language also provides an alternative, weaker form of synchronization, volatile variables, to ensure that updates to a variable are propagated predictably to other threads.
So, my understanding is,
the below code that uses locking(synchronized
) to provide (mutual exclusion + memory visibility),
public class SynchronizedInteger{
private int value;
public synchronized int get(){ return value; }
public synchronized void set(int value){ this.value = value; }
}
can also be written just using volatile
keyword providing (mutual exclusion + memory visibility), shown below,
public class SynchronizedInteger{
private volatile int value;
public int get(){ return value; }
public void set(int value){ this.value = value; }
}
But,
Why
volatile
usage is weaker form of synchronization?Book says: writing a
volatile
variable is like exiting asynchronized
block and reading avolatile
variable is like entering asynchronized
blockCan multiple threads writing to
volatile
memory areavalue
, holds mutual exclusion?