12

I am using an ExecutorService to implement a 3-thread pool, and CountDownLatch to monitor the completion of all threads, for further processing.

ExecutorService threadExecutor = Executors.newFixedThreadPool(3);
CountDownLatch countDownLatch = new CountDownLatch(3);

AuthorisationHistoryTask task1 =
    new AuthorisationHistoryTask(commonDataThread, countDownLatch );
PreAuthHistoryTask task2 = 
    new PreAuthHistoryTask(userID,sessionID, commonDataThread, countDownLatch );

SettlementHistTask task4 = new SettlementHistTask(commonDataThread,countDownLatch);

Future<Map<String, Object>> futureAuthHistory = threadExecutor.submit (task1);
Future<Map<String, Object>> futurePreAuthHist = threadExecutor.submit (task2);
Future<Map<String, Object>> futureSettleHist = threadExecutor.submit(task4);

threadExecutor.shutdown();

try {
     countDownLatch.await();
}catch (InterruptedException e) { 
     logger.logCommon("InterruptedException",CLASS_NAME);                     
}catch (ExecutionException ex) { 
     logger.logCommon("InterruptedException",CLASS_NAME); 
}

I have used countDownLatch.await() to wait till all the threads are completed. I want this process countDownLatch.await() to abort in case of TIME OUT say 45 secs. How can I implement this?

Perception
  • 79,279
  • 19
  • 185
  • 195
user2122524
  • 516
  • 1
  • 7
  • 9

1 Answers1

31

Use the overloaded variant of await that accepts a timeout.

countDownLatch.await(45, TimeUnit.SECONDS);
Perception
  • 79,279
  • 19
  • 185
  • 195
  • This does not work. This holds the threads for 45 secs even if process has been completed in 2-3 secs. – user2122524 Mar 06 '13 at 11:23
  • 12
    No it doesn't, it waits ***up to** the specified time. As long as the latch is being counted down to zero in your tasks, it is guaranteed to wait the *lesser* of the completion time, or the timeout. – Perception Mar 06 '13 at 11:26
  • @DavidDoria - indeed it should. Thanks for spotting that, and ... fixed. – Perception Oct 23 '13 at 20:37
  • @Perception: Do you know if the latch is still functional if the count has not been met but the await() function times out? In other words, can I timeout, check something, and call the await() method again and still have it signaled by a 'count()' in another thread? – Brian Reinhold Oct 23 '16 at 11:26
  • This code helps only if code before countDownLatch is asynchronous. If you put synchronous code - it will not help you. – Kostadin May 23 '18 at 07:06