The volatile variable in Java has the effect of informing the change of its value to different threads if the variable is being used in multiple threads.
For you to understand more, I made an example as follows:
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 36 37 38 39 |
public class VolatileExample { private volatile static int COUNT = 0; public static void main(String[] args) { new ChangeListener().start(); new ChangeMaker().start(); } static class ChangeListener extends Thread { @Override public void run() { int value = COUNT; // When value of COUNT variable is less than 5, this thread will loop forever to check the value of this variable while (value < 5) { if (value != COUNT) { System.out.println("Count variable changed to : " + COUNT); value = COUNT; } } } } static class ChangeMaker extends Thread { @Override public void run() { int value = COUNT; while (COUNT < 5) { System.out.println("Increasing value of count variable to " + (value + 1)); COUNT = ++value; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } } |
In this example, we have two threads that are using the value of the COUNT variable, the first thread (ChangeMaker) that will change the value of the COUNT variable, and the second thread (ChangeListener) will listen for that change. The variable COUNT will be declared as a volatile variable so that it can be notified of its change to the ChangeListener thread.
Result:
1 2 3 4 5 6 7 8 9 10 |
Increasing value of count variable to 1 Count variable changed to : 1 Increasing value of count variable to 2 Count variable changed to : 2 Increasing value of count variable to 3 Count variable changed to : 3 Increasing value of count variable to 4 Count variable changed to : 4 Increasing value of count variable to 5 Count variable changed to : 5 |
As you can see, whenever the value of COUNT changes, the ChangeListener thread will update that change immediately.
If I now don’t declare COUNT variable as the volatile variable, the result will be as follows:
1 2 3 4 5 6 |
Increasing value of count variable to 1 Count variable changed to : 1 Increasing value of count variable to 2 Increasing value of count variable to 3 Increasing value of count variable to 4 Increasing value of count variable to 5 |
Obviously, the ChangeListener thread will not be able to update the value of the COUNT variable, and therefore our program will run forever.