Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

using Thread.activeCount to monitor the end of work by the threads

 
Saravanan Venkat
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a calculation which is to be performed multiple times ( I will not know in advance on how many times to be performed, as the current flow is such that it checks for the details and starts a thread to do the calculation whenever required ). But, I do want to advance to the next step after 'calculation', only when all the calculations are done. Currently, when the total number of threads active (based on active count) is less than number allowed (I dont want to start alot of threads, so limited to core processors available in the m\c), a new thread is started. And the whole process waits for the threads to complete (again based on ThreadCount). So for, it works. but is there a better elegant way to do this ?.

pseudo code

for-loop-
{
evaluate a collection
if calculation required
{
while(Thread.activeCount() <= numThrdsAllowed(input parameter) )
assign the job to new thread
}
}

//now I want all the thread to get completed, so
public void threadWait()
{
boolean done = false;
while(!done)
{
if(Thread.activeCount() <= 1)
done = true;
}
}



Thanks in advance,

Rgds,
bengu
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Saravanan Venkat wrote:Hi All,
So for, it works. but is there a better elegant way to do this ?.

Hi,

you could use a thread pool:
For example in fixedThreadPool you declare how many threads it should use (maximum),
then submit tasks to execute - how many tasks you only want, could be hundreds or thousands
The pool creates threads and maintains tasks to be executed itself, you don't have to bother with it,
and it uses only up to declared number of threads to run all submitted tasks.

The pseudo code could look like this:




If there are only 5 tasks to run - it creates 5 threads, if there are 100 tasks - it creates 10 threads
and run sequentially all tasks (but only 10 at the same time).
 
Saravanan Venkat
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent. This is exactly I was looking for. Thanks for the reply.

Rgds,
Saravanan.V
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic