Logo

dev-resources.site

for different kinds of informations.

Java 9 CompletableFuture API Improvements - Delay and Timeout Support

Published at
4/3/2021
Categories
java9
completablefuture
Author
loizenai
Categories
2 categories in total
java9
open
completablefuture
open
Author
8 person written this
loizenai
open
Java 9 CompletableFuture API Improvements - Delay and Timeout Support

Java 9 CompletableFuture API Improvements - Delay and Timeout Support

https://grokonez.com/java/java-9/java-9-completablefuture-api-improvements-delay-timeout-support

To improve Java Future, Java 8 provides CompletableFuture which can execute some code whenever its ready. In this article, we're gonna take a look at new Java 9 CompletableFuture API that supports delay and timeout.

I. Delay


static Executor delayedExecutor(long delay, TimeUnit unit);
static Executor delayedExecutor(long delay, TimeUnit unit, Executor executor);
  • The first method, not specify Executor, returns a new Executor that submits a task to the default executor (general purpose pool ForkJoinPool.commonPool()) after delay time.
  • The second method, with an Executor as parameter, returns a new Executor that submits a task to that input executor after delay time.

Now see an example to illustrate how the method works. We have a CompletableFuture that will delay its completion by 3 seconds. The code could be:


future.completeAsync(supplier, CompletableFuture.delayedExecutor(3, TimeUnit.SECONDS))
        .thenAccept(result -> System.out.println("accept: " + result));

// other statements

The program runs 'other statements' first. 3 seconds later, it call get() method of supplier and pass the result to thenAccept().

II. Timeout

1. orTimeout()


CompletableFuture orTimeout(long timeout, TimeUnit unit);

The method exceptionally completes current CompletableFuture by throwing a TimeoutException if not otherwise completed before the timeout.

For example, we have a doWork() method that takes 5 seconds to return a CompletableFuture. But we set TIMEOUT only 3 seconds.


// TIMEOUT = 3;
// doWork() takes 5 seconds to finish

CompletableFuture future = 
        doWork("JavaSampleApproach")
        .orTimeout(TIMEOUT, TimeUnit.SECONDS)
        .whenComplete((result, error) -> {
            if (error == null) {
                System.out.println("The result is: " + result);
            } else {
                System.out.println("Sorry, timeout in " + TIMEOUT + " seconds");
            }
        });

More at: https://grokonez.com/java/java-9/java-9-completablefuture-api-improvements-delay-timeout-support

Featured ones: