Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread exit callback

I need to be able to inject some exit code for the current running thread. I have struggled with this one for a while, and i finally came up with a solution here is some code similar to what I am doing:

public static void injectThreadExitCallback(final Runnable callback) {
    final curr = Thread.currentThread();
    new Thread() {
        @Override
        public void run() {
            try {
                curr.join();
                callback.run();
            } catch (InterruptedException ex) {
                ... logging ...
            }
        }
    }.start();
}

It seems to work fine and does exactly what I'm wanting, my only concern is, if this causes any leaking or other undesired side effects, that i may not bee seeing.

or is this perfectly fine, if so this is pretty useful. I could see a simple library that can dynamically add exit code to existing threads.

like image 778
Nick Hecht Avatar asked Feb 08 '13 20:02

Nick Hecht


People also ask

What happens when a thread calls exit?

A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.

What is a thread callback?

One pattern for performing long-running tasks without blocking the main thread is callbacks. By using callbacks, you can start long-running tasks on a background thread. When the task completes, the callback, supplied as an argument, is called to inform your code of the result on the main thread.

Can main thread exit before child?

Yes. "this gets printed before the system. out. println() in the child threads.


2 Answers

You better do

new Thread () {
    @Override
    public void run () {
        try
        {
            // Thread logic here
        }
        finally
        {
            // Thread exit logic here
        }
    }
}.start ();
like image 154
Mikhail Vladimirov Avatar answered Oct 11 '22 06:10

Mikhail Vladimirov


You can't possibly inject code into a running thread unless that thread is actively cooperating, like for example the Event Dispatch Thread in AWT, which at its root has a loop that takes Runnables off of a queue and executes them.

Your design may introduce data races into code that was previously single-threaded and thus had no concurrency issues.

Finally, the design wastes a precious system resource (a thread) to do nothing but wait for another thread to finish.

If you need this to patch up some existing code from the outside, then it may be the only option; if not, it would be better to provide an explicit mechanism for it that was more efficient.

like image 29
Marko Topolnik Avatar answered Oct 11 '22 05:10

Marko Topolnik