System.out returns the "standard" output stream - a PrintStream. The javadoc of PrintStream tells me nothing about thread safety but looking at the source of the OpenJDK and the OracleJDK tells me that println is synchronized.
/**
* 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();
}
}
That fits pretty well to my experiences: Calling System.out.println() never created 'mixed' output when calling from different threads.
So my question(s):
Since the documentation of PrintStream, its superclass FilterStream, and its superclass OutputStream all fail to say anything about thread safety or synchronization, in theory you cannot rely on it, it's not part of the contract.
I think it would be surprising if someone produced a PrintStream class that didn't do what Oracle's does in this regard, but I've been surprised before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With