Add infrastructure for better shutdown handling

This commit is contained in:
AsamK 2023-11-09 16:01:08 +01:00
parent cbbfc4ea6e
commit f252597002
2 changed files with 67 additions and 0 deletions

View file

@ -64,6 +64,7 @@ public class Main {
e.printStackTrace(System.err); e.printStackTrace(System.err);
status = 2; status = 2;
} }
Shutdown.shutdownComplete();
System.exit(status); System.exit(status);
} }

View file

@ -0,0 +1,66 @@
package org.asamk.signal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import sun.misc.Signal;
public class Shutdown {
private static final Logger logger = LoggerFactory.getLogger(Shutdown.class);
private static final CompletableFuture<Void> shutdown = new CompletableFuture<>();
private static final CompletableFuture<Void> shutdownComplete = new CompletableFuture<>();
private static boolean initialized = false;
public static void installHandler() {
if (initialized) {
return;
}
initialized = true;
Signal.handle(new Signal("INT"), Shutdown::handleSignal);
Signal.handle(new Signal("TERM"), Shutdown::handleSignal);
Runtime.getRuntime().addShutdownHook(Thread.ofPlatform().unstarted(() -> {
logger.debug("JVM is shutting down");
if (!shutdown.isDone()) {
triggerShutdown();
}
try {
logger.debug("Waiting for app to shut down");
shutdownComplete.get();
logger.debug("Exiting");
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}));
}
public static void triggerShutdown() {
logger.debug("Triggering shutdown.");
shutdown.complete(null);
}
public static void waitForShutdown() throws InterruptedException {
try {
shutdown.get();
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
public static void registerShutdownListener(Runnable action) {
shutdown.thenRun(action);
}
static void shutdownComplete() {
shutdownComplete.complete(null);
}
private static void handleSignal(Signal signal) {
logger.info("Received {} signal, shutting down ...", signal);
triggerShutdown();
}
}