Coders Packet

Volatile keyword in Java.

By Vedanti Ravish Deshmukh

In this tutorial, We will study the Volatile keyword in Java. We will learn what is the volatile keyword. Why and how we use it. Also, how it is connected to the thread.

What is a volatile keyword in Java?
A volatile keyword is a type of keyword in Java that keeps thread-safe. It modifies the value of the variable when used by different threads at a time.


What is Thread in Java?
Thread in Java allows the program to run efficiently by doing multiple tasks at a time. It also doesn't interrupt the main program.


Volatile keyword stores its value in main memory. So, whenever a programmer reads or writes the value using a volatile variable then it will be read from or written in the main memory respectively, and not from the CPU cache.
It is only used with variables and not with classes or methods. It prevents the compiler to reorder the code and also assures visibility.

Public class Main
{
static int a=47;
} 

When 'Volatile' keyword is not used.

As we can see that without the 'Volatile' keyword when multiple threads access the variable value 'a' and if one thread changes the value then it is not known by the other thread and thus it leads to data inconsistency.

Public class Main
{
static volatile int a=47;
}

Similarly, static variables are a class member and thus it is shared with every object. There will only be one copy of it in the main memory and the volatile variable will never be stored in the cache. Every read and writes will be done from the main and data inconsistency will not be faced.

When is the Volatile keyword used?

  • Volatile keyword is only used with variables. It is illegal when volatile is used with classes or methods.
  • Synchronization in Java can also be achieved with volatile keywords.
  • Users will see the updated value of the volatile variable after completing the write operation. If one is not using the volatile keyword then the user may see different values of the variable.
  • When volatile is used compiler prevents code from reordering.
  • When not used, the value of a variable can be written in the cache memory and instead of the main memory.

Difference Between Volatile and Synchronization keyword in Java:

Difference between Volatile and Synchronization keyword in Java.

Example of Volatile keyword in Java:

package pkgvolatile;

/**
 *
 * @author VD
 */

import static java.lang.String.format;
 
public class Volatile{
 
    private volatile static int x = 0;
    // Driver method
    public static void main(String[] args) 
    {
        new Read_the_data().start();     // calling thread 'Read_the_data'
        new Write_the_data().start();   // calling thread 'write_the_data'
    }
 
    static class Read_the_data extends Thread 
    {
        @Override
        public void run() 
        {
            int y = x; // Here x is a variable and y is a local variable.
            while (y < 10) 
            {
                if (y != x) 
                {
                    System.out.println(format("Changed Global value: %s", x));
                    y = x;
                }
            }
        }
    }
 
    static class Write_the_data extends Thread 
    {
        @Override
        public void run() 
        {
            int y = x;
            while (x < 10) 
            {
                System.out.println(format("Incremented Global value: %s", y + 1));
                x = ++y;
                try 
                {
                    Thread.sleep(450);   //sleep() method of Thread is used to sleep for the specified duration.
                } 
                catch (InterruptedException e) 
                {
                    e.printStackTrace();   //printStackTrace() method in Java is used to handle exceptions and errors.
                }
            }
        }
    }
}

 

Download project

Reviews Report

Submitted by Vedanti Ravish Deshmukh (vedantid30)

Download packets of source code on Coders Packet