What is the use of volatile keyword in java?

Use of volatile keyword in Java – The volatile keyword is used to declare a variable volatile, so, the variable can be accessed directly from the memory not from intermediary cache. For example,

If you declare a variable volatile, then it will be directly accessed from the memory where it resides and not from the intermediary any kind of cache.

You know that compiler does optimization internally and it may cache variables e.g. in register or something.

Example: Let’s say there is an int variable that is shared by two threads. One is updating the value and other is reading the value. If the int variable is not volatile then there may be a chance that other threads that read the variable, don’t get updated value. If it is volatile, then for sure second thread will read the value directly from the memory and that will be updated one.

NOTE: If you will use JDK 7 or 8 , you may not be able see the behaviour, If you really want to see the effect of volatile keyword in java program, then try with JDK 6 or earlier.

As a best practice, always declare a variable volatile if required. One example I have mentioned, that is multiple threads read and write a variable.

Related Posts