当其中一个正在运行的任务引发异常时,我需要取消所有计划的但尚未运行的CompletableFuture任务。
尝试以下示例,但大多数时候主方法不会退出(可能由于某种类型的死锁)。
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
并在每个cancel
上调用CompletableFuture
。但是我不喜欢从CancellationException
中抛出join
。
答案 0 :(得分:5)
您应该记住
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);
}
}
});
因此ExecutorService
对CompletableFuture
一无所知,因此,它不能一般取消。它所具有的只是一项工作,表示为Runnable
的实现。
换句话说,shutdownNow()
将阻止执行待处理的作业,因此,剩余的期货将无法正常完成,但不会取消。然后,您在join()
返回的未来上调用allOf
,由于未完成的期货,它将永远不会返回。
但是请注意,计划的工作确实会在做任何昂贵的事情之前检查未来是否已经完成。
因此,如果您将代码更改为
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();
可运行对象一旦取消关联的将来就不会执行。由于取消和普通执行之间存在竞争,将动作更改为
可能会有所帮助.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
而不是触发异常。
如果将两个cancel(false)
调用替换为complete(null)
,则会产生类似的效果,可运行对象将不会对已完成的期货执行,但是allOf
将报告原始异常,因为这是唯一的例外。而且它还有另一个积极的作用:用null
值完成要比构造CancellationException
便宜得多(对于每个未决的将来),因此通过complete(null)
强制执行的速度要快得多,从而防止了更多操作执行的未来。
答案 1 :(得分:1)
另一种仅依靠CompletableFuture
的解决方案是使用“取消”将来,这将导致所有未完成的任务在完成后被取消:
Set<CompletableFuture<?>> tasks = ConcurrentHashMap.newKeySet();
CompletableFuture<Void> canceller = new CompletableFuture<>();
for(int i = 0; i < 1000; i++) {
if (canceller.isDone()) {
System.out.println("Canceller invoked, not creating other futures.");
break;
}
//LockSupport.parkNanos(10);
final int id = i;
CompletableFuture<?> c = CompletableFuture
.runAsync(() -> {
//LockSupport.parkNanos(1000);
System.out.println("Running: " + id);
if(id == 400) throw new RuntimeException("Exception from: " + id);
}, executionService);
c.whenComplete((v, ex) -> {
if(ex != null) {
canceller.complete(null);
}
});
tasks.add(c);
}
canceller.thenRun(() -> {
System.out.println("Cancelling all tasks.");
tasks.forEach(t -> t.cancel(false));
System.out.println("Finished cancelling tasks.");
});