Java 9 CompletableFuture API improvements – delayedExecutor
Java 9 introduces a couple of improvements in CompletableFuture API. Today let’s take a look at new delayedExecutor
static method.
static Executor delayedExecutor(long delay, TimeUnit unit);
//Returns a new Executor that submits a task to the default executor after the given delay.
static Executor delayedExecutor(long delay, TimeUnit unit, Executor executor); //Returns a new Executor that submits a task to the given base executor after the given delay.
Let’s say we want to delay the execution for 5 seconds:
long start = System.currentTimeMillis();
CompletableFuture future = new CompletableFuture<>();
future.completeAsync(() -> "Inside task", CompletableFuture.delayedExecutor(5, SECONDS))
.thenAccept(result -> System.out.println("accept: " + result))
.get();
long end = System.currentTimeMillis();
//output
accept: Inside future task
task starts after 5 seconds