← 中文资源

简体中文版本

join 超时的优雅关闭流程

先用 join(timeout) 给工作线程一个有界的优雅退出窗口,超时后升级为 interrupt 并再次 join:关闭流程不会卡死在阻塞点上。

阅读英文原文

实现说明

join 超时的优雅关闭流程以类 GracefulStop为骨架。 迭代发生在 while (!Thread.currentThread().isInterrupted()) 内部——循环之外的语句只执行一遍。

使用要点

  • 每一步打印都带着自己的标签:indexer flushed and stopped、graceful window expired, escalating to interrupt、shutdown complete, alive=。

常见问题

运行「join 超时的优雅关闭流程」会打印什么?

运行文件本身,indexer flushed and stopped、graceful window expired, escalating to interrupt、shutdown complete, alive= 这些前缀各对应一段演示逻辑。

核心语句

Thread.currentThread().interrupt(); // restore the flag so the loop exits naturally
}

代码示例

public class GracefulStop {

    public static void main(String[] args) throws InterruptedException {
        Thread indexer = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    Thread.sleep(100); // stands in for a blocking point in shard scanning
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // restore the flag so the loop exits naturally
                }
            }
            System.out.println("indexer flushed and stopped");
        });
        indexer.start();

        // First grant a 250ms graceful window: join(timeout) blocks for at most that long, never forever
        indexer.join(250);
        // join's return value carries no signal: use isAlive to learn whether the thread actually finished
        if (indexer.isAlive()) {
            System.out.println("graceful window expired, escalating to interrupt");
            indexer.interrupt(); // break the sleep so the loop exits promptly
            indexer.join(1000);  // one more convergence window so shutdown cannot hang
        }
        System.out.println("shutdown complete, alive=" + indexer.isAlive());
    }
}