I’ve been looking at a clean way of implementing shut down logic for a server that I’m developing.
There are two approaches that I could take:
- Use Runtime.addShutdownHook() to gracefully handle shut down when Ctrl-C is issued.
- Listen to a designated shut down port (similar to what Tomcat does) and shut down when the appropriate command is received through that port.
The first approach is simple to implement but using Ctrl-C as the shut down mechanism doesn’t seem elegant.
The second approach seems cleaner, but requires the overhead of configuring and listening to another port.
I would appreciate advice on this, particularly if you can suggest a better alternative.
I’m not sure you have a choice 😉
Depending on how and where your server runs, and what kind of resources you use, you will need to implement a shutdown hook for the odd case where someone actually goes and ctrl+c’s the whole thing (regardless of it being on the user manual or not)
On the other hand, and for regular usage, having a way to push a shutdown command seems like the best way to go. You might not need a dedicated port or command set, though; you might be able to include it into your normal, existing interface.