0

I am trying to parse a file at work but for some reason my for loop does not execute an entire iteration of tasks before going on to the next iteration.

I have a sample code here that shows the same issue and I think that if I can fix this simple example I will be able to fix my more complex issue at work.

Sample code :

package loops;
public class Loops {
    public static void main(String[] args) {
    System.out.println("here goes");
    for(int i=0;i<1000;i++){
        System.err.println(i);
        if(i==i){
            System.out.println(i+1);
        }
    }
}}

The above code runs and prints the iteration of the loop "i" in red. It goes through the if statement and prints the i+1 in black. My issue is that instead of being red black red black it finishes the if statements long before it finishes the for loop "i" printouts. Is there any way to make this loop go in order? I have tried to make it sleep after each iteration but that does not fix it.

Thanks.

CDahn
  • 1,795
  • 12
  • 23
Jeremy
  • 15
  • 4

2 Answers2

0

Stdout is buffered, stderr isn't. Print both to stdout or both to stderr, don't mix them.

CDahn
  • 1,795
  • 12
  • 23
0

This because both System.out and System.err could be buffered streams. This means that writes are not executed right when data is placed onto the stream but rather in chunks.

Try to flush the output right after each print:

System.out.println(...);
System.out.flush();

In this way you will force the stream to flush their buffer before executing other instructions. This may come with a performance cost.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • added System.out.flush() inside the for loop with the same results. – Jeremy Jun 19 '14 at 00:18
  • I see now that you are correct Jack. Adding System.out.flush() and System.err.flush() does fix the issue. Just needed to flush both of them. – Jeremy Jun 19 '14 at 00:25