Volatile Keyword in Java | Volatile Variable

Volatile keyword in Java is a non-access modifier that can be applied with a variable declaration.

It tells the compiler the value of variable may change at anytime. The syntax to declare volatile keyword with field or variable is as follows:

Syntax:

volatile data_type variable_name;

For example:

volatile int count;

When we use the volatile keyword with a variable, all the threads always read the value of variable directly from the main memory i.e. from the stack where variable lives.

No thread will keep a local copy of that variable in its cache. The volatile keyword cannot be used with classes and methods.

Volatile Variable in Java


Java allows threads to access the shared variable. When a thread changes the value of shared variable, it is possible that another thread may see the old value of shared variable for some time. This is because threads are allowed to cache shared data.

That is, each thread keeps its own separate local copy of the shared value. When a thread changes the value of shared variable, the separate local copies of shared value in the caches of other threads are not immediately changed.

Therefore, other threads can continue to view the old value of shared variable due to data inconsistency problems.

However, in the case of a synchronized method or block, threads are forced to update their caches with the most current values of the variables. So, it is always safe while using shared variable inside synchronized code.

It is also possible to use a shared variable safely outside of the synchronized code when a variable is declared with a volatile keyword. In this case, each thread will always use the main copy of the variable.


Any change in the value of variable will immediately be visible to all threads. This makes it safe for threads to use volatile shared variable outside of synchronized code. Look at the below figure to understand concept better.

declaration of variable with Volatile Keyword in Java

Let’s understand it with an example.

volatile boolean flag = true;

For every read request, a thread always reads the value of volatile variable from the main memory. For every write/modify request, a thread writes or modifies the value of volatile variable to the main memory.

In other words, a thread does not store the value of a volatile variable in its cache. All read and write operations will be performed from and to the main memory, not cache.

When to use Volatile Keyword?


There are the following reasons to use volatile keyword in Java programs. They are:

1. A volatile keyword is only useful when we are working a multi-threaded environment and the value of variables is to be shared among threads. There is no use of volatile keyword in the non-multithreading environment.

2. We can use a volatile variable to stop a thread by using the value of variable as a flag. If the flag is set then thread will continue to run. If another thread clears the flag, thread will stop.

Since two threads share the flag, so the thread will get its updated value from the main memory on every read.

3. It can be used as an alternative way of performing synchronization in Java.

4. All threads will read the updated value of volatile variable after completion of the write operation. If we do not use the volatile keyword, different threads may read different values.


Let’s take an example program based on the above points.

Program code:

public class A extends Thread
{
// Declare a volatile variable named flag with initial value true.
 public volatile boolean flag = true;

@Override
public void run(){
 System.out.println("Thread starts running");	
 
// Since the flag is volatile, so for every read, thread will read its latest value from main memory.
 while(flag)
 {
  try{
	System.out.println("Thread going to sleep");
	Thread.sleep(1000);
  }
 catch(InterruptedException ie){
	ie.printStackTrace(); 
 }
  }
 System.out.println("Thread stopped..."); 
}
public void stopThread(){
  this.flag = false;	
 }
}
public class MyThread {
public static void main(String[] args) {
 A a = new A();
 Thread t = new Thread(a);
 t.start(); // Thread started.
 
try {
 Thread.sleep(3000); // Main thread will sleep for 3 seconds.	
}
catch(InterruptedException ie){
 ie.printStackTrace();	
}
// Stop thread.
// Call stopThread() using reference variable a.
   a.stopThread();
	}
}
Output:
      Thread starts running
      Thread going to sleep
      Thread going to sleep
      Thread going to sleep
      Thread stopped...

Advantage of  Volatile Keyword


The primary advantage of volatile keyword is we can overcome data inconsistency problems.

Disadvantage of Volatile Keyword


The disadvantage of using volatile keyword is that creating and maintaining a separate copy for every thread increases the complexity of programming and creates performance problems.

Hence, if there is no specific requirement, it is never recommended to use volatile keyword in Java program because it is an almost deprecated keyword.

Key Points to Remember about Volatile Keyword


1. We can declare only a class member variable (instance or static variable) as volatile.

2. A local variable cannot be declared as volatile because a local variable is always private to the thread which is never shared with other threads.

3. Volatile variable can not be declared as final because volatile keyword is used with a variable that changes. If you try to declare, it will give compile-time error.

4. Volatile keyword cannot be declared with classes and methods because it is illegal.

5. A volatile keyword provides a lock-free mechanism for synchronizing access to an instance or static variable.

6. All read and write requests are done from the main memory, not from local thread cache. That is, read and write are atomic.

7. A volatile keyword works great when the value of shared variable is only modified by one thread. If the value of variable is modified by more than one thread, volatile keyword cannot protect from data race conditions. For example, ++ operator over volatile variable is not thread-safe.

8. If a volatile variable is a reference to object, it may point to null as well. For example:

volatile Integer i = null;  // it’s allowed.

9. Volatile keyword is faster, cheaper and gives better performance than synchronized block because it does not need to get any monitor or lock to access variable.

10. It helps to reduce the risk of memory consistency error.


Hope that this tutorial has covered the basic points of volatile keyword in Java with example program. I hope you will have understood the use of volatile variable.

If you get any incorrect in this tutorial, please inform to our team through email. Your email will be precious to us.
Thanks for reading!!!
Next ⇒ Java Thread Pool⇐ PrevNext ⇒

Please share your love