有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何检查ExecutorService是否“健康”且正常工作?

我正在为我的公司开发一个无gui的桌面应用程序,它计划总是在后台运行,从网站检索信息(通过HtmlUnit)并更新数据库中的一些行。 我正在使用ExecutorService提交加载网站的任务,以便设置超时。这样:

private ExecutorService taskExecutor = Executors.newFixedThreadPool(1);
private long timeout = 60000L;

private Page loadSite(Loader<Page> c) {
    Page page;
    Future<Page> result = taskExecutor.submit(c);
    try {
        page = result.get(timeout, TimeUnit.MILLISECONDS);
    } catch (TimeoutException | ExecutionException | InterruptedException ex) {
        close();
        result.cancel(true);
        throw new HandledWebException(ex);
    }

    return page.getEnclosingWindow().getEnclosedPage();
}

问题是:

  • 我是否应该检查我的taskExecutor对象是否能够在submit调用之前安排任务,并在必要时重新实例化它?(延长执行时间对我来说似乎是一种威胁)
  • 如果提交的任务未能完成,我是否必须关闭并重新实例化taskExecutor

共 (1) 个答案

  1. # 1 楼答案

    1)我是否应该检查我的taskExecutor对象是否能够在提交调用之前安排任务,并在必要时重新启动它

    2)如果提交的任务未能完成,我是否必须关闭并重新启动taskExecutor

    这两个问题都没有必要

    公共静态执行器服务newFixedThreadPool(int-nThreads)

    Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.