The delayedExecutor() method has been added to the CompletableFuture class in Java 9. CompletableFuture defines two overloaded methods of delayedExecutor(): first method returns an Executor object from the default Executor object that CompletableFuture object uses to execute the task after the delay and new Executor object can do task execution whereas the second method also returns an Executor object but is an Executor object that we pass into this method after the delay and new Executor object can also do task execution.
Syntax
public static Executor delayedExecutor(long delay, TimeUnit unit, Executor executor) public static Executor delayedExecutor(long delay, TimeUnit unit)
Example
import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; public class DelayedExecutorMethodTest { public static void main(String args[]) throws InterruptedException, ExecutionException { CompletableFuture<String> future = new CompletableFuture<>(); future.completeAsync(() -> { try { System.out.println("inside future: processing data..."); return "tutorialspoint.com"; } catch(Throwable e) { return "not detected"; } }, CompletableFuture.delayedExecutor(3, TimeUnit.SECONDS)) .thenAccept(result -> System.out.println("accept: " + result)); for(int i = 1; i <= 5; i++) { try { Thread.sleep(1000); } catch(InterruptedException e) { e.printStackTrace(); } System.out.println("running outside... " + i + " s"); } } }
Output
running outside... 1 s running outside... 2 s inside future: processing data... accept: tutorialspoint.com running outside... 3 s running outside... 4 s running outside... 5 s