2014年11月25日 星期二

[ Java 常見問題 ] How to Catching Ctrl+C in Java

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 program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
* The virtual machine is terminated in response to a user interrupt, such as typing Ctrl+C, or a system-wide event, such as user logoff or system shutdown.

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
  1. Thread.start{  
  2.     while(true// Infinite loop  
  3.     {  
  4.         printf("Hello!\n")  
  5.         sleep(1000// Say hello each second until you Ctrl+C to terminate  
  6.     }  
  7. }  
  8.   
  9. Runtime.addShutdownHook {  
  10.     printf("Bye!\n")  
  11. }  
When you execute this .groovy, the background thread will print "Hello" each second until you terminate the process:
> groovy Test.groovy
Hello!
Hello! 
<< Enter Ctrl+C here
Bye! << The shutdown hook is executed!


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...