Usage of volatile keyword

  • Eclipse: Oxygen
  • Java: 1.8

The usage of volatile keyword is used to declare the variables that will be modified by different threads. All changes in the variable will be directly written back to the memory.

This keyword cannot be applied to class or method. It can only be used with a variable.

In the following program, a non-volatile variable may result in an infinite loop, without volatile variable compiler will re-order the code, free to cache value of volatile variable instead of always reading from main memory.

In another example, where a volatile variable can be used is to fix this problem.

When the thread is dependent on the variable always use the volatile keyword. It means this variable will not be cached by the thread.

This guarantees that value of the volatile variable will always be read from main memory and not from Thread’s local cache.

Contributed by: Poonam Tomar

Full stack Java Developer

   Buy me a coffee!



Download file

Leave a Reply

Notify of
Close Menu