aspose file tools*
The moose likes Threads and Synchronization and the fly likes Making main program exit on its own Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Making main program exit on its own" Watch "Making main program exit on its own" New topic
Author

Making main program exit on its own

Anthony Smith
Ranch Hand

Joined: Sep 10, 2001
Posts: 285
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

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Anthony Smith
Ranch Hand

Joined: Sep 10, 2001
Posts: 285
This is the Jakarta Commons Threadpool
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Making main program exit on its own