Java 8 Multiple CompletableFutures
Male avatar

loveprogramming viết ngày 19/04/2021

Java 8 Multiple CompletableFutures

In previous posts, we have concept of how to use CompletableFutures. This tutorial is about combining multiple CompletableFutures, it is one of the most important and useful abilities of Java 8 asynchronous processing.

Related articles:

I. Usage

1. thenCompose()

<U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn)

thenCompose() can chain 2 CompletableFutures by using the result which is returned from the invoking future.

private static void testCompose() throws InterruptedException, ExecutionException {
    CompletableFuture<String> future = createCF(2); // inside future
    CompletableFuture<String> combinedFuture = future.thenCompose(MainApp::calculateCF);

    combinedFuture.thenAccept(result -> System.out.println("accept: " + result));
    // check results
    System.out.println("Future result>> " + future.get());
    System.out.println("combinedFuture result>> " + combinedFuture.get());

private static CompletableFuture<String> calculateCF(String s) {

    return CompletableFuture.supplyAsync(new Supplier<String>() {
        public String get() {
            System.out.println("> inside new Future");
            return "new Completable Future: " + s;

combinedFuture uses thenCompose() method of future with calculateCF function to get and modify the result from previous step of future.

Run the code, the Console shows:

inside future: waiting for detecting index: 2...
inside future: done...
> inside new Future
accept: new Completable Future: 2
Future result>> 2
combinedFuture result>> new Completable Future: 2

More at:

Java 8 Multiple CompletableFutures

Bình luận

{{ }}
Bỏ hay Hay
Male avatar
{{ comment_error }}

Hiển thị thử

Chỉnh sửa

Male avatar


545 bài viết.
98 người follow
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
Male avatar
1 0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...
loveprogramming viết 7 tháng trước
1 0
Male avatar
1 0 Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...
loveprogramming viết 6 tháng trước
1 0
Male avatar
1 0
Angular Spring Boot jwt Authentication Example Github (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
loveprogramming viết 6 tháng trước
1 0
Bài viết liên quan
Male avatar
0 0 Java 8 CompletableFutures Java 8 multithreading programming has an important feature name...
loveprogramming viết 3 tháng trước
0 0


{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}

Male avatar
{{userFollowed ? 'Following' : 'Follow'}}
545 bài viết.
98 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!