Both orTimeout() and completeOnTimeOut() methods are defined in CompletableFuture class and these two methods are introduced in Java 9. The orTimeout() method can be used to specify that if a given task doesn't complete within a certain period of time, the program stops execution and throws TimeoutException whereas completeOnTimeOut() method completes the CompletableFuture with the provided value. If not, it complete before the given timeout.
Syntax for orTimeout()
public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)
Example
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; CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(5); } 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); } }
Output
25
Syntax for completeOnTimeOut()
public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)
Example
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; CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(5); } catch(InterruptedException e) { e.printStackTrace(); } return a + b; }) .completeOnTimeout(0, 4, TimeUnit.SECONDS) .thenAccept(result -> System.out.println(result)); TimeUnit.SECONDS.sleep(10); } }
Output
25