I was trying to create a few scenarios to demonstrate visibility issues while sharing variable across threads. And I noticed that in almost all the cases I tested, if inside
This behaviour is implementation specific. In OpenJDK, println
's body is synchronized altough the API does not state that it is.
PrintWriter is synchronized
public void println(String x) {
synchronized(this) {
this.print(x);
this.newLine();
}
}
Two sequential calls of System.out.println()
in main thread and in second thread create a synchronization order between two threads. That means that all actions (in your case it is variable update), that happened in main thread before releasing a monitor (exiting synchronized method) will be seen by the code, executed in second thread after it acquires a monitor (enter synchronized method).
In simple words, yes, calling System.out.println()
makes this synchronization.