简体   繁体   中英

Java shutdown hooks with ExecutorService

I'm running into a problem when shutting down my application that the ExecutorService has been terminated...What's a good way to deal with this?

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);
    }
}

Shutdown hook from main class:

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

I found that if I make a class that extends Thread and use that inside the addShutdownHook function that it runs with no problems.

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

and then just add it in the main class

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

EDIT

After reading a little more about the ExecutorService , it could be that this is receiving a shutdown or shutdownNow when the application starts to exit. The addShutdownHook is fired when the application begins its shutdown sequence. So it is possible that the ExecutorService is shutdown before your Shutdown hook is started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM