0

I scheduled a recurring task. Now I want the main thread to wait for the ScheduledExecutorService to complete its first execution. How can i accomplish this?

public void test1(){
  refreshFunction(); /* This should block until task has executed once. */
  /* Continue with main thread. */
  ... 
}

public void refreshFunction() {
  try {
    scheduledExecutorService = Executors.newScheduledThreadPool(1);
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        loadInfo();
      }
    }, 1, 5, TimeUnit.MINUTES);
    logger.info(" : Completed refreshing information : "
      + new Timestamp(System.currentTimeMillis()));
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}
erickson
  • 265,237
  • 58
  • 395
  • 493
BigDataLearner
  • 1,388
  • 4
  • 19
  • 40
  • Check for my answer in : http://stackoverflow.com/questions/35075886/how-to-wait-for-a-thread-that-spawns-its-own-thread – Ravindra babu Jul 19 '16 at 19:22
  • Have you seen this `scheduledExecutorService.awaitTermination(timeout, unit)`? –  Jul 19 '16 at 19:22

1 Answers1

3

Use a CountDownLatch to coordinate between threads.

final CountDownLatch latch = new CountDownLatch(1);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
  @Override
  public void run() {
    loadInfo();
    latch.countDown();
  }
}, 1, 5, TimeUnit.MINUTES);
latch.await();

A better approach might be for the scheduled task to execute a callback after the information is loaded to update observers that depend on that information.

erickson
  • 265,237
  • 58
  • 395
  • 493