CompletableFuture is a class in Java that represents an asynchronous computation that can be chained together with other computations. The class provides a set of methods that can be used to compose complex asynchronous computations.
The anyOf() method of the CompletableFuture class is a method that returns a new CompletableFuture that is completed when any of the given CompletableFuture objects completes. The result of the returned CompletableFuture is the result of the first completed CompletableFuture. If all of the given CompletableFuture objects complete exceptionally, the returned CompletableFuture will also complete exceptionally with an ExecutionException.
Here is an example that demonstrates how to use the anyOf() method:
import java.util.concurrent.*;
public class CompletableFutureAnyOfExample {
public static void main(String[] args) {
CompletableFuture<Integer> future1 =
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1;
});
CompletableFuture<Integer> future2 =
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 2;
});
CompletableFuture<Integer> future3 =
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 3;
});
CompletableFuture<Object> anyFuture =
CompletableFuture.anyOf(future1, future2, future3);
try {
System.out.println(anyFuture.get()); // prints 2
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
In this example, we create three CompletableFuture objects that simulate asynchronous computations that take different amounts of time to complete. We then pass these CompletableFuture objects to the CompletableFuture.anyOf() method, which returns a new CompletableFuture that completes as soon as any of the given CompletableFuture objects completes. We then call the get() method on the returned CompletableFuture object to retrieve the result of the first completed CompletableFuture. In this example, the result is 2, which is the result of the second CompletableFuture.