I'm writing a multithreaded Java program where each thread potentially needs its standard output redirected to a separate file. Each thread would have its own file. Is it possible to redirect System.out on a "per-thread" basis or are changes to System.out global across all threads?
Is it possible to redirect System.out on a "per-thread" basis
No it is not possible. System.out
is static and there is one per JVM that is loaded as part of the system classloader when the JVM initially boots. Although of course using proper logging calls per-thread is recommend, I assume there are reasons why you can't do this. Probably a 3rd party library or other code is what is using System.out
in this manner.
One thing you could do (as a radical suggestion) is to make your own PrintStream
that delegates to a ThreadLocal<PrintStream>
. But you will need to @Override
the appropriate methods called by your application to get it to work per-thread.
Lastly, if you are asking this because you are worried about concurrency, System.out
is a PrintStream
so it is already synchronized
under the covers and can be used safely by multiple threads.