代码框架
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
class OrderResult {
// 假设订单结果类包含金额等属性
private double amount;
public OrderResult(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
public class DistributedOrderProcessing {
public static void main(String[] args) {
List<CompletableFuture<OrderResult>> futures = new ArrayList<>();
// 模拟多个子任务,创建CompletableFuture对象并添加到列表中
for (int i = 0; i < 5; i++) {
CompletableFuture<OrderResult> future = CompletableFuture.supplyAsync(() -> {
// 模拟子任务处理,可能抛出异常
if (Math.random() < 0.1) {
throw new RuntimeException("Sub - task failed");
}
return new OrderResult(Math.random() * 100);
});
futures.add(future);
}
CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allFutures.thenAccept((v) -> {
double totalAmount = 0;
int orderCount = 0;
for (CompletableFuture<OrderResult> future : futures) {
try {
OrderResult result = future.get();
totalAmount += result.getAmount();
orderCount++;
} catch (Exception e) {
// 处理子任务异常
System.out.println("Exception occurred in sub - task: " + e.getMessage());
}
}
System.out.println("Total amount: " + totalAmount);
System.out.println("Order count: " + orderCount);
}).exceptionally((e) -> {
// 处理allOf操作本身的异常
System.out.println("Exception in allOf operation: " + e.getMessage());
return null;
});
}
}
异常处理说明
- 子任务异常:在每个子任务的
supplyAsync
中,如果子任务执行时抛出异常,在thenAccept
的遍历中,通过future.get()
获取结果时会捕获到异常,并在catch
块中进行处理,这里简单打印异常信息。
allOf
操作异常:使用exceptionally
方法处理allOf
操作本身可能出现的异常,例如在添加到allOf
的CompletableFuture
对象中有已经处于异常完成状态的情况,这里同样简单打印异常信息。