Friday 5 October 2012

Java Volatile Variable

Java Volatile Variable
Most of the time we used to hear one term called volatile variable. What is the difference between a normal variable and a variable varaible?
For understanding the concept of volatile variable, it is recommended that we have some basic idea of locking and visibility.
Locking and Visibility: Imagine a thread called Thread A enters into a synchronized block, it acquires a lock on the object also simultaneously one more thread called Thread B try to read the same object state, Can Thread B read the instance variables or will it get new value which is updated by thread A. The answer is Thread B will get all the values seen by Thread A while entering into the synchronized block. Synchronization is not only responsible for locking the object but also for memory visibility. When Thread A leaves a synchronized block, it will update all state variables to the memory.  Since processor has lots of registers and caches, the state of a variable may not be updated all the time to the memory. Synchronization allows you to forcefully updating the sate of a variable to the memory before leaving the synchronization block.
Volatile variable: Since normal variable may not give the up-to-date value of a variable in a concurrent thread scenario, we have to use synchronization for getting the up-to-date value. There is another way to get the up-to-date value of a variable by declaring it as volatile variable. If we declare a variable as volatile, compiler and runtime will take it with special care and never store these variables in caches. So a read to a volatile variable always give a value which is most recent write by another thread.
Locking can guarantee both visibilty and atomicity, but volatile variable can guarantee only visibility. So remember it is not recommended to relay heavily on volatile variables.
Hope this Helps!!

No comments:

Post a Comment