- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Differences between orTimeout() and completeOnTimeOut() methods in Java 9?
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
Advertisements