Friday, May 28, 2010

Volatillity of "volatile" in Java Multi-threading

Many people say volatile keyword in Java is poorly understood and underused and I am not the exception. I would try to throw some light over it to make it simple to understand.

volatile has its meaning in context of multi-threading. Many explain it as

"If a variable is declared as volatile then it is guaranteed that any thread which reads it see the most recently written value."

Well first we need to understand that each thread has private memory (cache) in addition to access to shared main memory. Thread contains a copy of shared object, present in main memory, in its cache. There is time-to-time synchronization between cached value and value in main memory; it happens on event of obtaining or releasing lock. But this is not true if variable is declared as volatile. Volatile variables are read and written to main memory only. So there is no need of synchronization and any thread trying to read value will read from main memory.

Having said that there is still an open question of dead lock. Well access to volatile variable is like accessing a synchronized block without holding lock.

No comments:

Post a Comment