System.Out.Println and System.Err.Println Out of Order

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

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).

Random printing order for System.out & System.err calls

I believe this is because you are writing to two different outputs (one is standard out and the other standard error). These are probably handled by two different threads at runtime to allow writing to both during java execution. Assuming this is the case, the cpu task scheduler is not going to execute the threads in the same order every time.

You should never get this functionality if all of your output is going to the same output stream (ie everything goes to standard out or everything goes to standard err). You will never be guaranteed execution order of standard error vs standard output.

System.out.println(); and System.err.println(); printing interchangeably

Those are two different output streams, the order in which they are invoked is not the only thing that matters. They might flush their contents towards the console at a different time.

Edit: after a bit more digging this answer indicates that it might be an (unresolved) eclipse bug as well. It's been open for 10 years, don't get your hopes up on a fix anytime soon.

Unexpected output using System.err.println() in java

They are different streams and they flushed at different times.

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

You can take help from this Stack-question

System.out.println/System.err.println not working

It's a common occurrence that a file is missing some contents if you don't close the file after writing. There are finalizer() methods in many OutputStream subclasses that do close the stream, but they don't always have a chance to get called as is the case here.

The main thread releases the gate and quits immediately, the other threads quickly run their course and at that point the VM is closed and you can't trust that things finished correctly.

The original code is convoluted and it's hard to "fix" something that's broken from the ground up. For instance in real code you wouldn't have 2 threads competing to write into the same file. That just doesn't make sense.

In any case the best "fix" for this would be for the main thread to wait for the other threads to finish (instead of sleeping), and then close the file as below.

Thread t1 = new Thread(() -> ...
Thread t2 = new Thread(() -> ...
t1.start();
t2.start();

t1.join();
t2.join();
out.close();


Related Topics



Leave a reply



Submit