[英]Async call of a FeignClient Springboot with CompletableFuture
[英]CompletableFuture: after async call, process result in current thread
我试图了解Java 8中的CompletableFuture接口。我当前的代码是:
CompletableFuture.supplyAsync(() -> wachtwoordBijwerken(gebruikersnaam, wachtwoord))
.thenAccept(this::saveOrUpdateGebruiker)
.exceptionally(e ->
{
log.error("Fout bij het bijwerken van wachtwoord voor gebruiker: " + gebruikersnaam, e);
return null;
});
我希望新创建线程中的异步调用完成后,调用saveOrUpdateGebruiker()
将在主线程中运行。 但是,该调用仍在另一个线程中,这会在基础的hibernate实现中引起问题。
有没有办法使用CompletableFuture
进行非阻塞的异步调用,并且仍然能够在当前线程中使用结果?
不是自动不会。 当执行CompletableFuture
提供的带有supplyAsync
, thenAccept
等的操作时,它们全部由线程thenAccept
的线程执行。 这样一来,您就可以按照自己的意愿在主线程中执行“射击后遗忘”操作并继续工作。
如果要在CompletableFuture
完成之后在当前线程中执行工作,则需要等待并使用isDone()
和/或get()
方法检查其是否完成。
但是,如果执行此操作,则使用CompletableFuture
与普通的Future
(例如FutureTask
)相比没有任何优势。
对于您的方案,使用CompletableFuture是一个过大的选择。 CompletableFuture在设计上是非阻塞性的,当作业完成时,您可以使用join()或轮询isDone()方法收集其结果,然后进行同步操作。 如果只有一个进程继续将任务发送到专用ThreadPool,那么使用CompletableFuture不会比CompletionService或ExecutorService更具优势。 我写了一个简单的博客,介绍了与传统Threadpool相比适合CompletableFuture的一种情况: https ://medium.com/@zhongzhongzhong/beauty-of-completablefuture-and-where-should-you-use-use-it-6ac65b7bfbe
您可以使用thenAcceptAsync(Runnable,Executor)方法,该方法使用您传入的执行程序参数执行回调,该方法最终可能与调用方所使用的相同
这样,您可以控制用于执行回调代码的线程/执行程序
另请参阅: 这个与Stackoverflow相关的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.