Is it possible to catch the Ctrl+C signal in a java command-line application? I'd like to clean up some resources before terminating the program.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can attach a shutdown hook to the VM which gets run whenever the VM shuts down:
The thread you pass as shutdown hook has to follow several rules, though, so read the linked documentation carefully to avoid any problems. This includes ensuring thread-safety, quick termination of the thread, etc.
Also, as commenter Jesper points out, shutdown hooks are guaranteed to run on normal shutdown of the VM but if the VM process is terminated forcibly they don't. This can happen if native code screws up or if you forcibly kill the process (
kill -9
,taskkill /f
).But in those scenarios all bets are off anyway, so I wouldn't waste too much thought on it.
Just for quick console testing purposes...