我正在尝试来自 JDK 11 的新 HTTP 客户端 API,特别是它执行请求的异步方式。但是有些东西我不确定我是否理解(某种实现方面)。在文档中,它说:
在可行的情况下,异步任务和返回
CompletableFuture
实例的相关操作在客户端提供的线程上执行。Executor
据我了解,这意味着如果我在创建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
)中,我看到执行它的线程来自公共池而不是自定义执行程序,因为它打印Thread is: ForkJoinPool.commonPool-worker-5
.
这是实现中的错误吗?或者我错过了什么?我注意到它说“实例在客户端执行器提供的线程上执行,如果可行”,那么这是不适用的情况吗?
请注意,我也尝试过thenAcceptAsync
,结果相同。