System.out.println and System.err.println out of order

Viewed 23811

My System.out.println() and System.err.println() calls aren't being printed to the console in the order I make them.

public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
        System.out.println("out");
        System.err.println("err");
    }
}

This produces:

out
out
out
out
out
err
err
err
err
err

Instead of alternating out and err. Why is this?

7 Answers

They are different streams and are flushed at different times.

If you put

System.out.flush();
System.err.flush();

inside your loop, it will work as expected.

To clarify, output streams are cached so all the write goes into this memory buffer. After a period of quiet, they are actually written out.

You write to two buffers, then after a period of inactivity they both are flushed (one after the other).

In Eclipse specifically, you now have, with Eclipse 2019-09 synchronized standard and error output in console.

The Eclipse Console view currently can not ensure that mixed standard and error output is shown in the same order as it is produced by the running process.

For Java applications the launch configuration Common Tab now provides an option to merge standard and error output.
This ensures that standard and error output is shown in the same order it was produced but at the same time disables the individual coloring of error output.

https://www.eclipse.org/eclipse/news/4.13/images/merge-process-output.png

I have used thread to print the output of System.out and System.err sequentially as:

    for(int i = 0; i< 5; i++){
        try {
            Thread.sleep(100);
            System.out.print("OUT");
            Thread.sleep(100);
            System.err.print("ERR");
        }catch (InterruptedException ex){
            System.out.println(ex.getMessage());
        }
    }
Related