ScheduledFuture Interface in Java: Delays, Results and Cancellation
Every scheduling method of ScheduledExecutorService returns a ScheduledFuture. It is a Future that also knows how long remains until the task runs.
This tutorial shows what the interface inherits, how to read the remaining delay, how scheduled futures sort by time, and how to cancel them.
1. What Is ScheduledFuture?
ScheduledFuture<V> is an interface in java.util.concurrent, added in Java 5. It declares no methods of its own; it simply combines Delayed and Future<V>.
public interface ScheduledFuture<V> extends Delayed, Future<V> {
}
From Delayed it gets getDelay(TimeUnit), and because Delayed extends Comparable<Delayed>, scheduled futures can be ordered by how soon they are due. From Future it gets get(), cancel() and the other result methods.
2. ScheduledFuture Hierarchy
Swipe sideways to see the whole diagram.
Delayed(interface): ProvidesgetDelay(TimeUnit): the remaining delay, zero or negative once the task is due.Comparable<Delayed>(java.lang interface): Lets scheduled tasks be sorted by remaining delay.Future(interface): Providesget(),cancel(),isDone()and the Java 19 state methods.RunnableScheduledFuture(interface): Used inside scheduled executors; addsisPeriodic().
3. Key Methods (Inherited)
| Method | From | Description |
|---|---|---|
long getDelay(TimeUnit unit) | Delayed | Remaining delay in the given unit. |
int compareTo(Delayed o) | Comparable | Orders tasks by remaining delay. |
V get() | Future | Waits for the result of a one-shot task. |
boolean cancel(boolean) | Future | Cancels a pending or periodic task. |
isDone(), isCancelled() | Future | Report completion and cancellation. |
4. Example: Counting Down to a Scheduled Task
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class MaintenanceCountdown {
static long roundedMillis(ScheduledFuture<?> f) {
return Math.round(f.getDelay(TimeUnit.MILLISECONDS) / 100.0) * 100; // nearest 100 ms
}
public static void main(String[] args) throws InterruptedException {
try (ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor()) {
ScheduledFuture<?> maintenance = scheduler.schedule(
() -> System.out.println("Putting the shop into maintenance mode"), 2, TimeUnit.SECONDS);
System.out.println("Maintenance starts in ~" + roundedMillis(maintenance) + " ms");
Thread.sleep(500);
System.out.println("Maintenance starts in ~" + roundedMillis(maintenance) + " ms");
// The release was postponed: cancel the pending maintenance
boolean cancelled = maintenance.cancel(false);
System.out.println("Cancelled: " + cancelled + ", isDone: " + maintenance.isDone());
}
}
}
Maintenance starts in ~2000 ms Maintenance starts in ~1500 ms Cancelled: true, isDone: true
How the code works
schedule()returns aScheduledFuture<?>for a task due in 2 seconds.getDelay(MILLISECONDS)reports the time left; the example rounds it to 100 ms because the exact value depends on timing.- After 500 ms, about 1,500 ms remain.
cancel(false)then removes the need to run the task at all. - A cancelled task counts as done, so
isDone()istrue, and the maintenance message never prints.
5. Example: Finding the Next Job to Run
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class NextJobFirst {
public static void main(String[] args) {
try (ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1)) {
Map<ScheduledFuture<?>, String> jobs = new LinkedHashMap<>();
jobs.put(scheduler.schedule(() -> { }, 30, TimeUnit.MINUTES), "rotate logs");
jobs.put(scheduler.schedule(() -> { }, 5, TimeUnit.MINUTES), "send digest email");
jobs.put(scheduler.schedule(() -> { }, 2, TimeUnit.HOURS), "rebuild sitemap");
// ScheduledFuture extends Delayed, which is Comparable<Delayed>: sorts by remaining delay
List<ScheduledFuture<?>> byDelay = new ArrayList<>(jobs.keySet());
byDelay.sort(null);
for (ScheduledFuture<?> f : byDelay) {
System.out.printf("%-18s in %3d min%n", jobs.get(f), Math.round(f.getDelay(TimeUnit.SECONDS) / 60.0));
}
scheduler.shutdownNow(); // discard the pending demo jobs
}
}
}
send digest email in 5 min rotate logs in 30 min rebuild sitemap in 120 min
How the code works
- Three jobs are scheduled in an arbitrary order: 30 minutes, 5 minutes and 2 hours ahead.
byDelay.sort(null)uses natural ordering, which for ScheduledFuture meanscompareTo()fromDelayed: the shortest remaining delay first.shutdownNow()discards the pending demo jobs so the program can exit immediately.
6. Common Mistakes and Best Practices
- Calling
get()on a periodic task. It never completes normally, soget()blocks until the task is cancelled or fails. - Treating
getDelay()as exact. It is a snapshot that changes every moment, and tasks may start a little after the delay elapses. - Losing the handle. Keep the ScheduledFuture if you may need to cancel the task later.
- Many cancelled long-delay tasks. On a
ScheduledThreadPoolExecutor, enablesetRemoveOnCancelPolicy(true)so they leave the queue immediately.
7. Summary
ScheduledFuture<V>extendsDelayedandFuture<V>and adds no methods of its own.getDelay()returns the remaining delay; scheduled futures sort by it throughComparable<Delayed>.- Use
get()for one-shot tasks andcancel()to stop pending or periodic ones.
Related Tutorials
8. References
Frequently Asked Questions (FAQ)
Q1. Does ScheduledFuture have its own methods?
No. It declares none. All of its methods come from Delayed (getDelay() and compareTo()) and Future (get(), cancel() and the rest).
Q2. What does getDelay() return after the task is due?
Zero or a negative value. The documentation describes the result as the remaining delay, where zero or negative values indicate that the delay has already elapsed.
Q3. What does get() return for a periodic task?
A periodic task never completes normally. get() blocks until the task is cancelled, which causes CancellationException, or until a run throws, which causes ExecutionException.
Q4. How do I cancel a scheduled task?
Call cancel(false) on its ScheduledFuture to stop it from starting, or cancel(true) to also interrupt it if it is currently running.
Q5. Why is ScheduledFuture comparable?
Because it extends Delayed, which extends Comparable<Delayed>. Scheduled executors use this ordering to keep their queue sorted so the task due soonest runs first.