a shot of dev knowledge

RELATED TAGS

What is CompletableFuture.applyToEither() in Java?

The applyToEither() method is an instance method of CompletableFuture and is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package.

This method executes a function after the completion of either the given completion stage/completable future that is passed as a parameter or after the completion of the completion stage/completable future on which this method is invoked. The function takes the result of either of the completable futures (whichever finishes first and produces a result) and produces a result.

We can import the CompletableFuture class using the following import statement:

import java.util.concurrent.CompletableFuture;

Syntax


public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn)

Parameters

  • CompletionStage<?> other: The completable future or the completion stage to execute.
  • Function<? super T, U> fn: The function to execute.

Return value

This method returns a new CompletableFuture.

Code

import java.util.concurrent.*;
import java.util.function.Function;

public class Main {

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

    static void executionThread(){
        System.out.println("Thread execution - " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            sleep(1000);
            String stringToPrint = "Educative";
            System.out.println("----\nsupplyAsync first future - " + stringToPrint);
            executionThread();
            return stringToPrint;
        });

        CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(() -> {
            sleep(2000);
            String stringToPrint = "Edpresso";
            System.out.println("----\nsupplyAsync second future - " + stringToPrint);
            executionThread();
            return stringToPrint;
        });

        Function<String, String> functionToExecute = res -> {
            System.out.println("Result received from either futures - " +  res);
            return "Hello-" + res;
        };

        CompletableFuture<String> resultCf =  completableFuture1.applyToEither(completableFuture2, functionToExecute);

        System.out.println("Result after applyToEither method call - " + resultCf.join());
        sleep(3000);
    }
}
Implementation of the applyToEither() method

Explanation

  • Lines 1-2: We import the relevant packages and classes.
  • Lines 6-12: We define a function called sleep() that makes the current thread sleep for the given amount of milliseconds.
  • Lines 14-16: We define a function called executionThread() that prints the current thread of execution.
  • Lines 19-25: We create a completable future called completableFuture1 using the supplyAsyc() method. We do this by passing a supplier that sleeps for 1 second, invokes the executionThread() method, and returns a string value.
  • Lines 27-33: We create another completable future called completableFuture2 using the supplyAsyc() method. We do this by passing a supplier that sleeps for 2 seconds, invokes the executionThread() method, and returns a string value.
  • Lines 35-38: We define a function called functionToExecute that accepts the result of either of the futures and prepends a string to the result.
  • Line 40: The applyToEither method is invoked on completableFuture1 passing completableFuture2 and functionToExecute as method arguments. This creates a new CompletableFuture called resultCf.
  • Line 42: We get the result of resultCf using the join() method and print it to the console.
  • Line 33: The main thread sleeps for 3 seconds.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring