Using Shutdown Hook

R

rossum

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 ---
 
M

Mark Thornton

rossum said:
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

Warning: shutdown hook doesn't work reliably in Windows applications
that have a GUI. The process can (and often does) terminate before
shutdown hooks have completed.

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4486580

The shutdown hooks work if the application is closed normally or doesn't
have a GUI, but not if the close is the result of the user logging off
or shutting down the system.

Mark Thornton
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top