Is System.out.println thread safe by default?

System.out returns a "standard" output stream - a PrintStream . Javadoc PrintStream says nothing about thread safety, but looking at the OpenJDK source, OracleJDK tells me that println syncing.

 /** * Prints a String and then terminate the line. This method behaves as * though it invokes <code>{@link #print(String)}</code> and then * <code>{@link #println()}</code>. * * @param x The <code>String</code> to be printed. */ public void println(String x) { synchronized (this) { print(x); newLine(); } } 

This is very well suited for my experience: Calling System.out.println() never produced β€œmixed” output when called from different threads.

So my question (s):

  • Can I rely on this behavior (using different JVMs)?
  • Is there some kind of documentation that I skipped that describes this behavior?
+5
source share
1 answer

Since the FilterStream documentation, its FilterStream superclass FilterStream and its OutputStream superclass cannot say anything about thread safety or synchronization, theoretically you cannot rely on it, this is not part of the contract.

I think it would be surprising if someone created a PrintStream class that did not do what Oracle is doing in this regard, but I was surprised earlier.

+6
source

Source: https://habr.com/ru/post/1232674/


All Articles