Shirgill Farhan Ansari Shirgill Farhan Ansari - 4 months ago 15
Java Question

What happens if a volatile variable is written from 2 threads?

Consider the snippet from Java Concurrency in Practice-

public class SynchronizedInteger{
@GuardedBy("this") private int value;

public synchronized int getValue() {
return value;

public synchronized void setValue(int value) {
this.value = value;

An extract from the same book-

A good way to think about volatile variables is to imagine that they
behave roughly like the SynchronizedInteger class in Listing above,
replacing reads and writes of the volatile variable with calls to get
and set. Yet accessing a volatile variable performs no locking and so
cannot cause the executing thread to block, making volatile variables
a lighter-weight synchronization mechanism than synchronized.

A special case of thread confinement applies to volatile variables. It is safe to perform read-modify-write operations on shared volatile variables as long as you ensure that the volatile variable is only written from a single thread.

So, if you make the instance variable in the above class as volatile and then remove the synchronized keyword, after that suppose there are 3 threads

Thread A & Thread B are writing to the same volatile variable.

Thread C reads the volatile variable.

Since the volatile variable is now written from 2 threads, why is it unsafe to perform read-modify-write operations on this shared volatile variable?


The keyword volatile is used to ensure that changes to your Object will be seen by other Threads. This does not enforce, that non-atomic operations on the Object will be performed without an other Thread interfering before the operation is finished. For enforcing this you will need the keyword synchronized.