Java 11 HTTP客户端异步执行

标签 java http asynchronous completable-future java-11

我正在尝试 JDK 11 中的新 HTTP 客户端 API,特别是它执行请求的异步方式。但是有些事情我不确定我是否理解(某种实现方面)。在documentation ,它说:

Asynchronous tasks and dependent actions of returned CompletableFuture instances are executed on the threads supplied by the client's Executor, where practical.

据我了解,这意味着如果我在创建 HttpClient 对象时设置自定义执行程序:

ExecutorService executor = Executors.newFixedThreadPool(3);

HttpClient httpClient = HttpClient.newBuilder()
                      .executor(executor)  // custom executor
                      .build();

然后,如果我异步发送请求并在返回的 CompletableFuture 上添加依赖操作,则依赖操作应在指定的执行器上执行。

httpClient.sendAsync(request, BodyHandlers.ofString())
          .thenAccept(response -> {
      System.out.println("Thread is: " + Thread.currentThread().getName());
      // do something when the response is received
});

但是,在上面的依赖操作中(thenAccept 中的消费者),我看到执行它的线程来自公共(public)池而不是自定义执行程序,因为它打印 Thread is : ForkJoinPool.commonPool-worker-5.

这是实现中的错误吗?或者我错过了什么?我注意到它说“实例是在客户端执行器提供的线程上执行的,在可行的地方”,那么这是不适用的情况吗?

请注意,我也尝试了 thenAcceptAsync,结果相同。

最佳答案

我刚刚找到更新的 documentation (我最初链接到的那个看起来很旧)它解释了这个实现行为:

In general, asynchronous tasks execute in either the thread invoking the operation, e.g. sending an HTTP request, or by the threads supplied by the client's executor. Dependent tasks, those that are triggered by returned CompletionStages or CompletableFutures, that do not explicitly specify an executor, execute in the same default executor as that of CompletableFuture, or the invoking thread if the operation completes before the dependent task is registered.

CompletableFuture 的默认执行器是公共(public)池。

我还找到了 bug ID介绍了这种行为,API 开发人员在其中对其进行了全面解释:

2) Dependent tasks run in the common pool The default execution of dependent tasks has been updated to run in the same executor as that of CompletableFuture's defaultExecutor. This is more familiar to developers that already use CF, and reduces the likelihood of the HTTP Client being starved of threads to execute its tasks. This is just default behaviour, both the HTTP Client and CompletableFuture allow more fine-grain control, if needed.

关于Java 11 HTTP客户端异步执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51907641/

相关文章:

java 正则表达式 : match input starting with non-number or empty string followed by specific pattern

java - 如何在 Java 中递归地从 N 元素集生成所有 k 元素子集

http - Tomcat、HTTP、选项

php - PHP/MySQL 中的异步消息传递?

swift - PromiseKit 履行和拒绝约定

node.js - 理解和实现 Promise 和异步事物如何与循环一起工作存在问题

java - JDBC 的 rs.getString() 不会返回查询结果的值

java - 如何在 Java 中签署 AWS API 请求(适用于 Android 应用程序)

c# - 使用 httpwebrequest/httpwebresponse 从服务器到客户端的 Docx 文件传输

javascript - 如何使用 Javascript 设置授权 HTTP header