Pregunta

Every now and again I want to use System.out.prinln to debug things instead of using a debugger, or I want a simple program to write to standard output so that I can log something without taking the time to get proper logging set up. I've noticed that sometimes my text winds up getting printed out of order. E.g.:

System.out.println("A");
System.out.println("B");    
System.out.println("C");

might result in

A
C
B

being printed.

I'm pretty sure I'm not crazy, so I have two questions:

  1. Why does this happen?
  2. What's an easy way I can keep this from happening?

EDIT: More information:

I'm running unit tests that build Lucene queries with JUnit. To print them out I've written this class:

public class LogHelper { //TODO-DAVID remove
    public static final boolean ENABLED = true;
    public static final boolean DISABLED = false;

    private boolean enabled;

    public LogHelper(boolean enabled){
        this.enabled = enabled;
    }

    public synchronized void debug(String someString){
        if(enabled){
            System.out.println(someString);
        }
    }
}

I tried making 'debug()' synchronized, just in case multiple threads were calling it, but strange printing still occasionally happens out of order.

¿Fue útil?

Solución

That will never happen unless the printing is happening in different threads. Then execution order may be indeterminate. If, on the other hand, you're writing to System.out and System.err and seeing jumbled output, that's because those are two different streams that happen to write to the exact same output by default, and one or the other may come out first, especially due to buffering or other considerations.

Otros consejos

I'm sure will never happen with your example on a single thread..

Anyway, make sure you don't have function calls inside System.out.println( that might create new thread..specially functions that call OS System.. they usually mess up...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top