Java Programming Tutorials

Java programming tutorials with many code examples!

Java ScheduledThreadPoolExecutor Example


How to use Java ScheduledThreadPoolExecutor to schedule tasks for one-time or repeated execution? In this post we’re going to show newer alternative to Timer/TimerTask pair.


In the previous post we’ve shown how to use Java Timer with TimerTask, a pair that allows to schedule tasks. With advent of java.util.concurrent this can be done using SchedulerThreadPoolExecutor service, which is a recommended approach when multiple worker threads are needed or flexibility of underlying ThreadPoolExecutor.

For scheduling purposes SchedulerThreadPoolExecutor has two groups of methods:

  • ScheduledFuture schedule(…)
    For one-time execution scheduling.
  • ScheduledFuture scheduleAtFixed(…)
    For repeated, periodic executions.

In the following example we’re going to use SchedulerThreadPoolExecutor with a pool of three threads and schedule sample tasks. Then we’re going to wain for a few seconds, to let them do some work, and then shutdown the executor with their tasks:


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;

public class ScheduledThreadPoolExecutorExample {

    private static class DataCollector implements Runnable {

        private static int nth = 0;

        private final int id = ++nth;

        public void run() {
            System.out.printf("DataCollector %d collecting data...%n", id);
            try {
            } catch (InterruptedException e) {
                // ignore
            System.out.printf("DataCollector %d finished.%n", id);

    public static void main(String[] args) throws InterruptedException {
        int nThreads = 3;
        System.out.printf("Starting Scheduled Thread Pool of %d threads%n", nThreads);
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(nThreads);
        for (int i = 1; i <= 8; ++i) {
            executor.scheduleAtFixedRate(new DataCollector(), 100, 800, MILLISECONDS);



The code is pretty simple. We haven’t used ScheduledFuture that is result of scheduleAtFixedRate() method, but it could be used to e.g. obtain results from a task or cancel it.

Here’s shortened result of running the above code:

Starting Scheduled Thread Pool of 3 threads
DataCollector 2 collecting data...
DataCollector 1 collecting data...
DataCollector 3 collecting data...
DataCollector 2 finished.
DataCollector 4 collecting data...
DataCollector 1 finished.
DataCollector 5 collecting data...
DataCollector 3 finished.
DataCollector 6 collecting data...
DataCollector 4 finished.
DataCollector 1 finished.
DataCollector 2 finished.
Was it helpful? Share!