Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Race between System.out and System.err in java [duplicate]

Please consider this java code:

public class CMain {
    public static void main(String[] args){

        for (int i = 0; i < 10; i++) {
            System.out.println("A");
            System.err.println("B");
        }

    }
}

By a quick look at the code, some of us may think the output has to be the print of As and Bs alternatively. However is not! It is a random appearance of 10 A characters and 10 B ones. Something like this:

enter image description here

Why is that? and what is the solution for it so that the As and Bs gets displayed alternatively ( A B A B A B ...) Before I ask this question, I checked several other similar questions for solution and non worked for my case! I have brought some of them here:

  • Synchronization and System.out.println
  • Java: synchronizing standard out and standard error
  • Java: System.out.println and System.err.println out of order PS. I am using Eclipse as my IDE
like image 835
C graphics Avatar asked Feb 28 '13 22:02

C graphics


2 Answers

Why does this happen?

This is because out and err are two different output streams. However, both of them print on console. So you do not see them as different streams. Moreover, when you do out.println(), it is not guaranteed that you will see the output on the console as soon as the statement gets executed. Instead, the strings are usually(depends on the system) stored in an output buffer (if you will) which is processed later by the system to put the output from the buffer onto the screen.

Solution :(

Although, as Eng.Fouad pointed out that you can use setOut(System.err) or setErr(System.out) to make them ordered, I would still not suggest doing that when you are actually putting this in an application (only use it for debugging purposes).

What the proposed solution does is that it will end up using only one stream for both the standard output and the standard error, which I do not think is a good thing to do.

like image 196
Ankit Avatar answered Oct 20 '22 02:10

Ankit


They are different OutputStreams. If you really need to guarantee the order of printing them, use:

System.setErr(System.out);

or

System.setOut(System.err);
like image 5
Eng.Fouad Avatar answered Oct 20 '22 02:10

Eng.Fouad