31

What's the best way to make a synchronous version of an asynchronous method in Java?

Say you have a class with these two methods:

asyncDoSomething(); // Starts an asynchronous task
onFinishDoSomething(); // Called when the task is finished 

How would you implement a synchronous doSomething() that does not return until the task is finished?

hpique
  • 119,096
  • 131
  • 338
  • 476

1 Answers1

76

Have a look at CountDownLatch. You can emulate the desired synchronous behaviour with something like this:

private CountDownLatch doneSignal = new CountDownLatch(1);

void main() throws InterruptedException{
  asyncDoSomething();
  //wait until doneSignal.countDown() is called
  doneSignal.await();
}

void onFinishDoSomething(){
  //do something ...
  //then signal the end of work
  doneSignal.countDown();
}

You can also achieve the same behaviour using CyclicBarrier with 2 parties like this:

private CyclicBarrier barrier = new CyclicBarrier(2);

void main() throws InterruptedException{
  asyncDoSomething();
  //wait until other party calls barrier.await()
  barrier.await();
}

void onFinishDoSomething() throws InterruptedException{
  //do something ...
  //then signal the end of work
  barrier.await();
}

If you have control over the source-code of asyncDoSomething() I would, however, recommend redesigning it to return a Future<Void> object instead. By doing this you could easily switch between asynchronous/synchronous behaviour when needed like this:

void asynchronousMain(){
  asyncDoSomethig(); //ignore the return result
}

void synchronousMain() throws Exception{
  Future<Void> f = asyncDoSomething();
  //wait synchronously for result
  f.get();
}
rodion
  • 14,729
  • 3
  • 53
  • 55
  • 1
    I wish I could give you more than 1 vote. Excellent recommendation of Future – AZ_ Jan 22 '14 at 07:48
  • @rodion if I use CountDownLatch inside a loop, and instantiated it within the loop, will it stop the loop from executing the next iteration until the iteration's task is done or it will just continue to iterate? Please let me know if my question is not clear. – Aaron Oct 03 '16 at 13:56
  • a Semaphore would work as well – Zixradoom Sep 20 '22 at 17:12