Forums Register Login

Why no join() method in ThreadGroup?

+Pie Number of slices to send: Send
Hi all,
I'm probably missing something here, as I haven't worked much with Threads & ThreadGroups, but it seems to me that a join() method would be useful in ThreadGroup, & here's why:
I want to spawn a thread for each entry in a queue, and I need my calling thread not to die until each of the spawned threads has finished. The only way I can come up with to do this is to add each Thread to a Vector (Java 1.1.8 - no ArrayList ), and then loop through the elements of the Vector and call join() on each in turn.
Why can't I add my created Threads to a ThreadGroup, and then call a join() on the ThreadGroup as a whole? I'm hoping that the answers will give me more insight into what the ThreadGroup class is really for.
Thanks
Dave
+Pie Number of slices to send: Send
Well the truth is, ThreadGroup isn't really all that useful a class to begin with. The API for accessing all the Threads in a ThreadGroup is extraordinarily crappy, since activeCount() is just an approximation for some reason - there's no guarantee you've got all the active groups. Here's sample code that loops through all Threads in a ThreadGroup:

Frankly I find the need for that "safety factor" rather appalling. One reason that it's never been fixed though is that people have generally found that if they want to manage groups of threads, it's easier to just group the threads into Collections and iterate through the collections to do whatever you want. That's what you're doing with a Vector, and it's really pretty easy.

Of course we'd prefer to use more modern Collections classes here, but if you're stuck with 1.1.8...
I suppose they could have added convenience methods to ThreadGroup to do this sort of thing, but it never seemed that important. People rarely use ThreadGroup, and doing it this way requires only a little more code. Plus you get added control in that you can do any other things you want inside the loop.
[ March 14, 2003: Message edited by: Jim Yingst ]
+Pie Number of slices to send: Send
As of JDK 1.5, you can now use the goodies in java.util.concurrent.

I use the following code to check that an Executor fails as expected when its queue is full. I do this by giving it too many requests, but I need to wait until all threads have completed before I check that an error occurred at some point. To do that I needed somthing like a ThreadGroup.join(). A CountDownLatch does the business.

I love a good mentalist. And so does this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 8274 times.
Similar Threads
Thread Null pointer problem
Connection is failing at ObjectInputStream for Server
Keep-Alive-Timer Thread
Demon ThreadGroup/ThreadGroup
Thread Question: Are they all "under" creator?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 01:59:13.