| Author |
Determining Termination Condition for threads
|
chander shivdasani
Ranch Hand
Joined: Oct 09, 2007
Posts: 206
|
|
have written a multi-threaded Java application which reads a bunch of .jar files from a directory. This application spawns multiple threads and each threads reads bunch of jar files. I'm having trouble identifying the stopping condition for this application. How can i identify that all the files have been read?
The following is my code:
>
|
Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
|
 |
Jon Avadis
Ranch Hand
Joined: Jul 20, 2011
Posts: 49
|
|
Hi
Do you read all jar files of the given directory?
Why do you use multiple threads for this?
|
Knowledge Reigns Supreme
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Don't use Thread and Runnable but an ExecutorService and Callable. You can use Executors.newFixedThreadPool(int) to create an ExecutorService, then submit the Callable objects. This gives you back Future objects that have get methods that a) have a return value, and b) can throw exceptions. The ExecutionException wraps the exception thrown from the Callable's call() method; you can retrieve it with the getClause() method. Instead of joining on the threads you get the Futures.
Also, your loop is written in such a way that you have no concurrency. You create a thread, then join on it within the same loop iteration. You should instead have two loops after each other - one to start the work, one to join / get.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
chander shivdasani
Ranch Hand
Joined: Oct 09, 2007
Posts: 206
|
|
I have simplified my code. In this code, i create multiple threads and each thread will read all the jars in the directory. I created this to stress test an application. I wanted feedback on the following code, if it can be done in a better way.
Also, one question i had was that my main thread exits before other threads have completed. Is there a way i can make my main thread to wait until all the threads have completed?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
chander shivdasani wrote:Also, one question i had was that my main thread exits before other threads have completed. Is there a way i can make my main thread to wait until all the threads have completed?
Join on them. But you don't need to wait - since the threads are not daemon threads the JVM will not exit before all of them have ended.
|
 |
chander shivdasani
Ranch Hand
Joined: Oct 09, 2007
Posts: 206
|
|
So you mean something like this?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
Yes.
|
 |
 |
|
|
subject: Determining Termination Condition for threads
|
|
|