Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
completeontimeout
completablefuture

What is CompletableFuture.completeOnTimeout() in Java?

abhilash

completeOnTimeout() is an instance method of the CompletableFuture class that completes the class with the passed value. It only does so if the task associated with it is not completed within the waiting period.

The completeOnTimeout method is defined in the CompletableFuture class. The class is defined in the java.util.concurrent package. To import the CompletableFuture class check the following import statement:

import java.util.concurrent.CompletableFuture;

Syntax


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

Parameters

  • T value: The result of the future in the case of a timeout.
  • long timeout: The maximum amount of time to wait.
  • TimeUnit unit: The unit of time.

Return value

This method returns the CompletableFuture on which this method is invoked.

Code

import java.util.concurrent.*;

public class Main {

    static void sleep(int millis){
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            sleep(4000);
            return "Hello-Educative";
        });

        long timeOutValue = 1;
        TimeUnit timeUnit = TimeUnit.SECONDS;
        String valueIfTimeOut = "Future timed out";
        completableFuture.completeOnTimeout(valueIfTimeOut, timeOutValue, timeUnit)
                .thenAccept(System.out::println);
        sleep(3000);
    }
}
Implementation of the "completeOnTimeout" method

Explanation

  • Line 1: We import the relevant packages and classes.
  • Lines 5-11: We define a function called sleep() that makes the current thread sleep for the given amount of milliseconds.
  • Line 14: We create a CompletableFuture using the supplyAsyc() method. We pass a supplier that sleeps for 4 seconds and returns a string value.
  • Line 19: We define the wait time value as timeOutValue.
  • Line 20: We define the wait time unit as timeUnitForTimeOut.
  • Line 21: We define the value that gets stored in the future in the case of a time out as valueIfTimeOut.
  • Line 22: We invoke the completeOnTimeout() method and pass the relevant parameters. Once the future is in a complete state, we consume the future’s value.
  • Line 24: We invoke the sleep function on the main thread.

When the code above is run, the code prints a Future timed out. This indicates that the task took more time to be completed than the wait time.

RELATED TAGS

java
communitycreator
completeontimeout
completablefuture
RELATED COURSES

View all Courses

Keep Exploring