ave you ever found yourself in the following scenario:
- You've created server-side Java applications for a production environment.
- You write a program that allocates external resources: connections to a database using JDBC.
- A user prematurely terminates the program (by typing control-C, for example).
- The external database server eventually needs to be restarted because all client connections are allocated but not freed.
If this sounds familiar, it's time to explore a seldom-used feature of the Java Virtual Machine (JVM): the ability to register JVM shutdown hooks that execute before a JVM shuts down. In the above scenario, JVM shutdown hooks could perform cleanup processing to free the external resources. This 10-Minute Solution offers two quick demonstrations (one simple, one more complex) of how to use these hooks in your own Java programs.
In production environments, JVMs are killed and restarted either automatically by network management systems or manually by a network administrator. When a JVM is killed, it is often necessary to perform some cleanup work before the JVM finishes shutting down.
JVM shutdown hooks provide a clean and simple mechanism for registering application-specific behavior that performs cleanup work when a JVM terminates.