volatile Keyword in Java

Java Programming Java8Object Oriented Programming

The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory.

Accessing a volatile variable synchronizes all the cached copied 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 19-Sep-2018 11:32:22
Advertisements