Callback

I need to be able to enter an exit code for the current current stream. I struggled with this for a while, and I finally came up with a solution, this is 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 be working fine and doing what I want, my only concern is that if this causes any leaks or other unwanted side effects, I cannot see.

or it's great if it's so helpful. I could see a simple library that could dynamically add exit code to existing threads.

+7
source share
3 answers

Better do

 new Thread () { @Override public void run () { try { // Thread logic here } finally { // Thread exit logic here } } }.start (); 
+3
source

You cannot enter code into the current thread if this thread is not actively interacting, such as Thread Dispatch Thread in AWT, which has a loop at the root that takes Runnables out of the queue and executes them.

Your design can inject data into code that was previously single-threaded and therefore had no concurrency problems.

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

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

+2
source

You can move callback.run(); after a catch or into a final block if you want it to be called by anyways

0
source

All Articles