This method was introduced from Java 9.
1 |
CompletableFuture<T> orTimeout(long timeout, TimeUnit unit) |
This method is used to specify that if our task does not complete within a certain period of time, the program will stop and be TimeoutException.
In the following example, I want to calculate the sum of two numbers that will be completed in 1 second, but in the process of summing, I set up it 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 27 28 29 30 |
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; }) .orTimeout(1, TimeUnit.SECONDS) .whenComplete((result, exception) -> { System.out.println(result); if (exception != null) exception.printStackTrace(); }); TimeUnit.SECONDS.sleep(10); } } |
Result:
If I now increase the timeout time:
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 27 28 29 30 |
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; }) .orTimeout(4, TimeUnit.SECONDS) .whenComplete((result, exception) -> { System.out.println(result); if (exception != null) exception.printStackTrace(); }); TimeUnit.SECONDS.sleep(10); } } |
the program will not fail anymore.