Monday, May 10, 2010

Volatile Modifiers in Java

Volatile Modifier

       The volatile modifier requests the Java Virtual Machine to always access the shared copy of the variable so the its most current value is always read. If two or more threads access a member variable, and one or more threads might update that variable’s value, and all of the threads do not use synchronization to read and/or write the variable value, then that member variable must be declared volatile to ensure all threads should get the updated value.
       We will discuss the java volatile modifier using following example.
       In our example, we take two threads Thread T1 and Thread T2 accessing member variable x of class C and here Thread T1 is not using synchronization and Thread T2 uses synchronization. If Thread T2 updates value of variable x from 0 to 1. But if the variable x is not declared as volatile then meanwhile Thread T1 tried to access variable then it will get value of variable x as 0. But as variable x is updated to 1 by Thread T2, To avoid this mess the variable x should be declared as volatile so Thread T1 should get updated value 1.


  1. Java 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

    How to use synchronized keyword in Java