Ankit
Ankit

Reputation: 4644

Scheduled Executor Service with single thread

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.

Upvotes: 3

Views: 3429

Answers (1)

Rishabh Sharma
Rishabh Sharma

Reputation: 862

For any thread pool (including ScheduledThreadPool), number of threads can be less than number of tasks. Thread pools internally have a queue of tasks, in which a task will have to wait if no thread is available to execute the task.

In your example, at t=100 seconds, two tasks need to be executed. Since only one thread is available, it executes the first task (while second one waits in the queue). Once the first task is complete, the thread picks the second task from the queue and completes it.

You could print out the thread id in both the tasks and can verify that they are indeed being processed by the same thread.

Edit: So basically the task scheduled at fixed interval is executed multiple times with fixed intervals in between. During these intervals, our single thread in the pool is idle and is able to pick other tasks for execution. That's how a single thread executes both the tasks.

Upvotes: 5

Related Questions