Abort countDownLatch.await() after time out

江枫思渺然 提交于 2019-12-09 03:09: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?


回答1:


Use the overloaded variant of await that accepts a timeout.

countDownLatch.await(45, TimeUnit.SECONDS);


来源:https://stackoverflow.com/questions/15245629/abort-countdownlatch-await-after-time-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!