Sync version of async method

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();
}

Leave a Comment