Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

March 13, 2011

Volatile variable in java

According to Kathy Sierra :

" The volatile modifier tells the JVM that a thread accessing the variable must
always reconcile its own private copy of the variable with the master copy in
memory "

My understanding :
In normal scenario, In a multi-threaded environment, every thread keeps a local copy of instance variable and if a thread makes some change to the variable, the changed value would be visible to that thread only.

But if we declare a variable as volatile, the variable is stored in main memory and not in local memory of any thread. So, if the value of the variable is changed by any thread, it will be changed in the main memory and would be visible to all threads accessing that variable.

2 comments:

Gor's eye said...

keyword "volatile" is an information to JVM to not cache specified variable - so even, when it is "cached" in processor's registry, JVM will read it from main memory - so that each thread will see the most up-to-date value for volatile variables

so that means that what you suggested is not true:
"...if a thread makes some change to the [non-volatile] variable, the changed value would be visible to that thread only..." - no, the change will be visible also to other threads, but there is no guarantee, that these threads will use this new value (because of multithread issues) - "volatile" will take care of it

javin paul said...

Many Developers often mistake volatile as replacement of synchronized keyword which is not true. volatile keyword in Java
can guarantee visibility and ordering and prevent compiler to reorder code statement but as you mentioned can not guarantee atomicity which can only be achieved either by locking or by using Atomic classes from java.util.concurrent.atomic package. one more important thing to note is behavior of volatile keyword before and after java5. visibility and ordering guarantee is achieved by using happens-before relationship and every write in volatile variable happens before every read in volatile variable in java.Writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire

Javin
How to use synchronized keyword in Java