When should we use Volatile variables

In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased. In this case the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.

When a field is declared volatile, the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations. Volatile variables are not cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always returns the most recent write by any thread.

If we run this code with normal variable declaration of variable keepRunning, it might get hung. But if we make keepRunning as Volatile, the program will run as expected.

class TestVolatile extends Thread{
    //volatile
      boolean keepRunning = true;
 
    public void run() {
        long count=0;
        while (keepRunning) {
            count++;
            //System.out.println(count);
        }
 
        System.out.println("Thread terminated." + count);
    }
 
    public static void main(String[] args) throws InterruptedException {
        TestVolatile t = new TestVolatile();
        t.start();
        Thread.sleep(1000);
        System.out.println("after sleeping in main");
        t.keepRunning = false;
        System.out.println("keepRunning set to " + t.keepRunning);
        t.join();
        System.out.println("The end");
    }
}

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *