[英]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? 关闭我的应用程序时,我遇到了一个问题,那就是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);
}
}
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. 我发现,如果我创建了一个扩展Thread的类,并在没有问题的
addShutdownHook
函数内使用它,则可以正常运行。
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. 在阅读了有关
ExecutorService
更多信息之后,可能是在应用程序开始退出时,它正在接收shutdown
或shutdownNow
。 The addShutdownHook
is fired when the application begins its shutdown sequence. 当应用程序开始其关闭序列时,将触发
addShutdownHook
。 So it is possible that the ExecutorService
is shutdown before your Shutdown hook is started. 因此,有可能在启动Shutdown挂钩之前关闭
ExecutorService
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.