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?
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.
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.
Once a thread enters dead state it cannot be restarted.
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.
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."
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