dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


advertisement
 

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


advertisement

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

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