The JAVA Runtime.addshutdownhook () method {Gets the thread handle and invokes the freed resource before the program closes}__java

Source: Internet
Author: User

The Runtime#addshutdownhook method is to add a call hook to the virtual machine when the virtual machine shuts down and call the hook threads when the virtual machine shuts down. Or a very useful method, the most direct use is to monitor, because it is called when the virtual machine Pro shutdown, so it is natural to record the virtual organization shut this thing, and its related information; and then clean up the resources or something, you can do a hook thread, This will not be used in the application of these cleanup resources for the operation of finding the right location;

The following translation of this method of Java doc, found several translations on the internet, are from a version, a lot of mistakes, here to translate again:

Doc's first words are registers a new virtual-machine shutdown Hook. The translated version of the web translates it into registering a new virtual machine to close the hook, so the translation is wrong from a grammatical point of view, and the register and shutdown are all verbs in a sentence. A very simple word, is to register a new virtual body closed hook. You can use the following code to verify that the main program and these hook threads are not running in a JVM: Public static void main (String[] args)  {                        runtime.getruntime (). Addshutdownhook (New thread () {                 @Override                 public void run ()  {                        system.out.println ("I  am still alive! ");                         try {                            thread.currentthread ()-Sleep (1000);                             System.out.println (Runtime.getruntime (). toString ());                             System.out.println (Runtime.getruntime (). Hashcode ());                        } catch  ( Interruptedexception e)  {                            e.printstacktrace ();                        }                }           &NBSP});                       try {                thread.currentthread ()-Sleep (1000);            } catch  (interruptedexception e)  {                // TODO Auto-generated catch block                e.printstacktrace ();            }            System.out.println (RUNTIME.GETRUntime (). toString ());           system.out.println ( Runtime.getruntime (). Hashcode ());            System.out.println ("i am exit!");        }  

public static void Main (string[] args) {runtime.getruntime (). Addshutdownhook (New Thread ( {@Override public void run () {S
                                        Ystem.out.println ("I am Still alive!");
                                                try {thread.currentthread (). Sleep (1000);
                                                System.out.println (Runtime.getruntime (). toString ());
                                        System.out.println (Runtime.getruntime (). Hashcode ());
                                        catch (Interruptedexception e) {e.printstacktrace ();
                
                }
                        }
                });
                try {thread.currentthread (). Sleep (1000);
  catch (Interruptedexception e) {                      TODO auto-generated Catch block E.printstacktrace ();
                } System.out.println (Runtime.getruntime (). toString ());
                System.out.println (Runtime.getruntime (). Hashcode ());
        System.out.println ("I am exit!");
 }
The information of the runtime object printed in the main program is consistent with the runtime information printed in the hook thread.

The following begins a formal translation:

The Runtime#addshutdownhook method registers a new virtual organ close hook;

The Java Virtual machine shuts down only in response to the following two types of events:

1. When the last non daemon ends, the program ends normally, or when the Exit method (collectively, such as the System.exit () method) is invoked

2.JVM responds to user interrupts, such as typing a ^c or a system-level event, such as when the user exits the login or the system (the JVM's system, such as the PC's operating system, Android) shuts down.

A close hook is a simple initialization thread that has not yet started. When the virtual machine begins to enter the shutdown phase, the virtual machine will start all registered close hooks in an indeterminate order, and when all the hook threads end, if Finalization-on-exit is enabled, the JVM will then run all the finalizer that have not been invoked. Finally, the virtual machine stops. Note that during the shutdown phase of the JVM, the daemon will continue to run, and if the JVM's shutdown phase is entered by invoking the Exit method, the non-guarded thread will continue to run during the shutdown phase of the JVM.

Once you enter the shutdown operation, the JVM will only stop by invoking the halt method, which forces the end of the virtual machine.

Once the operation is closed, the virtual machine can no longer be registered as a new shutdown hook, nor can it undo the previously registered hooks. Both operations cause a illegalstateexception error to be thrown.

The shutdown hook runs at a very subtle moment in the entire lifecycle of the Java Virtual Machine, the final phase of the virtual machine lifecycle, so be careful when writing programs. These hook threads should all be thread-safe and avoid any possible deadlock occurrences. The hook thread should not depend on the bound service, which includes the other hook lines registered to the virtual machine threads the hook thread itself when the JVM has opened the shutdown operation. Using other thread based services, such as the AWT event distribution thread, can cause deadlocks.

To turn off hooks that are not caught in a thread like other threads, by invoking the Threadgroup#uncaughtexception method, the default implementation of this method is to print the error stack information (system#err) and then end the thread ; This method does not cause the virtual machine to end or terminate.

In rare cases, a virtual machine may be abort, that is, without a clean shutdown and simply stop running. This happens when the virtual machine is terminated by external forces. For example, a sigkill signal in UNIX or a terminateprocess in the window platform is invoked. Virtual machines may also abort when a native method fails, such as destroying internal data structures or attempting to access non-existent memory. If the virtual machine abort, it will not be guaranteed to close the hook thread is fully operational.


This section above is the annotation of the Runtime#addshutdownhook method. To sum up, the hook thread's start time:

1. The virtual machine at the end of its own call, such as the completion of the program, or the user to interact with the virtual machine, the virtual machine received the exit signal, the end of their own

2. External forces to end the virtual machine, can not guarantee the hook thread to start, such as in the Windows platform, start Task Manager, directly to the Java virtual body shut down the process, this situation can not guarantee that the hook thread must be called
The top 1 and 2 can be validated by slightly modifying the topmost program.

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.