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 comment: