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)