【发布时间】:2014-12-15 22:22:56
【问题描述】:
我正在寻找此处提出的问题的扩展:Does a Future timeout kill the Thread execution
鉴于以下代码 sn-p,我很想知道 TimeoutException 的捕获是否会在某种闭包中捕获超过时间限制的线程?即使主线程被 awaitTermination() 阻塞,这些也会捕获吗?这个实现似乎有效。 ...但到目前为止,我可能很幸运,没有出现死锁,也没有明显的竞争条件。
public List<T> setupThreads() throws InterruptedException, ExecutionException {
if (nThreads < 1 || timeout < 1 || preRunObjects == null || preRunObjects.isEmpty()) {
return null;
}
List<T> postRunObjects = new ArrayList<>();
List<Future<T>> futures = new ArrayList<>();
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
for (T runMe : preRunObjects) {
futures.add(executor.submit(runMe));
}
for (Future<T> f : futures) {
try {
postRunObjects.add(f.get(timeout, TimeUnit.SECONDS));
} catch (TimeoutException te) {
log.warn("A thread has failed to run in time! It will be canceled.");
if(!f.isDone()) {
f.cancel(true);
if(f.isCancelled()) {
log.info("Punishment complete!");
}
}
}
}
executor.shutdown();
executor.awaitTermination((timeout * postRunObjects.size()), TimeUnit.SECONDS);
return postRunObjects;
}
【问题讨论】:
-
由于 Java 在 Java 7 之前没有闭包,并且从第一天开始就有异常,我认为答案是否定的。
-
主线程将阻塞在
f.get,awaitTermination只会在所有未来都超时或完成时运行。 -
james large 和 BevynQ 对这个问题有正确的答案。也就是说,这个问题被打破了。我错过了文档中关于future.get() 阻塞的部分。因此,在 awaitTermination() 运行时,我已经运行并完成了每个子线程,并且所有线程都处于不会导致 awaitTermination() 阻塞的状态。这将使它在代码 sn-p 中变得毫无意义。然而,我现在有一个更完整的画面。谢谢 Elliott Frisch,我实际上从未尝试在 6 中使用闭包,现在我很高兴我没有/不会尝试!
标签: java timeout closures threadpoolexecutor cancellation