Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print output and an error message to the console

Tags:

java

eclipse

I'm trying to print output and an error message to the console. but sometimes the sequence of output changes, first it prints the error message & then it prints the simple message can anybody help me understand why is it happening as such? the sequence of output changes most of the time. There is no consistency in the printed output. I'm using eclipse IDE & the output I get is as follows.

I have tried to print the following code,

System.out.println("simple message");  
System.err.println("error message");  

the expected result is this:

simple message

error message

but the actual result is this:

error message

simple message

like image 780
tushar_lokare Avatar asked Jan 08 '19 05:01

tushar_lokare


2 Answers

System.out.println() and System.err.println() are different Streams of execution. Output Streams are cached so all the write goes into this memory buffer. After a period of quiet, they are actually written out. Here is a for loop that essentially shows your error again:

for(int x = 0; x <= 5; x++) {
    System.out.println("Out");
    System.err.println("Err");



}

In order to "flush" the Streams call .flush() each time through the loop:

for(int x = 0; x <= 5; x++) {
    System.out.println("Out");
    System.out.flush();
    System.err.println("Err");
    System.err.flush();


}

In this for loop, the out message, and the err message will initially print, but on each flush your out messages would print first, and then your err messages. The output will be something such as:

OutErr
Out
Out
Out
Out
Out

Err
Err
Err
Err
Err

And that is because System.out and System.err are executing on different Streams.

like image 196
Simeon Ikudabo Avatar answered Oct 17 '22 02:10

Simeon Ikudabo


Even if you flush your streams after writing, these streams are read by different threads in Eclipse and if the writes are almost simultaneously, it happens that the thread for reading stderr is executed before the thread for stdout even if the corresponding write to stdout happened first.

Since Java 1.5 there is the ProcessBuilder class and with this it could be solved in Eclipse by redirecting stderr to stdout during launching - but Eclipse's feature to show stderr output in a different color would be broken by this.

You may add your opinion to https://bugs.eclipse.org/bugs/show_bug.cgi?id=32205

like image 1
Till Brychcy Avatar answered Oct 17 '22 02:10

Till Brychcy