Abort countDownLatch.await() after time out
Asked Answered
T

1

13

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?

Twila answered 6/3, 2013 at 11:4 Comment(0)
N
34

Use the overloaded variant of await that accepts a timeout.

countDownLatch.await(45, TimeUnit.SECONDS);
Naquin answered 6/3, 2013 at 11:13 Comment(5)
This does not work. This holds the threads for 45 secs even if process has been completed in 2-3 secs.Twila
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.Naquin
@DavidDoria - indeed it should. Thanks for spotting that, and ... fixed.Naquin
@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?Veiled
This code helps only if code before countDownLatch is asynchronous. If you put synchronous code - it will not help you.Stafford

© 2022 - 2024 — McMap. All rights reserved.