Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java + Eclipse: Synchronize stdout and stderr

I use Eclipse. When I have an application like this:

write 20 times 'Hello World\n' to stdout
write 'ERROR\n' to stderr
write 5 times 'Hello  World\n' to stdout

The output looks many times like this:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
...
Hello World
Hello World
Hello World
ERROR

Is there a way to synchronize these two output streams? Of course without waiting a few milliseconds after the block of 20 times Hello World and waiting a few milliseconds after printing ERROR.

like image 525
Martijn Courteaux Avatar asked May 24 '10 12:05

Martijn Courteaux


3 Answers

Believe it or not, flushing is not a solution here....

If a stream leads to "an abstraction provided by the underlying operating system" (e.g. a disk drive or console) then remaining bytes "are passed to the operating system for writing; it does not guarantee that they are actually written..." (see the OutputStream documentation). The key here is that the OS can handle flushes from different streams in different orders if it so chooses.

I just had this happen in my program. I had an error message appear between two normal message, both of which had flushed before the error message did.

So the question remains, is there a built-in way to synchronize two streams? Or do we have to handle that manually?

like image 162
Vimes Avatar answered Nov 20 '22 17:11

Vimes


For "serious" use, I prefer not writing directly to System.out/System.err, since it hard-codes the destination, and it also it uses the rather quirky PrintStream (is it a byte stream or a character stream?). If you wrap the output streams in your own PrintWriter, you can then set it to flush automatically - the second argument in the constructor is auto-flush.

E.g.

PrintWriter out = new PrintWriter(System.out, true);
PrintWriter err = new PrintWriter(System.err, true);

out.println("Hello world");
//this will flush after writing the end of line

See

  • java.io.PrintWriter, javadoc Java SE 6
  • Differences between PrintWriter and PrintStream, SO question
like image 36
mdma Avatar answered Nov 20 '22 17:11

mdma


System.out and System.err are ordinary PrintStream objects (which provide a flush() method), so try System.out.flush() and System.err.flush().

like image 3
aioobe Avatar answered Nov 20 '22 18:11

aioobe