Home > Java > javaTutorial > body text

How to use Future and CompletableFuture in Java function concurrency and multi-threading?

王林
Release: 2024-04-27 16:33:01
Original
1110 people have browsed it

Future and CompletableFuture are tools for concurrency and multithreading in Java. Future represents the asynchronous calculation result and provides the get() method to block the thread to obtain the result. CompletableFuture extends Future to provide richer functionality, such as combining calculations, handling exceptions, and using callback functions.

How to use Future and CompletableFuture in Java function concurrency and multi-threading?

Concurrency and Multithreading of Java Functions: Using Future and CompletableFuture

Overview

Future and CompletableFuture are concurrency tools introduced in Java 8 for handling asynchronous operations and concurrent tasks. They allow you to perform long-running operations without blocking the main thread, improving application performance and responsiveness.

Future

Future is an object that represents the result of an asynchronous calculation. It provides a method get() that blocks the current thread until the result is available. You can also use the isDone() method to check if the calculation is complete.

CompletableFuture

CompletableFuture is an extension of Future, providing richer functions. It allows you to compose asynchronous calculations, handle exceptions, and use callback functions.

Practical Case

Consider the following example, using Future to load files asynchronously:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FileLoader {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<String> future = executorService.submit(() -> {
            // 异步加载文件
            return loadFile("file.txt");
        });

        // 继续执行其他任务,而不阻塞当前线程
        // ...

        // 当需要结果时,再阻塞主线程获取结果
        String result = future.get();
    }

    private static String loadFile(String filePath) {
        // 模拟文件加载操作
        return "File contents";
    }
}
Copy after login

In this example, we Use ExecutorService to create a thread pool, and then use submit() to submit an asynchronous task, which is responsible for loading the file. The main thread continues to perform other tasks without blocking waiting for the file to be loaded. Finally, when the file content is needed, we call get() to get the result from Future.

Using CompletableFuture

The following example shows how to use CompletableFuture to compose asynchronous calculations:

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {

    public static void main(String[] args) {
        // 定义第一个异步计算
        CompletableFuture<Integer> firstResult = CompletableFuture.supplyAsync(() -> {
            // 计算第一个结果
            return 5;
        });

        // 定义第二个异步计算
        CompletableFuture<Integer> secondResult = CompletableFuture.supplyAsync(() -> {
            // 计算第二个结果
            return 10;
        });

        // 组合两个计算,将它们的结果相加
        CompletableFuture<Integer> combinedResult = firstResult.thenCombine(secondResult, (x, y) -> x + y);

        // 获取最终结果
        int result = combinedResult.get();
    }
}
Copy after login

In this example, We create two asynchronous calculations using CompletableFuture#supplyAsync(). We then combine them using CompletableFuture#thenCombine() and add their results. Finally, we use CompletableFuture#get() to get the final result.

In short, Future and CompletableFuture are powerful tools for handling asynchronous operations and concurrent tasks. Use these tools to improve your application's performance and responsiveness, creating more efficient and scalable code.

The above is the detailed content of How to use Future and CompletableFuture in Java function concurrency and multi-threading?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!