Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to hook up the moment when a Thread has been destroyed

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...)

like image 525
pierrotlefou Avatar asked Dec 02 '22 02:12

pierrotlefou


2 Answers

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();
like image 168
Prince John Wesley Avatar answered Dec 07 '22 22:12

Prince John Wesley


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();
     }

}
like image 31
Jeff Storey Avatar answered Dec 07 '22 23:12

Jeff Storey