Saturday, May 27, 2017

Why volatile is not enough?

When thread uses some variable, JVM optimizes variable read/write by caching that value in thread local space, but this gives rise to unique problem Data Inconsistency. Lets see how



As from above image there are 2 threads, each using same variable, Now JVM copies that variable to thread local storage, Now lets say thread 1 modifies it, now thread 2 has no way to see that change as it already has its own copy of variable. So by using volatile we tell JVM that don't create local copy of variable instead let them use the original variable.

Now is this enough? I mean just using volatile all read / writes to variable will be correct or variable will be in consistent state, well NO, volatile only guarantees consistency in READS not WRITES or in other word it only guarantees Happens-Before relationship.

So How we gain both Read And Write consistency?

1) Synchronized / Lock 

We can use synchronized access to variable by Synchronized block or By using lock object
But this yields performance impact.

2) Atomic Wrappers

 Newer version of Java has Atomic Wrappers for primitive types like AtomicInteger which guarantees Atomic Read/write to the variable in lock free manner so this is much faster than Synchronized  or Locks.