Java 9 CompletableFuture API Improvements – Delay and 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

– 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:

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()

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.

Run the code above, we get result that prints out:
Sorry, timeout in 3 seconds
and throw a java.util.concurrent.TimeoutException.

Java 9 new CompletableFuture API also gives us another method to handle the case when timeout: completeOnTimeout().

2. completeOnTimeout()

The method completes current CompletableFuture by input value if not otherwise completed before the timeout.

Like the example above, we have a doWork() method that takes 5 seconds to return a CompletableFuture. But we set TIMEOUT only 3 seconds. We also specify the string value JavaTechnology in case the time 3 seconds is out and doWork() hasn’t done its operation yet.

Run the code above, we get result that prints out:
The result is: JavaTechnology

III. SOURCE CODE

1. DelayedExecutorTest.java


Result:

2. OrTimeOutTest.java

Result:

If we change TIMEOUT to 6

3. CompleteOnTimeoutTest.java

Result:

If we change TIMEOUT to 6

By JavaSampleApproach | March 28, 2017.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*