Browse DevX
Sign up for e-mail newsletters from DevX


Use JVM Shutdown Hooks to Optimize Resources-2 : Page 2




Building the Right Environment to Support AI, Machine Learning and Deep Learning

A Simple Example: the SimpleHook Class
You implement JVM shutdown hooks using a separate class that extends the Thread class (click here to download the accompanying source code for this Solution). When you register an instance of this separate class with a JVM (you will learn how to do this later), the shutdown thread class starts when the JVM terminates.

The non-public class MyShutdown is defined at the bottom of the file SimpleHook.java (included in the source code download):

class MyShutdown extends Thread { public MyShutdown(SimpleHook managedClass) { super(); this.managedClass = managedClass; } private SimpleHook managedClass; public void run() { System.out.println("MyShutDown thread started"); try { managedClass.freeResources(); } catch (Exception ee) { ee.printStackTrace(); } } }

Notice that the constructor requires a reference to the managed application class. In the design pattern this Solution (and I) use, the managed parent class is expected to define a method freeResources(). To be tidy, you could define a separate interface that defines the freeResources() method signature and have managed classes implement this interface. However, to keep this example simple, I just concentrate on using JVM shutdown hooks.

The constructor for the managed class SimpleHook creates an instance of the MyShutdown class and registers this instance with the JVM:

public SimpleHook() { // set up service termination hook (gets called // when the JVM terminates from a signal): MyShutdown sh = new MyShutdown(this); Runtime.getRuntime().addShutdownHook(sh); }

See the SimpleHook.java source file for the complete code.

Thanks for your registration, follow us on our social networks to keep up-to-date