我使用 Java 16 通过 HTTP 向 API 发出请求。为了加快整体速度,我已将其加载到自定义ForkJoinPool
. 我在下面编译了一个复制示例。
由于迁移到 Java 17(openjdk build 17.0.1+12-39),这会引发 RejectedExecutionException:
Caused by: java.util.concurrent.RejectedExecutionException: Thread limit exceeded replacing blocked worker
at java.base/java.util.concurrent.ForkJoinPool.tryCompensate(ForkJoinPool.java:1819)
at java.base/java.util.concurrent.ForkJoinPool.compensatedBlock(ForkJoinPool.java:3446)
at java.base/java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3432)
at java.base/java.util.concurrent.CompletableFuture.waitingGet(CompletableFuture.java:1898)
at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:2072)
at java.net.http/jdk.internal.net.http.HttpClientImpl.send(HttpClientImpl.java:553)
at java.net.http/jdk.internal.net.http.HttpClientFacade.send(HttpClientFacade.java:119)
at Test.lambda$retrieveMany$1(Test.java:30)
为什么会这样?我不知道的关于 ForkJoinPool 的一些变化吗?
代码
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.stream.Collectors.toList;
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
final List<String> urls = List.of("https://stackoverflow.com", "https://stackoverflow.com", "https://stackoverflow.com");
// This succeeds on JDK 16, 17
retrieveMany(urls, 4);
// This fails on JDK 17, but succeeds on 16
retrieveMany(urls, 3);
}
private static List<String> retrieveMany(List<String> urls, int threads) throws InterruptedException, ExecutionException {
return new ForkJoinPool(threads, ForkJoinPool.defaultForkJoinWorkerThreadFactory, (t, e) -> {}, true, 0, threads, 1, null, 1, MINUTES)
.submit(() -> urls.parallelStream()
.map(url -> {
try {
return HttpClient.newBuilder().build().send(HttpRequest.newBuilder(URI.create(url)).build(), BodyHandlers.ofString()).body();
} catch (IOException | InterruptedException aE) { }
return null;
})
.collect(toList()))
.get();
}
}