Showing posts with label Volatile. Show all posts
Showing posts with label Volatile. Show all posts

Volatile in Java

Volatile is a important topic in Java where we will use in Multi-Threading. Volatile keyword will be used in variables and the value will be changed simultaneously by other threads. This makes compiler to read the value from main memory instead of reading from registers. If we say simply value will not be cached in register. And also this makes each thread to get current value of the variable and each thread will not change values unexpectedly.

The main use of Volatile is stops caching the values of variables in registers. When every time value got changes, immediately flushes the value to RAM where other threads can access the updated value directly.

Here we may think of synchronized which will holds a lock for an Object. Where as here its not suitable since we are just reading and updating value when we use Volatile keyword. Volatile can be applied on Object or Primitive types.

Before Java version 1.5 Volatile is not guarantee the atomicity of a 64-bit long load. For example while thread updating some 64 bit long and other reads can get half of old values and half of new values which will reside in improper value. Later from Java 1.5 onwards atomicity of volatile longs is guaranteed on 64-bit hardware also.

Lets see small example of using Volatile keyword which will works along with Multi Threading.



public class MyVolatile {
 
 static volatile long value = 1234567890L;
 
 public static void main(String[] args) {
  new Thread(new IncrementVolatileValue()).start();
  new Thread(new CheckVolatileValue()).start();
 }
 
 static class CheckVolatileValue implements Runnable{
  @Override
  public void run() {   
   for(int i=0;i<10;i++){
    System.out.println("Value Same : "+value);
   }
  }
 }
 
 static class IncrementVolatileValue implements Runnable{
  @Override
  public void run() {
   for(int i=0;i<10;i++){
    System.out.println("Value Incremented : "+value++);
   }
  }
 } 
}



In above example we are incrementing volatile variable in single Thread and by other Thread we are reading the value and printing in loop for checking the change of value. Both the threads are having its own stack and its own copy of variables in its own memory. Volatile keyword is used to say to the JVM "Warning, this variable can be changed by other Thread" so don't cache it, rather read every time from RAM.

So one who programmer need to decide whether he needs to use Volatile or not according to his business logic's.