我使用的是带有调度程序的AbstractScheduledService。一个简单的模式,如:
class MyService extends AbstractScheduledService {
// KEEP THIS VAR IN MIND W.R.T the SHUTDOWN_HOOK BELOW
public static volatile boolean keepRunning = true;
protected void startUp() throws Exception {
// startup stuff
}
protected void runOneIteration() throws Exception {
// main logic stuff
}
protected void shutDown() throws Exception {
// shutdown stuff
}
protected Scheduler scheduler() {
return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.SECONDS);
}
}现在,我想实现一个典型的关闭钩子,如下所示:(下面的代码片段将在main方法中)
final Thread mainThread = Thread.currentThread();
LOGGER.debug("Adding the shutdown hook");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
keepRunning = false;
LOGGER.debug("The shutdown hook was engaged. Setting keepRunnning to false.");
try {
// Is this appropriate?
mainThread.join();
} catch (InterruptedException e) {
// handle exception here
}
}
});shutdown钩子来自典型的文档示例。它似乎不能很好地与Guava服务模式一起工作,因为服务本身运行在不同的线程上。
我的服务在runOneIteration()逻辑中有一个轮询循环。我希望它完成手头的当前任务,然后当is看到keepRunning现在是false时,优雅地关闭它,因为关闭钩子在最近的过去某段时间被占用,当时它正忙于当前的迭代。
有什么想法可以优雅地做到这一点(完成当前迭代,然后关闭)?
发布于 2012-08-31 21:13:57
难道你不会直接调用stopAndWait()吗?
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
service.stopAsync().awaitTerminated(60, TimeUnit.SECONDS);
}
});https://stackoverflow.com/questions/12206248
复制相似问题