I have a sample code for Scheduled Executor Service, taken from Oracle's site. It creates a ScheduledExecutorService with core pool size o 1. It does 2 jobs: First it starts a repeated task executed at fixed intervals and then it kills the same task and the service itself after a delay.
ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(1);
//This will keep executing the task at fixed interval
ScheduledFuture<?> futureTask = scheduledService.scheduleAtFixedRate(new RepeatedTask(), initialDelay, interval, TimeUnit.SECONDS);
//A future task is returned which can be used to cancel the execution after sometime
//Here we will cancel our repeated task after 100 seconds
scheduledService.schedule(new TaskStopper(futureTask, scheduledService), 100, TimeUnit.SECONDS);
The repeated task code:
public class RepeatedTask implements Runnable{
int count = 0;
@Override
public void run() {
count++;
System.out.println(count + ". Beep");
}
}
The stop task
@Override
public void run() {
mFutureTask.cancel(true);
System.out.println("Task stopped");
mExecutorService.shutdownNow();
boolean shutDown = mExecutorService.isShutdown();
if(shutDown) {
System.out.println("Executor shutdown");
}else {
System.out.println("Executor not shutdown");
}
}
I want to understand, how does it work with a single thread in the thread pool. Since our executor service performs two tasks and starts them both almost at the same time, shouldn't we have 2 threads i.e. a ScheduledExecutorService with core pool size of 2.
It works fine though. I just want to understand why it works fine with a single thread.