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?
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.
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?
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.