How can I "convert" a blocking method call to a CompletableFuture? Example:
T waitForResult() throws InterruptedException {
obj.await(); // blocking call
// ...
return something;
}
I need to turn that into this:
CompletableFuture.of(this::waitForResult); // .of(Callable<T>) doesn't exist
Some things to consider:
waitForResult()
may throw exceptions. These have to be handled correctly, so thatcompletableFuture.get()
would throw anInterruptedException
or anExecutionException
.- There must not be another thread involved (
supplyAsync()
would do so). - It must be a CompletableFuture (possibly wrapped).
I tried this, but this won't handle exceptions correctly:
CompletableFuture.completedFuture(Void.TYPE).thenApply(v -> {
try {
listener.await();
// ...
return listener.getResult();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (SnmpException e) {
throw new RuntimeException(e);
}
});
I know Create CompletableFuture from a sync method call, but it doesn't help me:
- The original code in the question blocks the main thread
- The code in the answers either incorporates a third thread or doesn't handle exceptions correctly (correct me if I'm wrong)
2.
, "there must be no other thread involved"? Which thread should call (and wait on)obj.await()
? If it is the thread runningmain
; then you block the main thread. Otherwise, you need to involve another thread. And in this case, supplyAsynch will probably be okget()
which in turns runs the callable (resulting inlistener.await()
). A third thread would be started when usingsupplyAsync()
.listener.await()
. Is that right?get()
does not cause the callable to be invoked. Callingget()
only makes the caller waiting for the result, whether there is an attempt to provide it or not. When your main thread is supposed to calllistener.await()
, it must do so; it will not know whether anyone has invokedget()
on the future or not. — Besides that, when the second thread is supposed to callget()
on the future created by the first one, the first thread must somehow hand over the future to the second thread.