Talking about volatile variable in Java

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:

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:

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:

Obviously, the ChangeListener thread will not be able to update the value of the COUNT variable, and therefore our program will run forever.

5/5 - (1 vote)

Add Comment