I want to implement graceful shutdown for the following java service. when a SIGTERM
signal is sent, I want the program to keep processing the current task, but exit the loop. How can I achieve this?
@Service
@RequiredArgsConstructor
public class AsyncService {
@Async
public void run() {
while (no SIGTERM) {
// Some process
}
// More process
}
}
Version: Java 17, Spring Boot v3.3.1, Spring v6.1.10
I have found the answer.
@Slf4j
@Configuration
public class ShutdownHook {
@Getter
private static boolean shutdown;
@PostConstruct
private void addShutdownHook() {
shutdown = false;
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
log.info("Shutdown hook triggered!");
shutdown = true;
}));
log.info("Added shutdown hook.");
}
}
@Service
@RequiredArgsConstructor
public class AsyncService {
@Async
public void run() {
while (!ShutdownHook.isShutdown()) {
// Some process. This will not be executed after shutdown is triggered.
}
// More process. This will be executed even after shutdown is triggered.
// Notes:
// Spring by default have grace period of 30 seconds.
// You need to finish all process within that period or shutdown will be forced.
}
}