Today I experimented with the “new” CompletableFuture
from Java 8 and found myself confused when I didn’t find a runAsync(Callable)
method.
I can do it myself like shown below, but why is this (to me very obvious and useful utility method) missing? Am I missing something?
public static <T> CompletableFuture<T> asFuture(Callable<? extends T> callable, Executor executor) { CompletableFuture<T> future = new CompletableFuture<>(); executor.execute(() -> { try { future.complete(callable.call()); } catch (Throwable t) { future.completeExceptionally(t); } }); return future; }
Advertisement
Answer
You are supposed to use supplyAsync(Supplier<U>)
In general, lambdas and checked exceptions do not work very well together, and CompletableFuture
avoids checked exceptions by design. Though in your case it should be no problem.
related threads:
http://cs.oswego.edu/pipermail/concurrency-interest/2012-December/010486.html
http://cs.oswego.edu/pipermail/concurrency-interest/2014-August/012911.html