How Do You Stop a Java Program Gracefully?
This short article provides readers with a way to gracefully stop a Java program in case your program may be doing something important.
Join the DZone community and get the full member experience.
Join For FreeSometimes you may want to stop your java program using SIGINT hitting your CTRL+C
. For example, your program may be doing something important, e.g., opening a server socket and waiting on a port or doing some background work on a thread pool. You want to stop it gracefully, shutting down your socket or the thread pool. For such scenarios, what you can do is add a shutdown hook to the java runtime. The following code demonstrates precisely that:
package com.bazlur;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Day008 {
public static void main(String[] args) {
var executorService = Executors.newSingleThreadExecutor();
executorService.submit((Runnable) () -> {
while (true) {
doingAStupendousJob();
}
});
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
executorService.shutdown();
if (executorService.awaitTermination(100, TimeUnit.MILLISECONDS)) {
System.out.println("Still waiting 100ms...");
executorService.shutdownNow();
}
System.out.println("System exited gracefully");
} catch (InterruptedException e) {
executorService.shutdownNow();
}
}));
}
private static void doingAStupendousJob() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Published at DZone with permission of A N M Bazlur Rahman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments