Reputation: 21991
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();
}
});
Upvotes: 0
Views: 2121
Reputation: 1256
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.
Upvotes: 1