I have a multi-threaded batch processing app that runs anywhere between 5-10 concurrent threads of execution. Their data segments are carefully sliced to be as evenly distributed as possible but, of course, the execution times always vary. What I wanna do is to invoke one last kind of onFinalize method when the last thread finishes, which will do some stat computation.
I was wondering if the best way to know for a thread that it is the last one (rather than querying the DB, which seems kind of pedestrian) is to have a static var which would be incremented in a synchronized block when a new thread is added and decremented when each thread finishes. So when a thread finishes and does its decrementing, I can have an if to see if the outstanding # of threads is 0 and then invoke the final stats.
That is what I was thinking. I was wondering if there is a better, more elegant, or bulletproof way of accomplishing this.
Using Java 7
Thanks
So what else you can do is that you can create a
ThreadManagerclass. This class should have aList<Thread>. Whenever you create a newThreadto execute your task you shouldregisterit inThreadManager. Then create a method inThreadManagerwhich returns the totalnumberoflive Threadsin theList.In this way you can at any point see how many threads are running and also you can perform any other operation on the running threads if you want. Also one more
Threadshould run periodically which should clear all dead Thread references from theList.Sample
ThreadManagercan look like this:Hope this helps. You can perform other functions aswell on the
Thread List.