简体   繁体   English

如果使用 CompletableFuture 失败,如何并行调用独立函数并抛出异常

[英]How to call independent functions parallel and throw exception if one fails using CompletableFuture

I am try to do something like我正在尝试做类似的事情

Optional<Order> orderDetails = orderRepository.findById(orderId);
if (orderDetails.isEmpty())
    throw new OrderNotFoundException("Order not found!");

Optional<User> UserDetails = userRepository.findById(userId);
if (UserDetails.isEmpty())
    throw new UserNotFoundException("User not found!");

List<OrderItem> ItemDetailsList = orderItemRepository.findByOrderIdOrderByItemIdAsc(orderId);

Where I want to call these three Services methods together in a non-blocking way, but I want to throw error if any one of those call fails and dont proceed furthur.我想以非阻塞方式一起调用这三个服务方法,但是如果其中任何一个调用失败并且不继续进行,我想抛出错误。 If all of the above works, then execute the later logic.如果以上都可行,则执行后面的逻辑。

I am thinking of using allOff() then after that use get on the Futures and do the above logic of throwing error when the Optional is empty?我正在考虑使用allOff()然后使用 get on Futures 并在 Optional 为空时执行上述引发错误的逻辑?

Is there better way of doing it?有更好的方法吗? ie if one of them fails and others are still running, throw error and abort the other running tasks.,如果其中一个失败而其他仍在运行,则抛出错误并中止其他正在运行的任务。

CompletableFuture is the wrong tool for the job here. CompletableFuture在这里的工作是错误的工具。 And the main problem is that you want:主要问题是您想要:

"...throw error and abort the other running tasks" “...抛出错误并中止其他正在运行的任务”

If you read what CompletableFuture::cancel documentation says, you will see that:如果您阅读CompletableFuture::cancel文档中的内容,您会看到:

mayInterruptIfRunning – this value has no effect in this implementation because interrupts are not used to control processing. mayInterruptIfRunning——这个值在这个实现中没有影响,因为中断不用于控制处理。

So, even if you call cancel , this will not interrupt your tasks, they will still continue to completition.因此,即使您调用cancel ,这也不会中断您的任务,它们仍然会继续完成。 As such, your fundamental requirement can not be met.因此,您的基本要求无法满足。

There is a way with creating a custom pool of threads for that CompletableFuture that you want to cancel and shut down the pool, as an example here .有一种方法可以为您想要取消并关闭池的CompletableFuture创建自定义线程池, 例如此处 But this is not trivial to do and your threads need to respond to interrupts properly.但这并非易事,您的线程需要正确响应中断。

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

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