Abort countDownLatch.await() after time out

13,623

Use the overloaded variant of await that accepts a timeout.

countDownLatch.await(45, TimeUnit.SECONDS);
Share:
13,623
user2122524
Author by

user2122524

Updated on June 04, 2022

Comments

  • user2122524
    user2122524 almost 2 years

    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?

  • user2122524
    user2122524 about 11 years
    This does not work. This holds the threads for 45 secs even if process has been completed in 2-3 secs.
  • Perception
    Perception about 11 years
    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
    Perception over 10 years
    @DavidDoria - indeed it should. Thanks for spotting that, and ... fixed.
  • Brian Reinhold
    Brian Reinhold over 7 years
    @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?
  • Kostadin
    Kostadin almost 6 years
    This code helps only if code before countDownLatch is asynchronous. If you put synchronous code - it will not help you.