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.
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.
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.
Yes. "this gets printed before the system. out. println() in the child threads.
You better do
new Thread () {
@Override
public void run () {
try
{
// Thread logic here
}
finally
{
// Thread exit logic here
}
}
}.start ();
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.
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