Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Making main program exit on its own

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not sure how to make my program exit after all the threads have been completed.

I have a way of know when they are all complete.

ThreadPool threadPool = new DefaultThreadPool(25);
//There is a static variable called size size = myObjects.size()
for (a = 0; a!= myObjects.size(); a++)
{
threadPool.invokeLater(new FancyObject(a));
//a just tells which obj from the array
}

in my run method (My class extends Runnable)

public void run()
{
//Do your job

//Now check to see if you are the last thread... if so... terminate
if (i = (size - 1)
{
//quit
}

}


//Now if 5 finishes before 4 and 5 is the last object, the program will terminate before 4 finsihes. I just want the program to shutdown when all threads are finished.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where did you get your ThreadPool & DefaultThreadPool classes? I googled and found several.

The Java5 ThreadPoolExecutor has methods to shutdown() and isTerminated() to know when shutdown is done. Do you have such things?

Failing that, the only thing that comes to mind is a counter. Each FancyObject would record when it has completed and when the count equals the number you started you know they are all done. This feels really ugly.

Maybe locks? FancyObject could lock a lock in its constructor and unlock it when run is done. I haven't used them enough to know if this would work. Locks are a cleaner alternative to wait / notify.
 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the Jakarta Commons Threadpool
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow, I recommended this to people because it was so easy to understand, but now it seems to be in "dormant" status. The JavaDoc link is broken. If you have the doc, see if it has anything about shutting down or querying queue length.

Any chance you can move up to the Java5 concurrent package?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic