Java Graceful Downtime Implementation

Source: Internet
Author: User

In some scenarios, we design the service to take into account when the application stopped/stopped to do some clean-up operations, such as: Shut down the thread, release the connection resources.
In the Java language, we can register hooks through the Runtime.getruntime (). Addshutdownhook () method to guarantee smooth exit of the program as follows:

Runtime.getruntime (). Addshutdownhook (New Thread (new Runnable () {
            @Override public
            void Run () {

                SYSTEM.OUT.PRINTLN ("Hook Running");
            })
        ;

After registering the hook thread, the program receives the exit signal and keeps the program running until the hook thread finishes, stopping and exiting all of the program's threads.

Import Java.util.concurrent.TimeUnit;  /** * ${description} * * @author Ricky Fung * @create 2016-11-22 13:33 * * public class Shutdownhooktest {public
            static void Main (string[] args {//start 5 threads to perform task for (int i=0;i<5;i++) {final int id = i; New Thread (New Runnable () {@Override public void run () {Sy
                    Stem.out.println ("Thread_" +id+ "Start ...");
                    try {TimeUnit.SECONDS.sleep (ID);
                    catch (Interruptedexception e) {e.printstacktrace (); } System.out.println ("Thread_" +id+ "finish!");}).
        Start (); Runtime.getruntime (). Addshutdownhook (New Thread (new Runnable () {@Override public void
            Run () {System.out.println ("hook running ...");
    }
        })); }
}
Related Article

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.