00:00

ScheduledThreadPoolExecutor in Java: Policies and Examples

Last updated:

ScheduledThreadPoolExecutor is the JDK class behind Executors.newScheduledThreadPool(). It combines a thread pool with a delay queue, so it can run tasks after a delay or periodically.

This tutorial covers the class's constructors and the three policies it adds, settings that the ScheduledExecutorService interface does not expose.

1. What Is ScheduledThreadPoolExecutor?

It is a class in java.util.concurrent, added in Java 5. It extends ThreadPoolExecutor and implements ScheduledExecutorService.

Internally it behaves as a fixed-size pool of corePoolSize threads working from an unbounded delay queue. Because of that, changing maximumPoolSize has no useful effect, and setting the core size to zero is almost never a good idea.

2. ScheduledThreadPoolExecutor Hierarchy

ScheduledThreadPoolExecutor hierarchyScheduledThreadPoolExecutor extends ThreadPoolExecutor and implements ScheduledExecutorService.«class»ThreadPoolExecutorexecute(…), shutdown()getQueue(), getPoolSize()«interface»ScheduledExecutorServiceschedule(…)scheduleAtFixedRate(…)scheduleWithFixedDelay(…)«class»ScheduledThreadPoolExecutorthis pagesetRemoveOnCancelPolicy(boolean)setExecuteExisting…Policy(boolean)setContinueExisting…Policy(boolean)extendsimplementsinterfaceclass

Swipe sideways to see the whole diagram.

  • ThreadPoolExecutor (class): Supplies the worker threads, rejection handling and monitoring methods.
  • ScheduledExecutorService (interface): Defines schedule(), scheduleAtFixedRate() and scheduleWithFixedDelay().

3. Constructor Details

ConstructorDescription
ScheduledThreadPoolExecutor(int corePoolSize)Default thread factory and AbortPolicy.
(int, ThreadFactory)Custom thread factory, for example to name threads.
(int, RejectedExecutionHandler)Custom handler for tasks rejected after shutdown.
(int, ThreadFactory, RejectedExecutionHandler)Both customisations.

4. The Three Policies

MethodDefaultEffect
setRemoveOnCancelPolicyfalseWhen true, a cancelled task leaves the queue immediately instead of waiting until its delay elapses.
setExecuteExistingDelayedTasksAfterShutdownPolicytrueOne-shot delayed tasks still run after shutdown().
setContinueExistingPeriodicTasksAfterShutdownPolicyfalsePeriodic tasks are cancelled by shutdown().

5. Example: Cleaning Up Cancelled Reminders

A reminder service schedules reminders an hour ahead, then the user deletes two of them.

ReminderQueueCleanup.java
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ReminderQueueCleanup {

    // Schedules three reminders an hour away, cancels two, and reports the queue size
    static int queuedAfterCancelling(boolean removeOnCancel) {
        ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1);
        scheduler.setRemoveOnCancelPolicy(removeOnCancel);

        ScheduledFuture<?> r1 = scheduler.schedule(() -> System.out.println("call dentist"), 1, TimeUnit.HOURS);
        ScheduledFuture<?> r2 = scheduler.schedule(() -> System.out.println("renew passport"), 1, TimeUnit.HOURS);
        scheduler.schedule(() -> System.out.println("water plants"), 1, TimeUnit.HOURS);

        r1.cancel(false);
        r2.cancel(false);
        int queued = scheduler.getQueue().size();
        scheduler.shutdownNow();     // discard the remaining reminder
        return queued;
    }

    public static void main(String[] args) {
        System.out.println("removeOnCancel=false -> tasks still queued: " + queuedAfterCancelling(false));
        System.out.println("removeOnCancel=true  -> tasks still queued: " + queuedAfterCancelling(true));
    }
}
Output
removeOnCancel=false -> tasks still queued: 3
removeOnCancel=true  -> tasks still queued: 1

How the code works

  1. With the default policy, cancelled tasks stay in the delay queue until their hour is up. They will not run, but they still use memory.
  2. With setRemoveOnCancelPolicy(true), cancel() removes the task from the queue straight away.
  3. For services that schedule and cancel many long-delay tasks, enabling the policy prevents cancelled tasks from piling up.

6. Example: What Survives shutdown()

ShutdownPolicies.java
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ShutdownPolicies {

    public static void main(String[] args) throws InterruptedException {
        ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(2);
        System.out.println("Run delayed tasks after shutdown?   "
                + scheduler.getExecuteExistingDelayedTasksAfterShutdownPolicy());
        System.out.println("Keep periodic tasks after shutdown? "
                + scheduler.getContinueExistingPeriodicTasksAfterShutdownPolicy());

        AtomicInteger syncRuns = new AtomicInteger();
        scheduler.schedule(() -> System.out.println("End-of-day backup ran after shutdown"), 200, TimeUnit.MILLISECONDS);
        scheduler.scheduleAtFixedRate(syncRuns::incrementAndGet, 100, 100, TimeUnit.MILLISECONDS);

        scheduler.shutdown();        // delayed task kept, periodic task cancelled
        scheduler.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("Periodic sync runs: " + syncRuns.get());
    }
}
Output
Run delayed tasks after shutdown?   true
Keep periodic tasks after shutdown? false
End-of-day backup ran after shutdown
Periodic sync runs: 0

How the code works

  1. The two getters print the default shutdown policies: delayed tasks run, periodic tasks do not.
  2. The backup is a one-shot delayed task, so it still runs 200 ms later even though shutdown() was called first.
  3. The periodic sync is cancelled at shutdown, before its first run at 100 ms, so it never runs.
  4. awaitTermination() waits until the delayed backup has finished. Use shutdownNow() to discard delayed tasks too.

7. Common Mistakes and Best Practices

  • Using setMaximumPoolSize(). It has no useful effect here; size the pool with corePoolSize.
  • Forgetting delayed tasks at shutdown. shutdown() still waits for pending one-shot tasks by default.
  • Piles of cancelled tasks. Enable setRemoveOnCancelPolicy(true) when you cancel many long-delay tasks.
  • Exceptions in periodic tasks. One failed run suppresses all later runs; catch exceptions inside the task.
  • Real-time expectations. Tasks run no sooner than their delay, but there is no guarantee how soon after.

8. Summary

  • ScheduledThreadPoolExecutor extends ThreadPoolExecutor and implements ScheduledExecutorService.
  • It works as a fixed-size pool of corePoolSize threads with an unbounded delay queue.
  • Remove-on-cancel is off by default; turn it on to free cancelled tasks immediately.
  • By default, shutdown() keeps one-shot delayed tasks and cancels periodic ones.

Related Tutorials

9. References