Java Volatile Keyword

public class VolatileTest {

    private volatile int MY_INT = 0;

    public static void main(String[] args) {
        VolatileTest volatileTest = new VolatileTest();
        new ChangeListener().start();
        new ChangeMaker().start();
    }

    class ChangeListener extends Thread {
        @Override
        public void run() {
            int local_value = MY_INT;
            while ( local_value < 5){
                if( local_value!= MY_INT){
                    System.out.printf("Got Change for MY_INT : %d", MY_INT);
                    System.out.println();
                    local_value= MY_INT;
                }
            }
        }
    }

    class ChangeMaker extends Thread{
        @Override
        public void run() {

            int local_value = MY_INT;
            while (MY_INT <5){
                System.out.printf("Incrementing MY_INT to %d", local_value+1);
                System.out.println();
                MY_INT = ++local_value;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) { e.printStackTrace(); }
            }
        }
    }
}

With the volatile keyword the output is :

Incrementing MY_INT to 1
Got Change for MY_INT : 1
Incrementing MY_INT to 2
Got Change for MY_INT : 2
Incrementing MY_INT to 3
Got Change for MY_INT : 3
Incrementing MY_INT to 4
Got Change for MY_INT : 4
Incrementing MY_INT to 5
Got Change for MY_INT : 5

Without the volatile keyword the output is :

Incrementing MY_INT to 1
Incrementing MY_INT to 2
Incrementing MY_INT to 3
Incrementing MY_INT to 4
Incrementing MY_INT to 5

…..And the change listener loop infinitely…

Previous Next

Leave a Reply

Your email address will not be published. Required fields are marked *