Use of Volatile Keyword in JAVA
There is a keyword in java named as ‘Volatile ‘. Keywords are basically reserve words which have specific meaning. The value of volatile variable will never be cached thread-locally: all reads and writes will go straight to “main memory”;. It means, there is no cache, volatile is an indicator to java compiler and thread that do not cache value of this variable in which read and write operation directly performs through main memory. The volatile keyword guarantees that all the threads should see the same value of a specified variable.
If you are working with the multithreaded programming, the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it’s updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn’t know anything about the values changed by another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever threads are updating the values, it is updated to the main memory. So, other threads can access the updated value.
Below is the example which demonstrates this properly:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
class VolatileExample extends Thread { private volatile int volatileValue; public VolatileExample (String str){ super(str); } public void run() { int i; for(i = 0; i< 3; i++) { try { System.out.println(getName() + " : "+i); if (getName().equals("First ")){ volatileValue= 10; System.out.println( "Test Value : " + volatileValue); } if (getName().equals("Second ")){ System.out.println( "Test Value : " + volatileValue); } Thread.sleep(1000); } catch (InterruptedException exception) { exception.printStackTrace(); } } } } public class ExampleMain{ public static void main(String args[]) { new VolatileExample ("First ").start(); new VolatileExample ("Second ").start(); } } |
Output:
Each thread has its own stack, and so its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables in its own memory. The volatile keyword is used to say to the jvm “Warning, this variable may be modified in another Thread”. Without this keyword the JVM is free to make some optimizations, like never refreshing those local copies in some threads. The volatile keyword forces the thread to update the original variable for each variable.
Leave a Reply