I was running the following small program and I noticed that sometimes the stack trace is not necessarily printed between 'before stack trace' and 'after stack trace' but sometimes it is at the very beginning or at the end.
It looks like printStackTrace instead of printing the stack trace directly runs a thread for doing it....any idea?
No, your debugging output goes to one place (stdout) and your stacktrace goes to a different place (stderr). If both of those are your console, then the buffering of the two streams may obscure the actual order they were written to.
I predict that if you use "System.err.println" instead of "System.out.println" then you won't see that behaviour any longer.