在 Java 中,URL 连接何时关闭?

什么时候 java 会放弃到 URL 的连接?我没有在 URL 或 URLConnection 上看到 close ()方法,所以请求一完成它就会释放连接吗?我主要是询问是否需要在异常处理程序中执行任何清除操作。

try {
URL url = new URL("http://foo.bar");
URLConnection conn = url.openConnection();
// use the connection
}
catch (Exception e) {
// any clean up here?
}
76177 次浏览

It depends on the specific protocol specified in the protocol. Some maintain persistent connections, other close their connections when your call close in the input or outputstream given by the connection. But other than remembering to closing the streams you opened from the URLConnection, there is nothing else you can do.

From the javadoc for java.net.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.

If you cast to an HttpURLConnection, there is a disconnect() method. If the connection is idle, it will probably disconnect immediately. No guarantees.

I had to download several hunders of files at a time and meet the problem.

You may check your app's open descriptors with the following command:

adb shell ps

Find your application PID in the list and use another command:

adb shell run-as YOUR_PACKAGE_NAME ls -l  /proc/YOUR_PID/fd

I see about 150 open descriptors on a usual launch. And there are 700+ when files are downloading. Their number decreases only after some minutes, looks like Android frees them in the background, not when you can close on a stream.

So we can't be sure when the connection closes actually.