search
HomeJavajavaTutorialHow to use CompletableFuture's thenCompose and thenCombine functions for asynchronous merge operations in Java

In Java, we often encounter scenarios that require asynchronous operations. For this situation, Java 8 introduced the CompletableFuture class, which provides us with rich asynchronous programming tools to make asynchronous programming simpler and easier. Among them, thenCompose and thenCombine are two commonly used combined asynchronous operation methods in the CompletableFuture class.

1. The use of thenCompose

ThethenCompose method is used to convert a CompletableFuture instance into another CompletableFuture instance. Specifically, it receives a Function parameter that takes as input the result returned by the previous CompletableFuture and returns a new CompletableFuture object. Here is an example:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 10;
});

CompletableFuture<Integer> result = future.thenCompose(value -> CompletableFuture.supplyAsync(() -> value * 2));

result.whenComplete((res, ex) -> {
    if (ex != null) {
        ex.printStackTrace();
    } else {
        System.out.println(res);
    }
});

In the above code, first we create a CompletableFuture instance, which will simulate the calculation time in another thread. Next, we use the thenCompose method to convert it into a new CompletableFuture instance, which multiplies the result returned by the previous CompletableFuture by 2. Finally, we use the whenComplete method to output results or error messages.

2. The use of thenCombine

ThethenCombine method is used to merge two CompletableFuture instances into one. Specifically, it receives another CompletableFuture instance and a BiFunction parameter that takes as input the results returned by the two CompletableFutures and returns a new CompletableFuture object. Here is an example:

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 10;
});

CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 5;
});

CompletableFuture<Integer> result = future1.thenCombine(future2, (value1, value2) -> value1 + value2);

result.whenComplete((res, ex) -> {
    if (ex != null) {
        ex.printStackTrace();
    } else {
        System.out.println(res);
    }
});

In the above code, we created two CompletableFuture instances, which simulated the execution of two computing tasks respectively. Next, we use the thenCombine method to merge the two CompletableFuture instances into a new instance that adds the results returned by the first two CompletableFutures. Finally, we use the whenComplete method to output results or error messages.

3. Use thenCompose and thenCombine to implement complex asynchronous operations

We have already introduced the use of thenCompose and thenCombine methods, and they are both very useful asynchronous operation methods. In fact, we can also use them to implement more complex asynchronous operations, such as aggregation operations on multiple calculation results.

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 10;
});

CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 5;
});

CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
    // 模拟计算耗时
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return 20;
});

CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2, future3);

CompletableFuture<Integer> result = combinedFuture.thenCompose(
        voidResult -> CompletableFuture.supplyAsync(() -> {
            int sum = future1.join() + future2.join() + future3.join();
            return sum;
        }));

result.whenComplete((res, ex) -> {
    if (ex != null) {
        ex.printStackTrace();
    } else {
        System.out.println(res);
    }
});

In the above code, we created three CompletableFuture instances, each of which simulates the execution of a computing task and returns the corresponding results. Next, we use the CompletableFuture.allOf method to combine these three instances and create a new CompletableFuture instance. It should be noted here that the allOf method returns a CompletableFuture instance of Void type, and its return value is null.

Then, we use the thenCompose method to convert the above CompletableFuture instance that returns null into a new CompletableFuture instance, which adds the results returned by the previous three CompletableFutures. In the callback function of the thenCompose method, we use the join() method to obtain the result value of each CompletableFuture instance and perform corresponding calculations. Finally, we use the whenComplete method to output results or error messages.

In general, thenCompose and thenCombine are very useful methods in the CompletableFuture class. They can help us perform asynchronous operations more conveniently and improve the concurrency and execution efficiency of the program.

The above is the detailed content of How to use CompletableFuture's thenCompose and thenCombine functions for asynchronous merge operations in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment