Differences between orTimeout() and completeOnTimeOut() methods in Java 9?



In this article, we will learn about the differences between the orTimeout() and the completeOnTimeout() methods in Java. Both the orTimeout() and completeOnTimeout() methods are defined in the CompletableFuture class, and these two methods were introduced in Java 9.

CompletableFuture class

The CompletableFuture class, introduced in Java 8, represents a Future that can have its value and status set explicitly. It also supports dependent functions and actions that are triggered upon the completion of the future. In Java 9, the CompletableFuture API received further enhancements.

The following are some common methods of the CompletableFuture class:

  • orTimeout()
  • completeOnTimeout()
  • defaultExecutor()
  • newIncompleteFuture()

orTimeout() Method

The orTimeout() is a method of the CompletableFuture class that 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 a TimeoutException.

Syntax

The following is the syntax for the orTimeout method declaration:

public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)

Parameters:

  • timeout: how long to wait before completing exceptionally with a TimeoutException, in units of time.
  • unit: a TimeUnit determining how to interpret the timeout parameter.

Characteristics

The following are some key characteristics of the orTimeout() Method:

  • There is strict time enforcement, and it fails as soon as the timeout.
  • Exceptional completion leads to a TimeoutException.
  • Disrupts the normal path of completion, which causes the pipeline interruption.
  • Best in situations where a timeout is a failure and needs special treatment.

Example

Below is an example of the Timeout() method in Java:

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

The above code throws the TimeoutException Error as the program doesn't finish within the specified time:

null
Warnings/Errors:
java.util.concurrent.TimeoutException
	at java.base/java.util.concurrent.CompletableFuture$Timeout.run(CompletableFuture.java:2920)
	at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
	at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
	at java.base/java.lang.Thread.run(Thread.java:1583)

completeOnTimeout() Method

The completeOnTimeout() is also a method of the CompletableFuture class and completes the CompletableFuture with the provided value. If not, it completes before the given timeout.

Syntax

The following is the syntax for the completeOnTimeout() method declaration:

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

Parameters:

  • value: The value to use upon timeout.
  • timeout: How long to wait before completing normally with the given value, in units of time.
  • unit: a TimeUnit determining how to interpret the timeout parameter.

Characterstics

The following are some key characteristics of the completeOnTimeout() Method:

  • Timeout Handling is great as it completes normally with a default value.
  • No Exception is thrown as it keeps the normal completion path.
  • Later phases continue to run, which helps in Pipeline Continuation.
  • Best when there is a good default, and the implementation should go ahead.

Example

Below is an example of the completeOnTimeout() method in Java:

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

0

Difference Table

The following are some key differences between the orTimeout() and the completeOnTimeout () methods in Java:

Criteria orTimeout() completeOnTimeout()
Completion Type Completes exceptionally Completes normally
Result on Timeout TimeoutException Specified default value
Pipeline Flow Interrupts normal flow Continues normal flow
Use When Timeout means critical failure Timeout can be handled easily
Error Handling Requires catch/handle No special handling needed
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-06-09T14:27:47+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements