如果没有多线程,使用Future有什么意义呢?

mar*_*31b 5 java multithreading asynchronous future completable-future

我继承了一些代码,原来的开发人员已经没有人留下了。该代码大量使用了CompletableFuture,这是我第一次使用它,所以我仍在尝试理解它。据我了解, a(Completable)Future通常与某种多线程机制一起使用,该机制允许我们在执行耗时的任务时执行其他操作,然后只需通过 Future 获取其结果。正如javadoc中所示:

interface ArchiveSearcher { String search(String target); }
class App {
    ExecutorService executor = ...
    ArchiveSearcher searcher = ...
    void showSearch(final String target) throws InterruptedException {
        Future<String> future = executor.submit(new Callable<String>() {
        public String call() {
            return searcher.search(target);
        }});
        displayOtherThings(); // do other things while searching
        try {
            displayText(future.get()); // use future
        } catch (ExecutionException ex) { cleanup(); return; }
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,在我继承的这个应用程序中,以下不使用任何多线程的模式多次出现:

public Object serve(Object input) throws ExecutionException, InterruptedException {
    CompletableFuture<Object> result = delegate1(input);
    return result.get();
}

private CompletableFuture<Object> delegate1(Object input) {
    // Do things
    return delegate2(input);
}

private CompletableFuture<Object> delegate2(Object input) {
    return CompletableFuture.completedFuture(new Object());
}
Run Code Online (Sandbox Code Playgroud)

对我来说,这相当于:

public Object serve(Object input) {
    Object result = delegate1(input);
    return result;
}

private Object delegate1(Object input) {
    // Do things
    return delegate2(input);
}

private Object delegate2(Object input) {
    return new Object();
}
Run Code Online (Sandbox Code Playgroud)

当然,代码要复杂得多,exceptionallyCompletedFuture出错时会返回,但有 is Callable、 no Runnable、 no Executor、 no supplyAsync()no 多线程的迹象。我缺少什么?Future在单线程上下文中使用 a 有什么意义?

Ste*_*235 0

ExecutorService 实现通常管理线程。我使用了 ThreadPoolExecutor,它正是这样做的。您注释掉了代码使用的 ExecutorService。

  • 使用“ExecutorService”的代码片段是一个反例——它是 OP _确实_理解的示例。实际的问题是关于第二个片段中对“CompletableFuture.completedFuture(...)”的调用。 (3认同)