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?
I’m writing a multithreaded Java program where each thread potentially needs its standard output
Share
No it is not possible.
System.outis 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 usingSystem.outin this manner.One thing you could do (as a radical suggestion) is to make your own
PrintStreamthat delegates to aThreadLocal<PrintStream>. But you will need to@Overridethe 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.outis aPrintStreamso it is alreadysynchronizedunder the covers and can be used safely by multiple threads.