Tuesday, 2 April 2013

Tricky interview question on Volatile keyword in Java

As we all know that, 
1) Volatile prevents the threads from caching variable values locally.
2)  It plays key role in inter thread communications.

But there is a tricky question on volatile i.e 'Is there any side affects on non volatile variables if we use volatile '. Have a look at the below program to know the answer.

public class TestVolatile implements Runnable
{
int num1 = 10;
int num2 = 30;
 volatile int sum;
 
public void run() 
{
           // First thread performs write operations on sum and num1
          // Second thread performs read operations to get latest values from main memory and                        //then perform write
sum = num1 + num2;
num1 = 300;
   System.out.println(Thread.currentThread().getName()+" - "+sum);
    System.out.println(Thread.currentThread().getName()+" - "+num1);
   System.out.println(Thread.currentThread().getName()+" - "+num2);
}
public static void main(String args[])
{
TestVolatile TestVolatile =  new TestVolatile();
Thread thread1 = new Thread(TestVolatile);
Thread thread2 = new Thread(TestVolatile);
thread1.setName("Thread1");
thread2.setName("Thread2");
thread1.start();
thread2.start();
}
}

You would have noticed that, num1 value of one thread is effecting sum computation of another thread . Does this mean that using volatile also has side-effects to the usage of non-volatile variables? YES.

Reason: Any writes in the thread that wrote to the volatile before doing so will be seen by the thread reading the volatile after having done so

Refer below links for more info: