0

In continuation with this article. Could someone please explain why does one of the below code snippet demonstrates the visibility problem (Thread keeps running forever) while the other does not on the same windows 64 bit machine.

Note: I suspect that it could have something to do with println method of PrintStream class in System class being synchronized. Could someone explain the same. How does it impact the visibility.

Code snippet 1 - Demos visibility problem (Thread t1 keeps running as expected)

public class Test2 extends Thread {
    boolean keepRunning = true;
    public static void main(String[] args) throws InterruptedException {
        Test2 t = new Test2();
        t.start();
        Thread.sleep(1000);
        t.keepRunning = false;
        System.out.println(System.currentTimeMillis() + ": keepRunning is false");
    }
    public void run() {
        while (keepRunning) 
        {}
    }
}

Code snippet 2 - Does not demo visibility problem (Thread t1 stops running which is not expected)

public class Test2 extends Thread {
    boolean keepRunning = true;
    public static void main(String[] args) throws InterruptedException {
        Test2 t = new Test2();
        t.start();
        Thread.sleep(1000);
        t.keepRunning = false;
        System.out.println(System.currentTimeMillis() + ": keepRunning is false");
    }
    public void run() {
        int count = 0;
        while (keepRunning) 
        {
         System.out.println(count++);
        }
    }
}
K2M
  • 1
  • `System.out.println` is typically (although not required to be) synchronized. There is something inside the method which establishes a happens-before. – Andy Turner Aug 05 '20 at 12:39
  • Thanks Andy. Thats what I want to understand how does below println implementation establishes happens-before rule. Is synchronized block enough to achieve that. public void println(String x) { synchronized (this) { print(x); newLine(); } } – K2M Aug 05 '20 at 12:44
  • Yes, a synchronized block would do that. The language spec describes other things which establish HB. – Andy Turner Aug 05 '20 at 12:58

0 Answers0