Search code examples
javamultithreadingcountdown

Processing N threads in parallel and main threads exits in the end


For some processing, n threads needs to spawned and runs in parallel. The main thread, which starts the processing should exit, after all the processing is done.

Here is the code snippet:

private void spawnThreads2(int n) throws InterruptedException {
  final CountDownLatch latch = new CountDownLatch(n);
  final Random random = new Random(System.currentTimeMillis());
  for (int i = 1; i <= n; i++) {
    final int id = i;
    new Thread(){
      public void run() {
        try {
          Thread.sleep(random.nextInt(1000)); // represents processing, can throw any Exception
        } catch (Exception e) {} 
        finally {
          latch.countDown();
        }
      }
    }.start();
  }
  latch.await();
  System.out.println("all completed.");
}

The countdown() is done in the finally block, so in case any exception happens application does not hang.

  1. Is this design good for creating threads and waiting for them? Is there possibility application can hang and never come out, because of the await()?
  2. Is there a way we can achieve same functionality using join()? We can store all the instance of the threads and check for status and wait. Is that a good way to do this.

Solution

  • You should use an ExecutorService. You can obtain one using n threads by calling:

    ExecutorService executor = Executors.newFixedThreadPool( n );
    

    Then, you can start a task as follow:

    executor.submit( runnable );
    

    At the end, you can stop executor by calling shutdown() method. Doing that, no task can be added anymore but all submitted tasks will be executed. You can also wait for shutdown:

    executor.shutdown();
    
    while ( !executor.isTerminated() ) {
        try {
            executor.awaitTermination( 5, TimeUnit.SECONDS);
        } catch ( InterruptedException e ) {
        }
    }