我正在寻找这里提出的问题的扩展:Does a Future timeout kill the Thread execution
鉴于以下代码片段,我很想知道TimeoutException的catch是否会在某种闭包中捕获超过timelimit的线程?即使主线程被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;
}
答案 0 :(得分:0)
我很想知道TimeoutException的catch是否会在某种闭包中捕获超过timelimit的线程?即使主线程被awaitTermination()阻塞,它们也会捕获吗?
某种封闭?这有关系吗?
executor.awaitTermination()
循环完成之后,
另请注意:所有for(...)
次调用都是顺序的:您的主要线程将等待f.get()
秒,以获得第一个结果,然后它将等待timeout
更多秒为下一个结果,...和下一个,...和下一个,......等等。
这是你的想法吗?或者您的意思是等待不超过timeout
总秒?