gpt4 book ai didi

java - 如果不关闭 URL 连接会发生什么?

转载 作者:行者123 更新时间:2023-11-30 03:47:32 27 4
gpt4 key购买 nike

如果不关闭下面的输入流,到底会发生什么?

InputStream is = new URL(queryUrl).openStream();

既然是 URL 连接,它是否足够智能,可以在请求后自动关闭?

我尝试查看文档,但内容相当模糊。根据我们收集的信息,这与执行 HTTPUrlConnection.getInputStream() 相同。

我只是想弄清楚不执行 is.close() 的影响。这肯定会导致资源泄漏吗?

最佳答案

当您调用close时,关联的系统资源将被释放。如果您查看方法 URL.openStream()

的实现
public final InputStream openStream() throws java.io.IOException {
return openConnection().getInputStream();
}
public URLConnection openConnection() throws java.io.IOException {
return handler.openConnection(this);
}

根据 javadoc,它返回一个 URLConnection

Invoking the close() methods on the InputStream or OutputStream of an URLConnection after a request may free network resources associated with this instance, unless particular protocol specifications specify different behaviours for it.

例如,如果您看到 HttpURLConnection ,他们的文档说:

Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.

干杯!!

关于java - 如果不关闭 URL 连接会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25251539/

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