1

I know very well what volatile variable is, but, I have never seen any setup that failed, if volatile is not used. As per the accepted answer's case in thread(Do you ever use the volatile keyword in Java?), tried replicating the setup, but program works perfectly fine. See below.

class VolatileTest extends Thread{
    boolean isRunning = true;

    public void run(){
        while(isRunning){
            System.out.println("volatile test");
        }
    }

}

public class App 
{
    public static void main( String[] args ) throws InterruptedException
    {
        VolatileTest volatileTest = new VolatileTest();
        volatileTest.start();

        Thread.sleep(2000l);
        volatileTest.isRunning = false;
    }
}

One thread runs and prints "volatile test" if isRunning is true(I was in assumption it will be cached). In main thread I am changing the value of isRunning. Here, other thread is able to read change after 2 sec. This setup never failed.

My question is:

  1. How this is working? is native OS doesn't allow caching?

  2. Is there any example I can get which actually fails?

Bikas Katwal
  • 1,895
  • 1
  • 21
  • 42

0 Answers0