[Java] intercepts Ctrl + C and system shutdown Signals

Source: Internet
Author: User
In the Java window ProgramPress Ctrl + C to forcibly stop the Java program. Clicking the close button in the window also forces the program to stop.

Runtime. getruntime (). addshutdownhook (hooker) allows you to register a thread and execute it after system. Exit () and before finalize is called.
According to the document, if multiple programs have registered hooker, they will be enabled at the same time, and the order is not guaranteed. For example, if you want to send messages through JMS before closing, it is very likely that the JMS service has been closed.

Google tells us that there is another good way to use sun's exclusive secret technology to directly intercept system signals. Note: It is invalid on non-Sun JVM.
Web: http://www.smotricz.com/kabutz/Issue043.html

Simple application:
Signalhandler handler = new signalhandler (){
Public void handle (signal sig ){
Server. This. Exit (0 );
}
};
Signal. Handle (new signal ("int"), Handler); // hook Ctrl + c
Signal. Handle (new signal ("term"), Handler); // hook Alt + F4

OK. Now the program can be closed for limited processing ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.