Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is System.out.println thread-safe by default? [duplicate]

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):

  1. Can I rely on this behavior (using different JVMs)?
  2. Is there some documentation that I missed which describes this behavior?
like image 256
TobiSH Avatar asked Oct 01 '15 06:10

TobiSH


1 Answers

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.

like image 160
T.J. Crowder Avatar answered Oct 24 '22 06:10

T.J. Crowder