gpt4 book ai didi

Java 11 HTTP客户端异步执行

转载 作者:搜寻专家 更新时间:2023-10-30 19:56:36 25 4
gpt4 key购买 nike

我正在尝试 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com