Reputation: 273
According to the document regarding newFixedThreadPool in Executors, I found
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.
While I run my code, I detected my fixed sized threadPool with capacity 5 keep generating threads as time goes like pool-1-thread-3212
which suppose to be pool-1-thread-5 or less
So I wonder when does ExecutorService decide one of its thread fails and launch new one.
Could anyone guide me the reason why this happen?
Upvotes: 3
Views: 1844
Reputation: 38910
If you did not implement exception handling properly, thread will die depending on the way you submit the task to ExeuctorService.
Since you are using FixedThreadPool
, fixed number of threads have to maintained in case of thread death.
if you use execute instead of submit, thread will die in case of unhandled exceptions.
Sample code to simulate the exception & thread death using execute()
import java.util.concurrent.*;
import java.util.*;
public class ThreadDeath{
public ThreadDeath()
{
System.out.println("creating service");
ExecutorService service = Executors.newFixedThreadPool(2);
for ( int i=0; i < 5; i++){
service.execute(new Runnable(){
public void run(){
int a=4, b = 0;
System.out.println("Thread Name before divide by zero:"+Thread.currentThread().getName());
System.out.println("a and b="+a+":"+b);
System.out.println("a/b:"+(a/b));
}
});
}
service.shutdown();
}
public static void main(String args[]){
ThreadDeath test = new ThreadDeath();
}
}
Now check the thread names in output:
creating service
Thread Name before divide by zero:pool-1-thread-1
Thread Name before divide by zero:pool-1-thread-2
a and b=4:0
a and b=4:0
Exception in thread "pool-1-thread-1" Thread Name before divide by zero:pool-1-thread-3Exception in thread "pool-1-thread-2"
a and b=4:0
Thread Name before divide by zero:pool-1-thread-4
Exception in thread "pool-1-thread-3" a and b=4:0java.lang.ArithmeticException: / by zero
Thread Name before divide by zero:pool-1-thread-5
Now just replace execute
with submit
while submitting the Runnable
task. The exception will be swallowed and output is like this: ( You can see only two threads, since FixedThreadPool size is 2)
creating service
Thread Name before divide by zero:pool-1-thread-1
a and b=4:0
Thread Name before divide by zero:pool-1-thread-2
a and b=4:0
Thread Name before divide by zero:pool-1-thread-1
a and b=4:0
Thread Name before divide by zero:pool-1-thread-2
Thread Name before divide by zero:pool-1-thread-1
a and b=4:0
a and b=4:0
For more details on Thread creation, refer to this grepcode link:
private boolean addWorker(Runnable firstTask, boolean core)
Upvotes: 3