简体   繁体   English

在 Spring Boot 的 @Async 注释中使用 CompletableFuture.supplyAsync 和 CompletableFuture.completedFuture

[英]use of CompletableFuture.supplyAsync and CompletableFuture.completedFuture within @Async annotation in spring boot

I have the following methods:我有以下方法:

@EnableAsync
@Service
Class MyService{ 

private String processRequest() {
        log.info("Start processing request");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        log.info("Completed processing request");
        return RESULT;
    }    

@Async
public CompletableFuture<String> getSupplyAsyncResult(){
    CompletableFuture<String> future
            = CompletableFuture.supplyAsync(this::processRequest);
    return future;
}

@Async
public CompletableFuture<String> getCompletedFutureResult(){
    CompletableFuture<String> future
            = CompletableFuture.supplyAsync(this::processRequest);
    return future;
}

and the following endpoints in controller:以及控制器中的以下端点:

   @RequestMapping(path = "/asyncSupplyAsync", method = RequestMethod.GET)
    public CompletableFuture<String> getValueAsyncUsingCompletableFuture() {
        log.info("Request received");
        CompletableFuture<String> completableFuture
                = myService.getSupplyAsyncResult();
        log.info("Servlet thread released");
        return completableFuture;
    }

and

   @RequestMapping(path = "/asyncCompletable", method = RequestMethod.GET)
    public CompletableFuture<String> getValueAsyncUsingCompletableFuture() {
        log.info("Request received");
        CompletableFuture<String> completableFuture
                = myService.getCompletedFutureResult();
        log.info("Servlet thread released");
        return completableFuture;
    }

Why would anyone use completableFuture.supplyAsync within @Async method in Spring endpoint?为什么有人会在 Spring 端点的 @Async 方法中使用completableFuture.supplyAsync I assume using completableFuture.completedFuture is more appropriate, please share your views.我认为使用completableFuture.completedFuture更合适,请分享您的意见。

They serve entirely different purposes to begin with.它们一开始就服务于完全不同的目的。 Before you think about how much it takes one or the other to process, you might want to understand how they work, first (so little calls are no indication of slow/fast anyway; these numbers mean nothing in this context).在您考虑处理一个或另一个需要多少时间之前,您可能首先想了解它们是如何工作的(无论如何,调用很少并不表示慢/快;这些数字在这种情况下没有任何意义)。

Here is the same example you have:这是您拥有的相同示例:

public class SO64718973 {

    public static void main(String[] args) {
        System.out.println("dispatching to CF...");
        //CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> processRequest());
        CompletableFuture<String> future = CompletableFuture.completedFuture(processRequest());
        System.out.println("done dispatching to CF...");
        future.join();
    }

    private static String processRequest() {
        System.out.println("Start processing request");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("Completed processing request");
        return "RESULT";
    }

}

You can run this and then change the implementation (by uncommenting CompletableFuture.supplyAsync ) and see where those System.out.println occur.您可以运行它,然后更改实现(通过取消注释CompletableFuture.supplyAsync )并查看System.out.println发生的位置。 You will notice that completedFuture will block main thread until it is executed, while supplyAsync will run in a different thread.你会发现, completedFuture将阻止main ,直到它被执行的进程,而supplyAsync会在不同的线程中运行。 So it's not like one is wrong and one is not, it depends on your use-case.所以它不像一个是错的,一个不是,这取决于你的用例。

In general, it is not a great idea to use CompletableFuture.supplyAsync without configuring a pool for it;一般来说,使用CompletableFuture.supplyAsync而不为其配置池并不是一个好主意; otherwise it will consume threads from ForkJoinPool .否则它将消耗来自ForkJoinPool线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Mockito 测试 CompletableFuture.supplyAsync - Testing CompletableFuture.supplyAsync with Mockito 获取CompletableFuture.supplyAsync的结果 - Getting the result of a CompletableFuture.supplyAsync CompletableFuture.supplyAsync与新的CompletableFuture() - CompletableFuture.supplyAsync vs new CompletableFuture() ForkJoinPool在CompletableFuture.supplyAsync()中的行为 - Behaviour of ForkJoinPool in CompletableFuture.supplyAsync() CompletableFuture.supplyAsync() 没有 Lambda - CompletableFuture.supplyAsync() without Lambda `CompletableFuture.completedFuture ... thenAccept`是否等同于顺序处理? - is `CompletableFuture.completedFuture … thenAccept` equivalent to sequential processing? 如何将CompletableFuture.supplyAsync与PriorityBlockingQueue一起使用? - How do I use CompletableFuture.supplyAsync together with PriorityBlockingQueue? 简单的 CompletableFuture.supplyAsync() 导致 IllegalMonitorStateException 错误 - Simple CompletableFuture.supplyAsync() leads to IllegalMonitorStateException error 使用CompletableFuture.supplyAsync返回多个值 - Returning multiple values with CompletableFuture.supplyAsync CompletableFuture.supplyAsync 代码的代码覆盖率 - code coverage of CompletableFuture.supplyAsync code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM