Flo*_*own 7

您的应用程序由容器管理.由于不鼓励Thread你自己产生s,你可以让容器注入一个托管Executor.

@Service
class MyService {
  @Autowired
  private Executor executor;

  public CompletableFuture<?> compute() {
    return CompletableFuture.supplyAsync(() -> /* compute value */, executor);
  }
}
Run Code Online (Sandbox Code Playgroud)


Did*_*r L 7

两者之间没有" 对比 ":这些是互补技术:

  • CompletableFuture提供了一种链接异步计算不同阶段的便捷方式 - 比Spring更灵活ListenableFuture;
  • @Async 通过为执行程序提供标准的Spring配置,可以方便地管理后台任务和线程.

但两者都可以合并(从Spring 4.2开始).假设您要将以下方法转换为后台任务,返回CompletableFuture:

public String compute() {
    // do something slow
    return "my result";
}
Run Code Online (Sandbox Code Playgroud)

你要做什么:

  • 如果还没有完成:用bean @EnableAsyncExecutorbean 配置你的应用程序
  • 使用注释方法 @Async
  • 将结果包装成 CompletableFuture.completedFuture()
@Async
public CompletableFuture<String> computeAsync() {
    // do something slow - no change to this part
    // note: no need to wrap your code in a lambda/method reference,
    //       no need to bother about executor handling
    return CompletableFuture.completedFuture("my result");
}
Run Code Online (Sandbox Code Playgroud)

正如您所注意到的,您不必费心将后台任务提交给执行者:Spring会为您处理这些问题.您只需将结果包装成一个已完成的,CompletableFuture以便签名与调用者期望的匹配.