3

Can anyone tell me why I always have this strange output after running this loop? Is this a threading issue or what?

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

->OUTPUT:

    err: 1
    out: 0
    err: 2
    err: 3
    err: 4
    out: 1
    out: 2
    out: 3
    out: 4
    err: 5
    out: 5
    err: 6
    out: 6
    err: 7
    err: 8
    out: 7

    out: 8
    err: 9
    out: 9
    err: 10
    out: 10
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
imanis_tn
  • 1,150
  • 1
  • 12
  • 33

2 Answers2

11

Your terminal is running your application and has two file descriptors connected to it, one for stdout and one for stderr. It then has to read data that your application is outputting on these file descriptors and render it on the screen. There is no guarantee how the terminal application (or the OS for that matter) implements this interaction. Imagine that terminal actually has 2 threads reading from stdout and stderr in parallel. The order in which these 2 threads will get data from fds and onto the screen is not guaranteed to be sequential to when your app outputs.

MK.
  • 33,605
  • 18
  • 74
  • 111
  • This is interesting. I downvoted initially because I thought this was wrong. It was my assumption that Java was buffering `System.out` and `System.err` was not buffered. But if I run a class from the command line, I see `"oeoeoeoeoeoeoeoeoe"` perfectly interleaved. This means that it is the application that is doing something different. Fascinating. Thanks @MK. +1 – Gray Mar 29 '12 at 22:50
  • @Gray I think you are right that System.err is not buffered, but I don't think these are mutually exclusive. I was trying to give a general feeling as to why these will interleave. Also I think printing \n might cause flushing? In that case the behavior of stdout and stderr would be the same. – MK. Mar 30 '12 at 02:41
  • My comment was not disagreeing with you. I agree entirely. By default the PrintStream does not flush when it sees a '\n'. I'm not sure how `System.out` and `System.err` were configured. – Gray Mar 30 '12 at 13:15
3

Standard output and standard error have separate buffers. The interleaving is normal. Try flushing the output stream after each print call.

Tim Bender
  • 20,112
  • 2
  • 49
  • 58