0

I've noticed many times that when I have a certain line throwing an exception, if I put sysout's before it I will get a strange ordering of text in the console:

I get the first line of the exception, say java.lang.ArrayIndexOutOfBoundsException: -1 followed by the sysout line which is then followed by the rest of the stacktrace. If I have multiple sysouts, the previous ones will go above the Exception name.

java.lang.ArrayIndexOutOfBoundsException: -1
hello world
at line 5
at line 6
...

Why does this happen?

Aequitas
  • 2,205
  • 1
  • 25
  • 51
  • possible duplicate of http://stackoverflow.com/questions/4255743/how-to-keep-sysout-and-syserr-streams-from-intermixing – jdigital Nov 25 '15 at 23:33
  • as per the duplicate answer, the reason that system out appears AFTER the start of the stack trace, even though it was "printed first" is that the system.out and system.err internally have buffers which flush at different times. the purpose is probably that it's more efficient overall to buffer and flush periodically than to send each write to the actual system out / err for every write. – slipperyseal Nov 25 '15 at 23:38
  • also, this is just a guess, but maybe the first line of the stacktrace prints, and then building the actual stack trace (looking up the line numbers, traversing the stack), takes a while, maybe causing the thread to yield, and then the "hello world" system out buffer gets a chance to print in between. – slipperyseal Nov 25 '15 at 23:43
  • is an exception print being printed using System.err? – Aequitas Nov 26 '15 at 00:10
  • Also why would the exception be before AND after a sysout? The duplicate question shows ALL of one type being printed first and then the other, this is not the case here, as all but one sysout gets printed then part of the exception gets printed then the final sysout and then the exception – Aequitas Nov 26 '15 at 00:13
  • @Aequitas i think i answered that (or a possible reason). Printing a stack trace probably consists of two phases. Printing the class name and message, and then building and printing the actual trace. – slipperyseal Nov 26 '15 at 01:25
  • Also, why does it behave differently in different cases or stack overflow questions? because different JVMs, different operating systems, threading, star alignment and old fashioned luck. Since the interleaving order is not defined or predictable, it's best not to rely on any specific behaviour. – slipperyseal Nov 26 '15 at 01:37

0 Answers0