Graceful Shutdown Ladder Await Termination
Stop a pool politely: shutdown stops intake, awaitTermination grants a grace period, shutdownNow interrupts stragglers, then one more wait confirms.
Code
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ShutdownLadder {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
for (int i = 1; i <= 4; i++) {
int job = i;
pool.submit(() -> {
try {
Thread.sleep(100);
return "job " + job + " done";
} catch (InterruptedException cancelled) {
Thread.currentThread().interrupt(); // 保留中断标记
return "job " + job + " cancelled";
}
});
}
// 第一段:不再收新任务,已提交的任务继续跑
pool.shutdown();
// 第二段:给一个宽限期
if (!pool.awaitTermination(50, TimeUnit.MILLISECONDS)) {
System.out.println("grace period over, cancelling stragglers");
// 第三段:中断未完成的任务;排队中未启动的任务被直接撤下
pool.shutdownNow();
}
boolean settled = pool.awaitTermination(2, TimeUnit.SECONDS);
System.out.println("terminated: " + settled);
}
}The structure at work
Graceful Shutdown Ladder Await Termination comes down to the class ShutdownLadder.
Iteration happens inside for (int i = 1; i <= 4; i++) — everything outside it runs once.
Caveats
- No dependencies section needed; the standard library is the whole story.
Using it
Printed lines carry labels — grace period over, cancelling stragglers, terminated: — when the file runs.
Key statements
ExecutorService pool = Executors.newFixedThreadPool(2);
Thread.currentThread().interrupt(); // 保留中断标记
return "job " + job + " cancelled";
return "job " + job + " done";
Interactive Tools for This Topic
FAQ
- What does Graceful Shutdown Ladder Await Termination print when run?
- The script runs standalone; its 2 labeled outputs include `grace period over, cancelling stragglers`, `terminated:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.