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?
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process. Threads can be created by using two mechanisms : 2. We create a class that extends the java.lang.Thread class.
A process always is a single threaded until it does’t implemented multi threading behaviour. if More than one thread are involved in process it may give higher execution but also program complexity and maintainability are also high . What is multithreading in java? Originally Answered: What is the use of multithreading in Java?
Each program has at least one thread. If we create a simple program to print “Hello world”, it means at least one thread will exist in the program. We will discuss it later in detail. What is multithreading in Java?
This approach provides more flexibility in handling multiple threads created using available methods in Thread class. You will need to override run ( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run () method −
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With