Using Shutdown Hook
Thanks to all of you who responded to my thread on replacing
runFinalizersOnExit.
David Roden suggested using a Shutdown Hook. Never having used one
before I put together a simple test program, (below), which seems to
work. Have I made any mistakes in this? Any pointers to improvements
would be helpful.
Thanks in advance,
rossum
// --- Begin Code ---
import java.lang.ref.WeakReference;
/**
* Testing Shutdown Hook
*/
public class HookTester {
private double mSecret;
public HookTester() {
mSecret = Math.random();
// Set up ShutdownHook in constructor
ShutdownHook sdh = new ShutdownHook(
new WeakReference<HookTester>(this));
Runtime.getRuntime().addShutdownHook(new Thread(sdh));
}
public void dispose() {
System.out.println("Running dispose()");
mSecret = 0.0;
System.out.println("Secret deleted.");
}
@Override
protected void finalize() {
System.out.println("Running finalize()");
dispose();
}
class ShutdownHook implements Runnable {
// Use a weak reference so as not to delay garbage collection.
private WeakReference<HookTester> mWeakRef;
public ShutdownHook(WeakReference<HookTester> wRef) {
mWeakRef = wRef;
}
public void run() {
if (mWeakRef.get() != null) {
mWeakRef.get().dispose();
}
}
}
public static void main(String[] args) {
HookTester ht = new HookTester();
// ht.dispose() not explicitly called.
}
}
// --- End Code ---