I was using Executors.newSingleThreadExecutor()
and I am a bit confused about how it works. Let's say I am not calling shutdown()
. I looked at the available source code
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/Executors.java#Executors.newSingleThreadExecutor%28%29
and it says:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
So, my assumption is after a task is executed even if I do not call shutdown() the thread should be stopped and a new Thread should be created if I call a task again on the same executor. But when I ran a code it gave a different output. Can someone explain the behavior? Here's the code:
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService es = Executors.newSingleThreadExecutor();
Future<String> f = es.submit(new MyService());
System.out.println(f.get());
System.out.println("Done executing 1st run");
Thread.sleep(3000);
f = es.submit(new MyService());
System.out.println(f.get());
es.shutdown();
}
public class MyService implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("Old name: " + Thread.currentThread().getName());
Thread.currentThread().setName("Mythread: " + Math.random());
return Thread.currentThread().getName();
}
}
Here's the output:
Old name: pool-1-thread-1
Mythread: 0.061937241356848194
Done executing 1st run
Old name: Mythread: 0.061937241356848194
Mythread: 0.49829755639701667
I thought the Old name:
in the 4th line should be pool-1-thread-1
as the existing thread has a timeout of 0L. So, a new thread should be created. Instead it is using the previous thread