Monday 30 March 2020

Java Thread CountDownLatch

In case when we want to do some logic until a thread finish (either success or fail), we can use countDownLatch, for instance if we have one thread,
CountDownLatch countDownLatch = new CountDownLatch(1);
jobExecutor = new Thread() {
   @Override public void run() {
      try {
         // core logic
      } catch (Throwable e) {
         //Logger.error
      } finally {
         // count down either success or fail         countDownLatch.countDown();
      }

   } };

// run the thread
jobExecutor.start();
// wait until batch job finishif(countDownLatch != null){
   countDownLatch.await();
}

// other logic when the thread finish running
....