When do I need to call this method Runtime.getRuntime().addShutdownHook()

后端 未结 3 1354
梦如初夏
梦如初夏 2020-12-02 13:21

When do I actually need call this method Runtime.getRuntime().addShutdownHook() and when or why I need to shutdown my application. Could anyone please explain me this by giv

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 13:51

    You only worry about shutdown hooks when you want something to happen when a shutdown occurs on the virtual machine.

    From Javadoc:

    The Java virtual machine 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 ^C, or a system-wide event, such as user logoff or system shutdown.

    Thus, a shutdown hook is a initialized and unstarted thread that gets executed when a JVM shutdown occurs.

    Popular examples of shutdown hooks exists in application servers (such as JBoss AS). When you press Ctrl+C, the JVM calls all the Runtime shutdown hooks registered (such as JBoss shutdown hooks) before exiting.

提交回复
热议问题