CompletableFuture Delayed Task Executor
Schedule a delayed stage with CompletableFuture.delayedExecutor (Java 9+): supplyAsync holds the stage back, orTimeout bounds the wait without Thread.sleep.
Code
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class DelayedRetry {
public static void main(String[] args) throws Exception {
// 延迟执行器(Java 9+):提交到这里的事统一推迟 1 秒再跑
var delayed = CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS);
long start = System.nanoTime();
CompletableFuture<String> refresh = CompletableFuture
.supplyAsync(() -> "fresh value", delayed)
.orTimeout(2, TimeUnit.SECONDS);
System.out.println("submitted, not blocking on the caller thread");
System.out.println("result: " + refresh.get(5, TimeUnit.SECONDS));
System.out.println("elapsed ms: " + (System.nanoTime() - start) / 1_000_000);
}
}What the code does
CompletableFuture Delayed Task Executor is built around the class DelayedRetry.
Applying it
Output lines are prefixed (submitted, not blocking on the caller thread, result:, elapsed ms:), so the effect of every operation can be spotted in the printed lines.
Statements that matter
var delayed = CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS);
CompletableFuture<String> refresh = CompletableFuture
.supplyAsync(() -> "fresh value", delayed)
.orTimeout(2, TimeUnit.SECONDS);
Interactive Tools for This Topic
FAQ
- What does CompletableFuture Delayed Task Executor print when run?
- Running the file directly is enough — expect labeled output lines such as `submitted, not blocking on the caller thread`, `result:`, `elapsed ms:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.