I am trying to understand visibility issue in multthreading(Java) with one example which I copied from Internet, however, it looks like not working.
Expectation: while loop should keep running.
Result: It breaks even though I am not using volatile.
Code:
public class VolatileDemo extends Thread{
boolean flag = true;
@Override
public void run() {
while (flag){
System.out.println(Thread.currentThread().getName() + ":: Task 2");
}
}
public static void main(String[] args) throws InterruptedException {
VolatileDemo volatileDemo = new VolatileDemo();
volatileDemo.start();
Thread.sleep(1000);
volatileDemo.flag = false;
System.out.println(Thread.currentThread().getName() + ":: Main Task");
}
}
My understandng so far is this loops should keep running(once thread enters in it) because flag update will not be visible to other thread. It should resolve with volatile keyword, but it's not happening. So, I think my understaing is not clear on this. Could someone explain it with proper example.