Is multi-thread output from System.out.println interleaved

JavaMultithreadingSynchronizationPrintstream

Java Problem Overview


If multiple threads call System.out.println(String) without synchronization, can the output get interleaved? Or is the write of each line atomic? The http://docs.oracle.com/javase/6/docs/api/java/io/PrintStream.html#println(java.lang.String)">API</a> makes no mention of synchronization, so this seems possible, or is interleaved output prevented by buffering and/or the VM memory model, etc.?

EDIT:

For example, if each thread contains:

System.out.println("ABC");

is the output guaranteed to be:

ABC
ABC

or could it be:

AABC
BC

Java Solutions


Solution 1 - Java

Since the API documentation makes no mention of thread safety on the System.out object nor does the PrintStream#println(String) method you cannot assume that it is thread-safe.

However, it is entirely possible that the underlying implementation of a particular JVM uses a thread-safe function for the println method (e.g. printf on glibc) so that, in reality, the output will be guaranteed per your first example (always ABC\n then ABC\n, never interspersed characters per your second example). But keep in mind that there are lots of JVM implementations and they are only required to adhere to the JVM specification, not any conventions outside of that spec.

If you absolutely must ensure that no println calls will intersperse as you describe then you must enforce mutual exclusion manually, for example:

public void safePrintln(String s) {
  synchronized (System.out) {
    System.out.println(s);
  }
}

Of course, this example is only an illustration and should not be taken as a "solution"; there are many other factors to consider. For example, the safePrintln(...) method above is only safe if all code uses that method and nothing calls System.out.println(...) directly.

Solution 2 - Java

The OpenJDK source code answers your question:

public void println(String x) {
    synchronized (this) {
  	    print(x);
        newLine();
   	}
}

Reference: http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/39e8fe7a0af1/src/share/classes/java/io/PrintStream.java

Solution 3 - Java

As long as you don't change the OutputStream via System.setOut it is thread safe.

Though it is thread safe you can have many threads writing to System.out such that

Thread-1
  System.out.println("A");
  System.out.println("B");
  System.out.println("C");
Thread-2
  System.out.println("1");
  System.out.println("2");
  System.out.println("3");

can read

1
2
A
3
B
C

among other combinations.

So to answer your question:

When you write to System.out – it acquires a lock on the OutputStream instance - it will then write to the buffer and immediately flush.

Once it releases the lock, the OutputStream is flushed and written to. There would not be an instance where you would have different strings joined like 1A 2B.

Edit to answer your edit:

That would not happen with System.out.println. Since the PrintStream synchronizes the entire function, it will fill the buffer and then flush it atomically. Any new thread coming in will now have a fresh buffer to work with.

Solution 4 - Java

Just to clarify, say you have two threads, one that prints "ABC" and another that prints "DEF". You will never get output like this: ADBECF, but you could get either

ABC
DEF 

or

DEF
ABC

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEllen SpertusView Question on Stackoverflow
Solution 1 - JavamaericsView Answer on Stackoverflow
Solution 2 - JavatwimoView Answer on Stackoverflow
Solution 3 - JavaJohn VintView Answer on Stackoverflow
Solution 4 - JavaparkovskiView Answer on Stackoverflow