6956385: URLConnection.getLastModified() leaks file handles for jar:file and file: URLs

Define FileURLConnection.closeInputStream for use by JarURLInputStream.close.
JarURLConnection properly tracks any InputStream it itself opened,
and correspondingly closes the JarFile if necessary (when caches are disabled).
But if its underlying FileURLConnection was used to retrieve a header field,
that would have caused a FileInputStream to be opened
which never gets closed until it is garbage collected.
This means that an application which calls certain methods
on jar:file:/…something.jar!/… URLs will leak file handles,
even if URLConnection caches are supposed to be turned off.
This can delay release of system resources,
and on Windows can prevent the JAR file from being deleted
even after it is no longer in use (for example after URLClassLoader.close).

Reviewed-by: dfuchs, michaelm
This commit is contained in:
Jesse Glick 2023-06-28 15:33:37 +00:00 committed by Michael McMahon
parent 46e4ee1e80
commit 9f98136c3a
3 changed files with 86 additions and 2 deletions

View file

@ -90,6 +90,12 @@ public class FileURLConnection extends URLConnection {
}
}
public synchronized void closeInputStream() throws IOException {
if (is != null) {
is.close();
}
}
private boolean initializedHeaders = false;
private void initializeHeaders() {

View file

@ -25,6 +25,7 @@
package sun.net.www.protocol.jar;
import sun.net.www.protocol.file.FileURLConnection;
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -88,8 +89,14 @@ public class JarURLConnection extends java.net.JarURLConnection {
try {
super.close();
} finally {
if (!getUseCaches()) {
jarFile.close();
try {
if (!getUseCaches()) {
jarFile.close();
}
} finally {
if (jarFileURLConnection instanceof FileURLConnection fileURLConnection) {
fileURLConnection.closeInputStream();
}
}
}
}