【发布时间】:2014-06-12 18:41:24
【问题描述】:
我正在玩 Java 8 可完成的期货。我有以下代码:
CountDownLatch waitLatch = new CountDownLatch(1);
CompletableFuture<?> future = CompletableFuture.runAsync(() -> {
try {
System.out.println("Wait");
waitLatch.await(); //cancel should interrupt
System.out.println("Done");
} catch (InterruptedException e) {
System.out.println("Interrupted");
throw new RuntimeException(e);
}
});
sleep(10); //give it some time to start (ugly, but works)
future.cancel(true);
System.out.println("Cancel called");
assertTrue(future.isCancelled());
assertTrue(future.isDone());
sleep(100); //give it some time to finish
使用 runAsync 我安排执行等待闩锁的代码。接下来我取消未来,期望内部抛出一个中断的异常。但似乎线程在 await 调用上仍然被阻塞,即使未来被取消(断言通过),也永远不会抛出 InterruptedException。使用 ExecutorService 的等效代码按预期工作。这是 CompletableFuture 还是我的示例中的错误?
【问题讨论】:
-
你能用
Executors.newFixedThreadPool和Executors.newWorkStealingPool重现这个问题吗?比较两个不同的 executor 实现,而不是比较 futures 和可完成的 futures,这个问题会更清楚。 -
JavaDoc 说 cancel(true) 会使用 CancellationException 取消,但您没有发现。
-
@nosid 你说得对,newWorkStealingPool 显然也不支持取消
标签: java multithreading java-8 completable-future