Alexandru Nedelcu
Alexandru Nedelcu

Reputation: 267

wait for child threads to finish, without having a reference to the thread

I am working on building an API for an application that already exists, which sometimes uses threads. So one on my methods is like this

private SSG theSSG;
...
private void doSomething(){
  theSSG.loadMenu();

//my code
}

Now, the loadMenu method could give birth to a thread, but not necessarily. If it does, doSomething will execute the rest of the code, while the new thread is executing other code. What I need is a way to wait for the loadMenu() to finish executing all of its children threads before perceeding to the next line of code. I do not have a reference of the thread that could possibly run, since that is based on the user's choice, so I can't use join(). I also can't edit the application (or what happens in loadMenu).

Upvotes: 1

Views: 162

Answers (1)

Stephen C
Stephen C

Reputation: 719416

It is not possible to tell if a thread has finished unless you have a reference to the Thread object1.

It is possible (in theory) to trawl through all of the existing Thread objects in the JVM and try to identify the thread(s) (by name) that might be associated with a task. But I don't know how you would reliably distinguish the threads without help from something that understands what they are. And if you can get that kind of help, it is a small step to asking for the child references instead.

Your best bet would be to redesign this part of your application. Either change things so that the framework knows (or can find out) what the child threads are, or so that it can delegate the "wait for threads to finish" functionality to something that can implement it.


1 - There is a (useless) exception to this. You can always find "this thread" by calling Thread.currentThread(). However, the current thread is guaranteed to be still alive. If you (mistakenly) try to get a Thread to join() itself, bad things happen; e.g. the thread will deadlock.

Upvotes: 2

Related Questions