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
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 ]
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.