java - 从 CompletableFuture 调用 ExecutorService.shutdownNow

标签 java java-8 java-threads completable-future

当其中一个已在运行的任务抛出异常时,我需要取消所有已安排但尚未运行的 CompletableFuture 任务。

尝试了以下示例,但大多数时候 main 方法不会退出(可能是由于某种类型的死锁)。

public static void main(String[] args) {
    ExecutorService executionService = Executors.newFixedThreadPool(5);

    Set< CompletableFuture<?> > tasks = new HashSet<>();

    for (int i = 0; i < 1000; i++) {
        final int id = i;
        CompletableFuture<?> c = CompletableFuture

        .runAsync( () -> {
            System.out.println("Running: " + id); 
            if ( id == 400 ) throw new RuntimeException("Exception from: " + id);
        }, executionService )

        .whenComplete( (v, ex) -> { 
            if ( ex != null ) {
                System.out.println("Shutting down.");
                executionService.shutdownNow();
                System.out.println("shutdown.");
            }
        } );

        tasks.add(c);
    }

    try{ 
        CompletableFuture.allOf( tasks.stream().toArray(CompletableFuture[]::new) ).join(); 
    }catch(Exception e) { 
        System.out.println("Got async exception: " + e); 
    }finally { 
        System.out.println("DONE"); 
    }        
}

最后的打印输出是这样的:

Running: 402
Running: 400
Running: 408
Running: 407
Running: 406
Running: 405
Running: 411
Shutting down.
Running: 410
Running: 409
Running: 413
Running: 412
shutdown.

尝试在单独的线程上运行 shutdownNow 方法,但在大多数情况下,它仍然会产生相同的死锁。

知道是什么导致了这种僵局吗?

当抛出异常时,您认为取消所有已安排但尚未运行的 CompletableFuture 的最佳方法是什么?

正在考虑迭代 tasks 并在每个 CompletableFuture 上调用 cancel。但我不喜欢的是从 join 中抛出 CancellationException

最佳答案

你应该记住这一点

CompletableFuture<?> f = CompletableFuture.runAsync(runnable, executionService);

基本上等同于

CompletableFuture<?> f = new CompletableFuture<>();
executionService.execute(() -> {
    if(!f.isDone()) {
        try {
            runnable.run();
            f.complete(null);
        }
        catch(Throwable t) {
            f.completeExceptionally(t);
        }
    }
});

因此 ExecutorServiceCompletableFuture 一无所知,因此,通常 无法取消它。它所拥有的只是一些工作,表示为 Runnable 的实现。

换句话说,shutdownNow() 将阻止挂起作业的执行,因此,剩余的 futures 将不会正常完成,但不会取消它们。然后,您对 allOf 返回的 future 调用 join(),由于从未完成的 future ,它永远不会返回。

但请注意,预定作业会在做任何昂贵的事情之前检查 future 是否已经完成。

所以,如果您将代码更改为

ExecutorService executionService = Executors.newFixedThreadPool(5);
Set<CompletableFuture<?>> tasks = ConcurrentHashMap.newKeySet();
AtomicBoolean canceled = new AtomicBoolean();

for(int i = 0; i < 1000; i++) {
    final int id = i;
    CompletableFuture<?> c = CompletableFuture
        .runAsync(() -> {
            System.out.println("Running: " + id); 
            if(id == 400) throw new RuntimeException("Exception from: " + id);
        }, executionService);
        c.whenComplete((v, ex) -> {
            if(ex != null && canceled.compareAndSet(false, true)) {
                System.out.println("Canceling.");
                for(CompletableFuture<?> f: tasks) f.cancel(false);
                System.out.println("Canceled.");
            }
        });
    tasks.add(c);
    if(canceled.get()) {
        c.cancel(false);
        break;
    }
}

try {
    CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).join();
} catch(Exception e) {
    System.out.println("Got async exception: " + e);
} finally {
    System.out.println("DONE");
}
executionService.shutdown();

一旦相关的 future 被取消,runnables 将不会被执行。由于取消和普通执行之间存在竞争,因此将操作更改为可能会有所帮助

.runAsync(() -> {
    System.out.println("Running: " + id); 
    if(id == 400) throw new RuntimeException("Exception from: " + id);
    LockSupport.parkNanos(1000);
}, executionService);

模拟一些实际工作量。然后,您会看到遇到异常后执行的操作更少。

由于异步异常甚至可能在提交循环仍在运行时发生,因此它使用 AtomicBoolean 来检测这种情况并在这种情况下停止循环。


请注意,对于 CompletableFuture,取消和任何其他异常完成之间没有区别。调用 f.cancel(…) 等同于 f.completeExceptionally(new CancellationException())。因此,由于 CompletableFuture.allOf 报告异常情况下的任何异常,很可能是 CancellationException 而不是触发异常。

如果你用 complete(null) 替换两个 cancel(false) 调用,你会得到类似的效果,runnables 不会为已经完成的 futures 执行, 但 allOf 将报告原始异常,因为它是当时唯一的异常。它还有另一个积极的影响:用 null 值完成比构造一个 CancellationException(对于每个未决的 future )要便宜得多,所以通过 complete( null) 运行得更快,阻止更多的 futures 执行。

关于java - 从 CompletableFuture 调用 ExecutorService.shutdownNow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51957933/

相关文章:

`(a,b) -> a+b` 的 Java8 函数类型

java - 并行迭代大 HashMap

java - 从线程更新 gui(另一个类)

java - 订阅数据馈送的多个并发用户的设计和架构

java for循环问题

java - 如何使用 .net 代码执行 Amazon Cloud Search?

java - 窗口 xp 和 java 8

java - Spring Security数据库实现异常

java - 根据不同的条件分割字符串【需要优化】

java - 这个java线程程序的执行结果如何解读解释