gpt4 book ai didi

java - 资源关闭的差异

转载 作者:行者123 更新时间:2023-12-01 09:38:56 26 4
gpt4 key购买 nike

当我在主方法中打开资源时

WebClient webClient = new WebClient();

Eclipse 向我显示警告资源泄漏:“webClient”从未关闭。所以我需要关闭资源

webClient.close().

但是当我从方法中获取 WebClient

WebClient webClient = getWebCLient()

public static WebClient getWebClient() {
WebClient webClient = new WebClient();
...
return webClient;
}

我没有收到这样的警告。为什么?

最佳答案

在这种情况下,IDE 不够智能,无法向您发出警告。这绝不意味着 WebClient 不必再关闭。

如果WebClient实现AutoCloseable作为一个好的实践,考虑将对 getWebClient() 的调用包装到 try-with-resource 中以自动关闭

try (WebClient wc = getWebClient()) {
...
}

关于java - 资源关闭的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38604206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com