简体   繁体   English

CompletableFuture-使用thenapply与使用lambda块的优势

[英]Completablefuture - advantage of using thenapply vs using lambda block

I want to know advantage of using lambda block vs using thenApply() . 我想知道使用lambda块与使用thenApply()

I understand that the lambda block always gets executed by same thread executing the function in supplyAsync() whereas thenApply() block can be executed by the thread executing supplyAsync() or by caller thread. 我了解到lambda块总是由执行supplyAsync()的函数的同一线程执行,而thenApply()块可以由执行supplyAsync()的线程或调用者线程执行。

I was also wondering that if thenApply() has to execute only after supplyAsync() function is executed, why would it be ever executed by caller thread. 我还想知道,如果thenApply()仅在执行supplyAsync()函数之后supplyAsync()执行,为什么调用者线程会执行它呢?

CompletableFuture.supplyAsync(() -> {return doSomethingAndReturnA();})
                 .thenApply(a -> convertToB(a));

CompletableFuture.supplyAsync(() -> {
    A a = doSomethingAndReturnA();
    convertToB(a);
});

With the lambda block, you have the guarantee that both methods are called in the same thread, without anything else running on that thread in between. 使用lambda块,可以保证在同一个线程中调用这两种方法,而在此线程之间没有其他任何运行。

thenApply() is more useful when you already have a CompletionStage / CompletableFuture (eg in a variable or returned by some method call) and you want to have subsequent processing on its result. 如果您已经具有CompletionStage / CompletableFuture (例如,在变量中或由某个方法调用返回),并且您希望对其结果进行后续处理,那么thenApply()会更加有用。

It is also useful when you want to have access to the intermediate result (here a ) outside the scope of the lambda, as you could just joint() on the intermediate CompletableFuture to access it. 当您想访问lambda范围之外的中间结果(此处a )时,它也很有用,因为您可以只对中间CompletableFuture上的joint()进行访问。

The more advanced thenApplyAsync() also allows you to process that intermediate result asynchronously, which is difficult in a lambda block. 更高级的thenApplyAsync()也允许您异步处理该中间结果,这在lambda块中很难实现。

In some cases you might simply choose one or the other based on readability. 在某些情况下,您可能只是基于可读性来选择一个或另一个。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM