Home  >  Article  >  Java  >  What is the difference between orTimeout() method and completeOnTimeOut() method in Java 9?

What is the difference between orTimeout() method and completeOnTimeOut() method in Java 9?

WBOY
WBOYforward
2023-08-27 22:53:041023browse

Java 9中orTimeout()方法和completeOnTimeOut()方法之间的区别是什么?

##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>

Example

is:

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;
      <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);
   }
}

Output

<strong>25
</strong>

completeOnTimeOut() The Chinese translation of syntax

<strong>public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)</strong>

Example

is:

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;
      <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);
   }
}

Output

<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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete