Java关闭与ExecutorService挂钩

时间:2012-07-02 10:24:10

标签: java shutdown executorservice

我在关闭ExecutorService已终止的应用程序时遇到了问题...有什么好处理这个问题?

public class TradingLock {

    private ExecutorService executorService;
    private List<TradingHaltedListener> listeners=new ArrayList<>();
    public TradingLock(ExecutorService executorService) {
        super();
        this.executorService = executorService;
    }

    public void haltTrading(){
        for (final TradingHaltedListener listener: listeners){
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    listener.onTradingHalted();
                }
            });
        }
    }
    public synchronized void addTradingHaltedListener(TradingHaltedListener listener){
        this.listeners.add(listener);
    }
}

来自主类的关闭钩子:

Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            tradingLock.haltTrading();
        }
    });

1 个答案:

答案 0 :(得分:1)

我发现如果我创建一个扩展Thread的类并在其运行的addShutdownHook函数中使用它而没有任何问题。

 public class ShutdownHandler extends Thread {
      public void run(){
           // do all the work to clean up before shutting down
      }
 }

然后只需将其添加到主类

 Runtime.getRuntime().addShutdownHook(new ShutdownHandler());

修改

在阅读了有关ExecutorService的更多信息后,可能是应用程序开始退出时收到shutdownshutdownNow。应用程序开始关闭序列时会触发addShutdownHook。因此,在启动Shutdown挂钩之前,ExecutorService可能会关闭。