Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abort countDownLatch.await() after time out

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?

like image 860
user2122524 Avatar asked Mar 06 '13 11:03

user2122524


People also ask

What is CountDownLatch await?

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.

Can we reuse CountDownLatch in Java?

CountDownLatch cannot be reused, when count arrives at zero it can't be reset. CyclicBarrier can be reused after holding threads are released.

What is CountDownLatch in Java?

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.


1 Answers

Use the overloaded variant of await that accepts a timeout.

countDownLatch.await(45, TimeUnit.SECONDS);
like image 97
Perception Avatar answered Sep 29 '22 13:09

Perception