【问题标题】:Does a Java try catch use a closure to catch terminating child threads while the parent thread is blocked?当父线程被阻塞时,Java try catch 是否使用闭包来捕获终止的子线程?
【发布时间】: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.getawaitTermination 只会在所有未来都超时或完成时运行。
  • james large 和 BevynQ 对这个问题有正确的答案。也就是说,这个问题被打破了。我错过了文档中关于future.get() 阻塞的部分。因此,在 awaitTermination() 运行时,我已经运行并完成了每个子线程,并且所有线程都处于不会导致 awaitTermination() 阻塞的状态。这将使它在代码 sn-p 中变得毫无意义。然而,我现在有一个更完整的画面。谢谢 Elliott Frisch,我实际上从未尝试在 6 中使用闭包,现在我很高兴我没有/不会尝试!

标签: java timeout closures threadpoolexecutor cancellation


【解决方案1】:

我很想知道 TimeoutException 的捕获是否会在某种闭包中捕获超过时间限制的线程?即使主线程被 awaitTermination() 阻塞,这些也会捕获吗?

在某种封闭?有关系吗?

for(...) 循环完成之后,您的主线程不会调用executor.awaitTermination()

另请注意:所有f.get() 调用都是连续的:您的主线程将等待timeout 秒以获得第一个结果,然后它将等待timeout 更多下一个结果的秒数,...和下​​一个,...和下​​一个,...等等。

这就是你的想法吗?还是您的意思是等待不超过timeout total 秒?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 2016-09-26
    • 2017-12-20
    • 1970-01-01
    相关资源
    最近更新 更多