runAfterEither()
is an instance method of CompletableFuture
, which is used to execute a runnable after the completion of either the given completion stage/completable future
that is passed as a parameter or the completion stage/completable future
on which this method is invoked.
The runAfterEither
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;
public CompletableFuture<Void> runAfterEither(CompletionStage<?> other, Runnable action)
CompletionStage<?> other
: This is the completable future or the completion stage that needs to be executed.Runnable action
: This is the runnable that needs to be executed.This method returns a new CompletableFuture
.
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); String stringToPrint = "Hello-Educative"; System.out.println("----\nsupplyAsync second future - " + stringToPrint); executionThread(); return stringToPrint; }); CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(() -> { sleep(2000); String stringToPrint = "Hello-Edpresso"; System.out.println("----\nsupplyAsync second future - " + stringToPrint); executionThread(); return stringToPrint; }); Runnable runnable = () -> System.out.println("Completed one of the futures"); completableFuture1.runAfterEither(completableFuture2, runnable); sleep(2000); } }
sleep()
, which makes the current thread sleep for the given amount of milliseconds.executionThread()
, which prints the current thread of execution.completableFuture1
, using the supplyAsyc()
method, and by passing a supplier that sleeps for 1 second, invokes the executionThread()
method, and returns a string value.completableFuture2
, using the supplyAsyc()
method and by passing a supplier that sleeps for 2 seconds, invokes the executionThread()
method, and returns a string value.runAfterEither
method on the completableFuture1
and pass completableFuture2
and runnable
as the method arguments.RELATED TAGS
CONTRIBUTOR
View all Courses