Sathish Jayapal Sathish Jayapal - 1 month ago 16
Java Question

java synchronized Thread clarification

The answer for this program will have to be "Changing done" after 5 secs, but I get "Changing done" and "DONE". I do not have the getDone method as synchronized. Any ideas what am I doing for the thread to finish processing.

public class Main {
private static boolean done = false;
private static int count;

public static void main(String[] args)throws InterruptedException {
new Thread(() -> {
while (!getDone()) {
count = count + 1;
}
System.out.println("DONE!!!!");
}).start();
Thread.sleep(5000);
System.out.println("Changing done");
synchronized (Main.class) {
done = true;
}
}

public static boolean getDone() {
return done;
}
}

Answer

I do not have the getDone method as synchronized. Any ideas what am I doing for the thread to finish processing.

As you mention, there is no explicit memory synchronization between the done as seen by your spinning thread and the main thread. Although the main thread crosses a write memory barrier when exiting the synchronized block, there is no explicit read memory barrier crossed by the spinning thread.

However, there are many ways for a thread to see updated information. If the operating system swaps the thread out of its running processor, the cached memory may be lost so when the thread gets swapped back it, it will request done from central memory and will see the update.

Also, although your example code doesn't show it, if you make calls to other synchronized methods (such as System.out.println()) or logging calls, they also can cause done to be updated.