##orTimeout() and completeOnTimeOut() methods are both defined in the CompletableFuture class. This method was introduced in Java 9. The orTimeout() method can be used to specify that if a given task is not completed within a specific time, the program stops execution and throws TimeoutException strong>while completeOnTimeOut() Method completes CompletableFuture using the provided value. If not, it will complete before the given timeout. The Chinese translation of
orTimeout()'s syntax<strong>public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)</strong>
import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; public class OrTimeoutMethodTest { public static void main(String args[]) throws InterruptedException { int a = 10; int b = 15; <strong>CompletableFuture</strong>.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(5); } catch(InterruptedException e) { e.printStackTrace(); } return a + b; }) .<strong>orTimeout</strong>(4, TimeUnit.SECONDS) .<strong>whenComplete</strong>((result, exception) -> { System.out.println(result); if(exception != null) exception.printStackTrace(); }); TimeUnit.SECONDS.sleep(10); } }
<strong>25 </strong>
completeOnTimeOut() The Chinese translation of syntax
<strong>public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)</strong>
import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; public class CompleteOnTimeOutMethodTest { public static void main(String args[]) throws InterruptedException { int a = 10; int b = 15; <strong>CompletableFuture</strong>.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(5); } catch(InterruptedException e) { e.printStackTrace(); } return a + b; }) .<strong>completeOnTimeout</strong>(0, 4, TimeUnit.SECONDS) .<strong>thenAccept</strong>(result -> System.out.println(result)); TimeUnit.SECONDS.sleep(10); } }
<strong>25</strong>
The above is the detailed content of What is the difference between orTimeout() method and completeOnTimeOut() method in Java 9?. For more information, please follow other related articles on the PHP Chinese website!