Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a multithreaded Java program, does each thread have its own copy of System.out?

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?

like image 528
user1258361 Avatar asked Apr 04 '12 16:04

user1258361


People also ask

What is multithreading in Java?

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.

Is a process single threaded or multithreading?

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?

How many threads are in a Java program?

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?

How to handle multiple threads created using available methods in Thread class?

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 −


1 Answers

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.

like image 93
Gray Avatar answered Oct 31 '22 04:10

Gray