Search code examples
javaconcurrencyjava-8java.util.concurrent

CompletableFuture from Callable?


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

Solution

  • 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.