Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is System.err.println is printed before then System.out.println?

Tags:

java

I was tryingout Logger example from wiki chain of responsibility article. running the example in idea it prints:

Sending to stderr: An error has occurred.
Writing to stdout: Entering function y.
Writing to stdout: Step1 completed.
Sending via email: Step1 completed.
Writing to stdout: An error has occurred.
Sending via email: An error has occurred.

but when i put a break point in stderrs writeMessage

class StderrLogger extends Logger {
    public StderrLogger(int mask) {
        this.mask = mask;
    }

    protected void writeMessage(String msg) {
        System.err.println("Sending to stderr: " + msg);//break out here
    }
}

it prints all the messags except std err, there is no threads involved here, then why its printing stderr at first line in run case?.

like image 355
Acha Bhoot Avatar asked Apr 23 '26 23:04

Acha Bhoot


1 Answers

System.err flushes differently from System.out in Eclipse.

Try this in Eclipse:

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

This will randomly print out most of the OUTs and most of the ERRs in big chunks. However, this is an Eclipse issue, not a Java issue, as pointed out by Evgeniy Dorofeev.

If you run this sample program in a terminal, you will notice the correct output, without any flushing needed.

Update: Thanks to Evgeniy Dorofeev for pointing this out! The flushing not working is an Eclipse problem!

like image 81
Andrei Bârsan Avatar answered Apr 26 '26 13:04

Andrei Bârsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!