Tuesday, November 3, 2015

Volatile Keyword

Volatile is a modifier keyword. Volatile can be use with only variables not with class or method names. When a variable declared as volatile it means, the value of the variable should be taken from main memory of its stack not from cached thread-locally. A variable value will be modified by different threads. This keyword has to declare in synchronized block.



public class TryCatch {

       private static volatile int volatileVariable = 0;

       public static void main(String[] args) {
              new Listener().start();
              new Maker().start();
       }

       static class Listener extends Thread {
              @Override
              public void run() {
                     int LocalVariable = volatileVariable;
                     while (LocalVariable < 5) {
                           if (LocalVariable != volatileVariable) {
                                  System.out.println("Got Change for volatileVariable : " + volatileVariable);
                                  LocalVariable = volatileVariable;
                           }
                     }
              }
       }



       static class Maker extends Thread {
              @Override
              public void run() {

                    int localVariable = volatileVariable;
                     while (volatileVariable < 5) {
                           System.out.println("Incrementing volatileVariable to " + (localVariable + 1));
                           volatileVariable = ++localVariable;
                           try {
                                  Thread.sleep(1000);
                           } catch (InterruptedException e) {
                                  e.printStackTrace();
                           }
                     }
              }
       }

}


No comments:

Post a Comment

Thank you for your comments.