What does the modifier volatile in Java do?

Java 8Object Oriented ProgrammingProgramming

The volatile modifier is used to let the JVM understand that a thread accessing the variable should always merge its own personal copy of the variable with the original in the memory.

Accessing a volatile variable synchronizes all the cached copy of the variables in the main memory. Volatile can only be applied to instance variables, which are of type object or private. A volatile object reference can be null.

Example

public class MyRunnable implements Runnable {
   private volatile boolean active;
   public void run() {
      active = true;
      while (active) {    
      }
   }
   public void stop() {
      active = false;  
   }
}
raja
Published on 10-Jan-2018 12:08:09
Advertisements