Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top