public class XXX {
.........................................................
.........................................................
static {
// Add a shutdown hook to the VM if we're running JDK 1.3. When the
// thread is executed, it will call the destroy() method of the
// current connection provider. This is necessary for some connection
// providers -- especially those for in-VM Java databases.
Runtime runtime = Runtime.getRuntime();
Class c = runtime.getClass();
try {
Method m = c.getMethod("addShutdownHook", new Class[] { Thread.class } );
m.invoke(runtime, new Object[] { new ShutdownThread() });
}
catch (NoSuchMethodException nsme) {
// Ignore -- the user might not be running JDK 1.3.
}
catch (Exception e) {
e.printStackTrace();
}
}
..................................................
...................................................
/**
* Shuts down the current connection provider. It should be called when
* the VM is exiting so that any necessary cleanup can be done.
*/
private static class ShutdownThread extends Thread {
public void run() {
ConnectionProvider provider = ConnectionManager.getConnectionProvider();
if (provider != null) {
provider.destroy();
}
}
}
}
我觉得 static 块内没必要用反射来注册一个钩子,直接用
Runtime.getRuntime().addShutdownHook(new ShutdownThread()); 这不就可以了么 ?