java - 在 ScheduledThreadPoolExecutor 中终止之前等待任务完成

标签 java multithreading concurrency scheduled-tasks

我有一个 Runnable 实现,它执行一些可能需要一些时间的工作,我尝试使用 ScheduledThreadPoolExecutorscheduleAtFixedRate 方法来安排它。现在我想确保关闭是正常的,这意味着,在终止之前,应该允许任务完全运行。我编写了以下关闭代码。

 public void shutDown() throws Exception {
    try {
        LOG.info("Gracefully shutting down executor");
        executor.shutdown();
        if (!executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
            // cancels currently executing tasks.
            LOG.info("Executor is still alive. Forcing executor thread pool to shut down");
            executor.shutdownNow();

            // Wait a while for tasks to respond to being cancelled
            if (!executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
                LOG.fatal("Executor thread pool did not terminate");
                throw new Exception("Unable to shut down executor thread pool forcefully");
            }
            LOG.info("Executor shut down.");
        }
    } catch (Exception e) {
        LOG.error("Exception shutting down executor", e);
        throw e;
    }
}

但问题是,我必须明确指定等待时间,并且我无法提前预测任务所需的时间。有没有办法让执行器无限期地等待,直到执行任务完成,而不必提及等待时间?或者有更好的方法来处理上述场景吗?

谢谢

吉腾德拉

最佳答案

最简单的解决方案就是“过度配置”。我建议您使用一个很大的超时期限,决不能超过单个任务执行所需的时间,例如:

// do you have tasks that can take more than 2^63 - 1 days to finish? :)
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

关于java - 在 ScheduledThreadPoolExecutor 中终止之前等待任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9104190/

相关文章:

java - org.hibernate.QueryParameterException : could not locate named parameter [templateId]

asp.net - 静态方法是否适合 Linq To SQL DAL?

multithreading - 线程共享局部变量吗?

java - 多线程环境下使用哪些Java集合类比较好

javascript - 如何在没有冲突的 Node 中创建 tmp 目录

java - SwingWorker 的问题

java - WALA :“Could not create a entrypoint callsites:” 问题

java - 在Java中检查两个 double 之间的相等性的好方法是什么

java - 如何使用java将Thread实例保存在数据库中

concurrency - esper和update listener并发