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; }
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?
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. } } } } }
Submitted by Vedanti Ravish Deshmukh (vedantid30)
Download packets of source code on Coders Packet
Comments