What is CompletableFuture.acceptEither() in Java?
acceptEither() is an instance method of the CompletableFuture class, which takes a CompletableFuture and a Consumer as parameters. The Consumer is executed with the execution result of any of the futures that are completed normally.
We may refer to the code given below to gain a better understanding of the acceptEither() method.
The acceptEither method is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. To import the CompletableFuture class, we check the following import statement:
import java.util.concurrent.CompletableFuture;
Syntax
public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)
Parameters
CompletionStage<? extends T> other: This is the other future.Consumer<? super T> action: This is theConsumerthat is executed.
Return value
This method returns an empty/void CompletableFuture.
Code
import java.util.concurrent.*;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);executionThread();return "Educative";});CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(() -> {sleep(2000);executionThread();return "Edpresso";});completableFuture1.acceptEither(completableFuture2, res -> System.out.println("First completed future result - " + res));sleep(2000);}}
Code explanation
-
Line 1: We import the relevant packages and classes.
-
Lines 5–11: We define a function called
sleep(), which makes the current thread sleep for the given amount of time (in milliseconds). -
Lines 13–15: We define a function called
executionThread(), which prints the current thread of execution. -
Lines 19–23: We create a completable future called
completableFuture1, using thesupplyAsyc()method. We pass a supplier to it that sleeps for one second and then invokes theexecutionThread(). Finally, this method returns a string value. -
Lines 25–29: We create another completable future called
completableFuture2, using thesupplyAsyc()method. We pass a supplier to it that sleeps for two seconds and then invokes theexecutionThread(). Finally, this method returns a string value. -
Line 31: We invoke the
acceptEithermethod oncompletableFuture1. We passcompletableFuture2and aConsumerthat prints the result of either future to the console. -
Line 32: The main thread is made to sleep for two seconds.