Friday, July 29, 2016

Volatile keyword


Cached variables

Just think about a multithreaded application. In this kind of applications they are using cached variables for working. Normally threads may copy variables from CPU to cache memory to access them fast. These variables are called cached variables. This operation may increase application performances. If your system have multi cores, then variables will be cached to different CPU's cache memories. 

At the time, if one thread changes the value of a variable which is in one cache memory, it can't be guaranteed that it will get updated in other threads. because different threads are using different cached memories. That is why we need volatile variables.


What is Volatile ?

  • Volatile is a non access modifier
  • You can use it only with variables(fields), you CANNOT use it with classes and methods.

Volatile variables

  • If you define a variable with volatile modifier; it says to Java compiler, don't cache the value of this variable and it should read only from the main memory. So Java compiler doesn't copy this variable to cache memories and always uses original copy of the variable. 
Just think for moment, in your multi threaded application, you just want to update any value and that updated value need to be used in another thread. In multi threaded application, it will run different threads in different cores in multi core processors. At the time each thread cache its variables to the processor cache (Look at the top of this post)

If I change one value in one thread which is running in one CPU, may not be updated in another thread. This thread may be using old value. This will make troubles to the application. 

The best option to avoid this, make that variable volatile

When to use volatile variables

  • You can use volatile variables in concurrency operations like I mentioned above.
It warn, not to create a local copy of the variable in cache memories and always use the original value from main memory. Then only one value is there for many threads.

If you look at my Singleton Design pattern post, it can be seen double checked thread safe initialization of singleton design pattern. In this initialization we make the only instance as volatile.

  • Volatile variables are using to make double and long values atomically. 
You know that, both long and double primitives are 64bit. Some platforms make 64bit in two steps. This is not atomic. If you define variables with volatile, it makes that variables atomic.

  • Volatile boolean is used to terminate threads.
Volatile variable can be used as a flag. If you want to terminate a thread safety by using another thread, you can use this. Why you need volatile keyword is it will always get updated the status of the thread.

Look at the following example

package com.app.threads;

public class ThreadClose extends Thread {

   private volatile boolean stop = false;
 
   public void run() {
      while(!stop){
          System.out.println("Hi");
          closeThread();
      }
   }
 
   public void closeThread(){
      stop = true;
   }
}


Then you may ask why it uses volatile ? Simple answer is you need not to have synchronized block if you are using a volatile instance as I mentioned. 

Disadvantages of volatile

  • It may decrease your CPU performances.
Because it doesn't use cache memory, it always uses main memory. It is more valuable than accessing cache memory. Then it will decrease your system's performance.

But volatile keyword is less weight than using a synchronized block. Synchronized block required more CPU power than volatile. 

More about volatile

  • Volatile keyword can only be used with variables.
  • Volatile variable cannot be final.
  • Volatile object can be null.
  • There is no use of volatile keywords in non threaded applications.

Volatile vs Synchronized