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 anInterruptedExceptionor 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)