簡體   English   中英

Java關閉鈎子與ExecutorService

[英]Java shutdown hooks with 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();
        }
    });

我發現,如果我創建了一個擴展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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM