如何关闭HttpClient?为什么API中没有.close()方法?

huangapple go评论65阅读模式
英文:

How to close HttpClient? Why there is no .close() method in the API?

问题

我想使用所谓的“自Java 11以来的新 HttpClient” java.net.http.HttpClient

对我来说,确保在HTTP往返完成后关闭TCP连接非常重要,以便释放相应的端口和资源。

API上没有.close().disconnect()或类似的东西可用。

没有关闭连接的可能性真的很奇怪,也奇怪的是为什么期望的行为(发生了什么?连接会自动关闭吗?何时关闭?如何关闭?)从未在任何地方记录,包括Java HTTP Client简介示例和食谱

有什么建议吗?

英文:

I want to use so called "new HttpClient since Java 11" java.net.http.HttpClient.

To me, it is very important to make sure that the TCP connection gets closed after an HTTP roundtrip completes, so that corresponding port gets released and resources - deallocated.

There is no .close() or .disconnect() or something like that available on the API.

It is very weird not to have a possibility to close the connection, and it is also weird why the expected behaviour (what is happening? is the connection getting closed automatically? when? how?) is never documented anywhere, including Introduction to the Java HTTP Client
and Examples and Recipes
.

Any tips?

答案1

得分: 6

这确实是一个缺失的功能,您将需要等待Java 21以便能够显式关闭HttpClient

请参阅bug报告JDK-8304165,“通过使java.net.http.HttpClient实现AutoCloseable来支持关闭HttpClient”:

使java.net.http.HttpClient实现AutoCloseable,以便能够提前回收其资源(选择器、空闲连接位于池中等),而不必等待GC进行垃圾回收。

它的状态是“Approved”并且Fix Version是21。您还可以在HttpClient的早期访问文档中验证,该文档显示它现在实现了AutoCloseable,因此具有close方法,并且还注明“Since: 21”。

英文:

This is indeed a missing feature and you’ll have to wait for Java 21 to be able to close HttpClient explicitly.

See bug report JDK-8304165, “Support closing the HttpClient by making it auto-closable”:

> Make the java.net.http.HttpClient implement AutoCloseable in order to make it possible to reclaim its resources early (selector, idle connections sitting in pools, etc...) rather than having to wait for GC to garbage collect it.

It has the status “Approved” and Fix Version 21. You can also verify with the early access documentation of HttpClient which shows that it now implements AutoCloseable and therefore has a close method which also says “Since: 21”.

huangapple
  • 本文由 发表于 2023年6月13日 18:59:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76464211.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定