Graceful Shutdown With Join Timeout

Stop a worker with a bounded Thread.join timeout, then escalate to interrupt and join again so shutdown cannot hang on a blocked thread.

JavaResilience

Code

snippet
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());
    }
}

Inside the snippet

Graceful Shutdown With Join Timeout reduces to the class GracefulStop.

One loop does the cycling here: while (!Thread.currentThread().isInterrupted()).

Watch out for

  • There is no dependency tree here — the platform is the whole dependency.

Putting it to use

Expect labeled output — indexer flushed and stopped, graceful window expired, escalating to interrupt, shutdown complete, alive= — when the file runs.

Core lines

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

Interactive Tools for This Topic

FAQ

What does Graceful Shutdown With Join Timeout print when run?
Execute the whole file; each printed line is prefixed with a label like `indexer flushed and stopped`, `graceful window expired, escalating to interrupt`, `shutdown complete, alive=`.