Visualizing readwrite barriers while using synchronized volatile
suggest changeAs we know, we should use the synchronized keyword to make execution of a method or block exclusive. But few of us may not be aware of one more important aspect of using synchronized and volatile keyword: apart from making a unit of code atomic, it also provides read / write barrier. What is this read / write barrier? Let’s discuss this using an example:
class Counter {
private Integer count = 10;
public synchronized void incrementCount() {
count++;
}
public Integer getCount() {
return count;
}
}
Let’s suppose a thread A calls incrementCount() first, then another thread B calls getCount(). In this scenario there is no guarantee that B will see the updated value of count. It may still see count as 10, and it is also possible that it never sees the updated value of count.
To understand this behavior we need to understand how the Java memory model integrates with hardware architecture. In Java, each thread has its own thread stack. This stack contains the method call stack and local variables created in that thread. In a multi-core system, it is quite possible that two threads are running concurrently on separate cores. In such a scenario it is possible that part of a thread’s working copy lies in a register or cache of a core. If a thread accesses an object using the synchronized (or volatile) keyword, after the synchronized block that thread syncs its local copy of that variable with main memory. This creates a read / write barrier and makes sure that the thread is seeing the latest value of that object.
But in our case, since thread B has not used synchronized access to count, it might be referring to a value of count stored in a register and may never see updates from thread A. To make sure that B sees the latest value of count, we need to make getCount() synchronized as well.
public synchronized Integer getCount() {
return count;
}
Now when thread A is done with updating count it unlocks Counter instance, at the same time creates write barrier and flushes all changes done inside that block to the main memory. Similarly when thread B acquires lock on the same instance of Counter, it enters into read barrier and reads value of count from main memory and sees all updates.
Same visibility effect goes for volatile read / writes as well. All variables updated prior to write to volatile will be flushed to main memory and all reads after volatile variable read will be from main memory.