Curcuma_
Curcuma_

Reputation: 901

Error output stream is concurrent with standard output stream when printing in Java

When this code gets executed, it produces scrambled outputs with no particular order between System.out.print() and System.err.print(). Why is that so?

for (int i = 0; i < 100; i++) {
    System.out.print(i+" ");
    System.err.print(i+"+");
}

Why is the standard error output stream is concurrent with standard output stream when printing in Java?

Upvotes: 1

Views: 226

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

System.out and System.err are two different streams and so, they work at different times. The problem you're experiencing here is because in console applications both streams are flushed to the same output buffer, which is the console. Each stream can flush at different time, the console buffer will care about the synchronization for you, but this leads to unpredictable results.

If you want/need to have a single and better managed output for both streams, use a logger library like log4j2 or logback, that already solves these problems.

Upvotes: 3

Related Questions