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?
Class declaration CountDownLatch. await() method block the main thread execution until the current count reaches to zero. the count is decremented using countDown() method by executing threads when their task is completed. Any call to await returns immediately once the count is 0.
CountDownLatch cannot be reused, when count arrives at zero it can't be reset. CyclicBarrier can be reused after holding threads are released.
CountDownLatch in Java is a kind of synchronizer which allows one Thread to wait for one or more Threads before starts processing. This is a very crucial requirement and often needed in server-side core Java applications and having this functionality built-in as CountDownLatch greatly simplifies the development.
Use the overloaded variant of await
that accepts a timeout.
countDownLatch.await(45, TimeUnit.SECONDS);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With