Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are dead threads replaced in an ExecutionContext and/or Java thread pool?

When a thread dies due to an exception, what happens to this thread? If it is inside a thread pool, does it spawn a new thread? I'm interested in what happens in scala ExecutionContext, but since an ExecutionContext wraps a java thread pool, I think that Java users will also know the answer.

For example, if I create an ExecutionContext wrapping a FixedThreadPool(100), if one thread dies, does he thread pool replace the thread?

like image 361
vicaba Avatar asked Jun 19 '16 16:06

vicaba


People also ask

What happens when a thread dies in Java?

A thread dies naturally when its run() method exits normally. For example, the while loop in this method is a finite loop--it will iterate 100 times and then exit. A thread with this run() method will die naturally after the loop and the run() method completes. Thread myThread = new MyThreadClass(); myThread.

Can we use dead thread in Java?

Once the thread completes its run() method and dead, it cannot be brought back to thread of execution or even to runnable state. Invoking start() method on a dead thread causes runtime exception.

Can a dead thread be started again in Java?

Once a thread enters dead state it cannot be restarted.

Which method restart a dead thread?

Since a Thread can not be restarted you have to create a new Thread everytime. A better practice is to separate the code to run in a thread from a Thread 's lifecycle by using the Runnable interface. Just extract the run method in a class that implements Runnable . Then you can easily restart it.


1 Answers

The thread itself cannot spawn a new thread after it dies, however the thread pool can replace it. For example, the thread pool created by Executors.newFixedThreadPool() replaces dead threads when needed. From the documentation for Executors.newFixedThreadPool():

"If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks."

like image 113
Warren Dew Avatar answered Oct 20 '22 01:10

Warren Dew