我在HttpClient
基于 Servlet 的 Web 应用程序中使用 Java 的新版本(自版本 11 起):
private static final HttpClient HTTP_CLIENT =
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
...
public void httpPostAsyncToEndpoint(WebEndpoint endpoint, Map<String,String> params) {
HttpRequest req = buildRequest(endpoint, params);
CompletableFuture<HttpResponse<String>> future = HTTP_CLIENT.sendAsync(req, HttpResponse.BodyHandlers.ofString());
future.thenAccept((HttpResponse<String> res) -> {
if (res.statusCode() >= 400) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("{} HTTP response returned from endpoint {}", endpoint, res.statusCode());
}
}
}).exceptionally(ex -> {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Could not audit event using endpoint {}", endpoint, ex);
}
return null;
});
}
一切都很好,除了在 Tomcat 上重新启动 Web 应用程序时会产生以下警告:
14-Aug-2020 09:21:16.996 WARNING [http-nio-8080-exec-18] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [MyApp] appears to have started a thread named [HttpClient-3-SelectorManager] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
java.base/sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(Native Method)
java.base/sun.nio.ch.WindowsSelectorImpl$SubSelector.poll(WindowsSelectorImpl.java:357)
java.base/sun.nio.ch.WindowsSelectorImpl.doSelect(WindowsSelectorImpl.java:182)
java.base/sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:124)
java.base/sun.nio.ch.SelectorImpl.select(SelectorImpl.java:136)
java.net.http/jdk.internal.net.http.HttpClientImpl$SelectorManager.run(HttpClientImpl.java:867)
我怎样才能防止这种情况?我尝试使用ThreadFactory
只返回守护线程的自定义:
HttpClient.newBuilder()
.executor(Executors.newSingleThreadExecutor((Runnable r) -> {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}))
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL).build();
但警告仍然存在。
我在 Tomcat 9 上使用 OpenJDK 11.0.7。