This method was introduced from Java 9.
1 |
CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit) |
This method is used to: if after a timeout period our task is still unfinished, instead of throwing out the TimeoutException exception like the orTimeout() method, our code will return the value that we passed in this method.
The following example I want to calculate the sum of two numbers and I want it to complete in 1s, but because in the process of processing, I give sleep 3s:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.huongdanjava.javaexample; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; public class Example { public static void main(String[] args) throws InterruptedException { int a = 2; int b = 5; CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } return a + b; }) .completeOnTimeout(0, 1, TimeUnit.SECONDS) .thenAccept(result -> System.out.println(result)); TimeUnit.SECONDS.sleep(10); } } |
The result will return the value you passed into the completeOnTimeout() method, which is 0:
If I now increase the timeout time to 4s:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.huongdanjava.javaexample; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; public class Example { public static void main(String[] args) throws InterruptedException { int a = 2; int b = 5; CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } return a + b; }) .completeOnTimeout(0, 4, TimeUnit.SECONDS) .thenAccept(result -> System.out.println(result)); TimeUnit.SECONDS.sleep(10); } } |
The result would be: