Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 300
diesieben07 Avatar asked May 31 '15 16:05

diesieben07


1 Answers

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

like image 102
ZhongYu Avatar answered Oct 17 '22 09:10

ZhongYu