中断CompletableFuture的底层执行

问题描述 投票:0回答:1

我有这段代码:

 CompletableFuture<Void> timeoutFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                .orTimeout(1, TimeUnit.SECONDS); // Set a timeout for all futures combined

        CompletableFuture<List<MysticPlanetsNatalChartAspectResponse>> resultFuture = timeoutFuture
                .thenApply(v -> futures.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.toList()));

        // Cancel any remaining futures that may not have completed
        futures.forEach(future -> {
            if (!future.isDone() && !future.isCancelled()) {
                try {
                    future.cancel(true);
                } catch (Throwable c) {
                    //System.out.println(c.getMessage());
                }
            }
        });

但是异常没有被捕获,我在控制台中看到它:

2023-09-18T21:38:43,869+02:00 [http-nio-8080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.util.concurrent.CompletionException: java.util.concurrent.CancellationException] with root cause
java.util.concurrent.CancellationException: null
java multithreading asynchronous future completable-future
1个回答
0
投票

您可以在

.map()
方法中使用 lambda 表达式捕获异常,然后过滤列表的 null 值,如下所示:

CompletableFuture<List<MysticPlanetsNatalChartAspectResponse>> resultFuture = timeoutFuture
                .thenApply(v -> futures.stream()
                        .map(future -> {
                            try {
                                return future.join();
                            } catch (CompletionException | CancellationException ex) {
                                // Handle the exception here
                                return null;
                            }
                        })
                        // Filter out null results
                        .filter(Objects::nonNull) 
                        .collect(Collectors.toList()));
© www.soinside.com 2019 - 2024. All rights reserved.