2012-07-02 112 views
0

當關閉ExecutorService已終止的應用程序時,我遇到了一個問題......處理此問題的好方法是什麼?從主類使用ExecutorService執行Java關閉鉤子

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

我發現,如果我做擴展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。因此,在關閉掛鉤啓動之前可能會關閉ExecutorService