Sometimes you may want to stop your java program using SIGINT hitting your CTRL+C
. For example, your program may be doing something important, e.g., opening a server socket and waiting on a port or doing some background work on a thread pool. You want to stop it gracefully shutting down your socket or the thread pool.
For such scenarios, what you can do is, add a shutdown hook to the java runtime. The following code demonstrates precisely that.
for copy/paste pleasure: https://github.com/rokon12/100DaysOfJava/blob/main/src/main/java/com/bazlur/Day008.java