I have a simple Spring application that needs to save state to some files after being killed, but calling kill [PID]
on Debian 10 will not trigger the @PreDestroy
method I have registered. Here’s my state class and main class:
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class GlobalState {
private VerificationTokens verificationTokens;
@PreDestroy
public void onDestroy() {
System.out.println("Saving state...");
try {
//write to files
} catch (IOException e) {
e.printStackTrace();
}
}
@PostConstruct
public void postConstruct() {
try {
//load from files
} catch (IOException e) {
System.err.println("Failed to load saved application state");
e.printStackTrace();
}
}
}
@SpringBootApplication
@EnableScheduling
public class CrewsApplication {
public static void main(String[] args) {
initializeDirectories();
SpringApplication.run(MyApplication.class, args);
}
public static void initializeDirectories() {
File state = new File("./state");
if (!state.exists()) state.mkdirs();
}
}
The hook will run in my IDE (IntelliJ IDEA) after stopping the application, but won’t when I kill the process after deploying it on Linux. I’ve already added the -Xcs
JVM argument to toggle off thread dumps instead of killing the program. Why isn’t this working?