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?
Have a look at CountDownLatch. You can emulate the desired synchronous behaviour with something like this:
You can also achieve the same behaviour using
CyclicBarrierwith 2 parties like this:If you have control over the source-code of
asyncDoSomething()I would, however, recommend redesigning it to return aFuture<Void>object instead. By doing this you could easily switch between asynchronous/synchronous behaviour when needed like this: