提问人:blekione 提问时间:7/27/2016 更新时间:7/27/2016 访问量:52
资源关闭的差异
Difference in resource closing
问:
当我在main方法中打开资源时
WebClient webClient = new WebClient();
Eclipse向我显示警告。所以我需要关闭资源Resource leak: 'webClient' is never closed
webClient.close().
但是当我从方法中得到WebClient
WebClient webClient = getWebCLient()
public static WebClient getWebClient() {
WebClient webClient = new WebClient();
...
return webClient;
}
我没有收到这样的警告。为什么?
答:
1赞
Spotted
7/27/2016
#1
在这种情况下,IDE 不够智能,无法向您发出警告。这绝不意味着不必再关闭。WebClient
如果实现 AutoCloseable,请考虑将调用包装到用于自动关闭的 try-with-resource 中WebClient
getWebClient()
try (WebClient wc = getWebClient()) {
...
}
评论
try(WebClient webClient = getWebClient()){...