Source From Here
Question
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.
How-To
You can attach a shutdown hook to the VM which gets run whenever the VM shuts down in response to two kinds of events:
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.
Example Code
Below is the sample groovy code which will run a infinite loop in background thread:
- Test.groovy
When you execute this .groovy, the background thread will print "Hello" each second until you terminate the process:
Question
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.
How-To
You can attach a shutdown hook to the VM which gets run whenever the VM shuts down in response to two kinds of events:
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.
Example Code
Below is the sample groovy code which will run a infinite loop in background thread:
- Test.groovy
- Thread.start{
- while(true) // Infinite loop
- {
- printf("Hello!\n")
- sleep(1000) // Say hello each second until you Ctrl+C to terminate
- }
- }
- Runtime.addShutdownHook {
- printf("Bye!\n")
- }
沒有留言:
張貼留言