gpt4 book ai didi

java - 如何使用关闭 Hook 优雅地停止 Guava AbstractScheduledService?

转载 作者:搜寻专家 更新时间:2023-11-01 02:13:32 25 4
gpt4 key购买 nike

我正在使用带有调度程序的 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);
}
}

现在,我想像这样实现一个典型的关闭钩子(Hook):(下面的代码片段将在 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
}
}
});

关闭 Hook 来自典型的文档示例。它似乎不适用于 Guava 服务模式,因为服务本身运行在不同的线程上。

我的服务在 runOneIteration() 逻辑中有一个轮询循环。我希望它完成手头的当前任务,然后在看到 keepRunning 现在为 false 时优雅地关闭,因为 Shutdown Hook 在最近一段时间忙于当前迭代时被接合。

有什么想法可以优雅地完成(完成当前迭代然后关闭)吗?

最佳答案

你不会直接调用 stopAndWait() 吗?

Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
service.stopAsync().awaitTerminated(60, TimeUnit.SECONDS);
}
});

关于java - 如何使用关闭 Hook 优雅地停止 Guava AbstractScheduledService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12206248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com