Is there any place to hook up when a Thread has been killed? Something like :
onDestroy{
//do something...
}
EDIT: Sorry. I should have stated it more clearly.
The thread termination is not because all the job has done but because it has been killed by the client code using ThreadGroup.destroy(). As my singleton is being instantiated in the client code, so it will belong to the THreadGroup of the Client code and be killed as a result. (Actually, I am not very sure of the last sentence...)
You can wrap both the action and the hook like this.
public final class HookOnDestroy implements Runnable {
private final Runnable action;
private final Runnable hook;
public HookOnDestroy(Runnable action, Runnable hook) {
this.hook = hook;
this.action = action;
}
@Override
public void run() {
try {
action.run();
} finally {
hook.run();
}
}
}
and
Runnable action = ...
Runnable hook = ...
new Thread( new HookOnDestroy(action,hook)).start();
There's no general way to add an asynchronous listener to a thread that gets notified when the thread dies. You can use the join method to wait for a thread, but that is synchronous. Or you could create an extension of thread class that calls listeners at the end of its run method, something like:
public abstract class NotifyingThread extends Thread {
private final List<ThreadListeners> listeners;
protected abstract void doRun();
public void run() {
doRun();
notifyListeners();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With