确定ExecutorService的关闭时间

时间:2011-09-21 20:35:57

标签: java multithreading concurrency executorservice

我有一个处理某些任务的ExecutorService。客户端主题可以shutdown()上调用ExecutorService。我希望在ExecutorService完全关闭后运行一些清理代码。是否存在在ExecutorService完成关闭后运行回调方法的机制。

注意:

  1. 无法致电shutdownNow()
  2. 清理代码必须在 shutdown()完成后运行
  3. ExecutorServicenewCachedThreadPoolExecutor();

3 个答案:

答案 0 :(得分:2)

启动另一个线程/ executor-managed-runnable,在循环中的try-catch语句中检查ExecutorService.awaitTermination(...),直到它返回true,然后运行关闭处理代码。循环是必要的,因为该方法可能在中断时过早返回。

这样的事情:

public class ShutdownHandler implements Runnable {

    private final ExecutorService service;

    public ShutdownHandler(final ExecutorService service) {
        this.service = service;
    }

    @Override
    public void run() {
        boolean terminated = false;
        while (!terminated) {
            try {
                terminated = service.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
            } catch (final InterruptedException ex) {
                // check again until terminated
            }
        }

        // your shutdown handling code here
    }
}

答案 1 :(得分:1)

我会扩展和覆盖:

public class MyExecutorService extends ThreadPoolExecutor {
    @Override
    public void shutdown() {
        super.shutdown();
        // do what you need to do here
    }
}

像这样的东西

答案 2 :(得分:1)

好吧,如果你调用executorService.invokeAll(myListOfCallableTasks)和他们的executorService.shutDown()调用的线程将阻塞,直到完成所有任务:

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAll(java.util.Collection