Java CompletableFuture acceptEither()
May 26, 2019
Java CompletableFuture
implements CompletionStage
and Future
interfaces. CompletableFuture.acceptEither
is inherited from CompletionStage
. The acceptEither
method returns a new CompletionStage
that, when either this or the other given stage complete normally, is executed with the corresponding result as argument to the supplied action.
Find the method declaration of
acceptEither
method from Java doc.
CompletionStage<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)
CompletionStage
.
The parameter action is the action to perform before completing the returned
CompletionStage
.
Find the examples.
Example-1:
AcceptEitherDemo1.java
package com.concretepage; import java.util.concurrent.CompletableFuture; public class AcceptEitherDemo1 { public static void main(String[] args) { CompletableFuture.supplyAsync(() -> "Welcome ABC") .acceptEither(CompletableFuture.supplyAsync(() -> "Welcome XYZ"), s -> System.out.println(s)); } }
Welcome ABC
acceptEither
method is executed with the result of either this or other given stage, whichever completes normally earlier. So in our example sometimes the output will be "Welcome ABC" and sometimes the output will be "Welcome XYZ".
Example-2:
AcceptEitherDemo2.java
package com.concretepage; import java.util.concurrent.CompletableFuture; public class AcceptEitherDemo2 { public static void main(String[] args) { CompletableFuture<String> cfuture = CompletableFuture.supplyAsync(() -> getA()); CompletableFuture<String> otherCFuture = CompletableFuture.supplyAsync(() -> getB()); CompletableFuture<Void> cf = cfuture.acceptEither(otherCFuture, s -> System.out.println(s)); cf.join(); } private static String getA() { try { Thread.sleep(500); } catch (InterruptedException e) { System.err.println(e); } return "Mahesh"; } private static String getB() { try { Thread.sleep(400); } catch (InterruptedException e) { System.err.println(e); } return "Krishna"; } }
Krishna
otherCFuture
will complete earlier than cfuture
because getB()
will complete earlier than getA()
method. Hence acceptEither
method will be executed with the result of otherCFuture
completion stage.
References
Class CompletableFutureInterface CompletionStage