程序的终止是否有效地清理了资源,还是仍然需要显式地执行?如果这个样板没有任何好处,我会把它去掉。
我理解在长生命周期程序的情况下的需求,其中资源使用比程序的生命周期短。但是,当资源(如单例HTTP客户端)使用到最后时会发生什么情况呢?
1.无显式清理
这个版本会在程序退出时进行清理吗?
public static void main(String[] args) {
CloseableHttpClient client = HttpClients.createDefault();
// execute requests
}2.使用try with resources进行清理
这个版本显然做了清理,但需要额外的代码。
public static void main(String[] args) {
try (CloseableHttpClient client = HttpClients.createDefault()) {
// execute requests
} catch (IOException e) {
// exception handling
}
}发布于 2021-04-04 17:25:51
apachec doc的最新更新是创建inside try:
尝试(CloseableHttpClient httpclient = HttpClients.createDefault()) {
A more full answer更详细地解释
的答案是close方法用于关闭内部状态。httpclient的一些实现(在httpclient lib中)可以配置为使用持久资源,比如用于池化连接的PooledHttpClientConnectionManager,如果没有这样的方法,您就不能在需要
时清理这些资源
https://stackoverflow.com/questions/66939676
复制相似问题