ScheduledThreadPoolExecutor in Java: Policies and Examples
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
Swipe sideways to see the whole diagram.
ThreadPoolExecutor(class): Supplies the worker threads, rejection handling and monitoring methods.ScheduledExecutorService(interface): Definesschedule(),scheduleAtFixedRate()andscheduleWithFixedDelay().
3. Constructor Details
| Constructor | Description |
|---|---|
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
| Method | Default | Effect |
|---|---|---|
setRemoveOnCancelPolicy | false | When true, a cancelled task leaves the queue immediately instead of waiting until its delay elapses. |
setExecuteExistingDelayedTasksAfterShutdownPolicy | true | One-shot delayed tasks still run after shutdown(). |
setContinueExistingPeriodicTasksAfterShutdownPolicy | false | Periodic 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.
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));
}
}
removeOnCancel=false -> tasks still queued: 3 removeOnCancel=true -> tasks still queued: 1
How the code works
- 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.
- With
setRemoveOnCancelPolicy(true),cancel()removes the task from the queue straight away. - For services that schedule and cancel many long-delay tasks, enabling the policy prevents cancelled tasks from piling up.
6. Example: What Survives shutdown()
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());
}
}
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
- The two getters print the default shutdown policies: delayed tasks run, periodic tasks do not.
- The backup is a one-shot delayed task, so it still runs 200 ms later even though
shutdown()was called first. - The periodic sync is cancelled at shutdown, before its first run at 100 ms, so it never runs.
awaitTermination()waits until the delayed backup has finished. UseshutdownNow()to discard delayed tasks too.
7. Common Mistakes and Best Practices
- Using
setMaximumPoolSize(). It has no useful effect here; size the pool withcorePoolSize. - 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
ScheduledThreadPoolExecutorextendsThreadPoolExecutorand implementsScheduledExecutorService.- It works as a fixed-size pool of
corePoolSizethreads 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
Frequently Asked Questions (FAQ)
Q1. Does setMaximumPoolSize() work on ScheduledThreadPoolExecutor?
It can be called, but it has no useful effect. The class acts as a fixed-size pool of corePoolSize threads with an unbounded queue, so the maximum size is never reached.
Q2. What happens to a cancelled task by default?
It will not run, but it stays in the work queue until its delay elapses. Call setRemoveOnCancelPolicy(true) to remove cancelled tasks immediately.
Q3. Do delayed tasks still run after shutdown()?
Yes, by default. One-shot delayed tasks run when their delay elapses, while periodic tasks are cancelled. Both behaviours are configurable, and shutdownNow() discards all waiting tasks.
Q4. Which Executors methods return a ScheduledThreadPoolExecutor?
Executors.newScheduledThreadPool(n) returns one. Executors.newSingleThreadScheduledExecutor() also uses one internally, but wraps it so the result is guaranteed not to be reconfigurable to use additional threads.
Q5. Can two tasks scheduled for the same time run in a fixed order?
Tasks scheduled for exactly the same execution time are enabled in first-in-first-out order of submission. With more than one thread they may still finish in any order.