我将尝试证明ClassLoader.getResourceAsStream()
正在打开两个InputStreams
,不关闭任何一个,只向客户端返回一个我的逻辑正确吗?JDK源代码选自jdk1.8.0_25
我已经在间隔中使用Spring ClassPathResource处理了未闭合的资源问题(原始问题),即使用ClassLoader.getResourceAsStream
将InputStream
获取到属性文件。
经过调查,我发现classLoader.getResourceAsStream
通过URL url = getResource(name);
获得了URL
,然后它正在打开该流,但URL url = getResource(name)
已经打开了该流。JDK ClassLoader
来源:
public InputStream getResourceAsStream(String name) {
URL url = getResource(name); /* SILENTLY OPENS AND DON'T CLOSES STREAM */
try {
return url != null ? url.openStream() : null; /* SECOND OPEN !!! */
} catch (IOException e) {
return null;
}
}
如果我们将以这种方式提供的close()
InputStream
,我们将仅关闭由url.openStream()
打开的流。JDK来源:
public final InputStream openStream() throws java.io.IOException {
return openConnection().getInputStream();
}
我假设,问题是JDK在URL url = getResource(name)
中静默地打开一个流,只得到URL对象,该对象用于进一步创建**秒(返回到客户端)流**。看看这个方法来源:
public URL getResource(String name) {
URL url;
if (parent != null) {
url = parent.getResource(name);
} else {
url = getBootstrapResource(name); <---- we end up calling that method
}
if (url == null) {
url = findResource(name);
}
return url;
}
现在,在getBootstrapResource(name)
中,当我们将Resource
转换为URL
时,忘记了Resource
中打开的流:
private static URL getBootstrapResource(String name) {
URLClassPath ucp = getBootstrapClassPath();
Resource res = ucp.getResource(name); <---- OPENING STREAM [see further]
return res != null ? res.getURL() : null; <--- LOSING close() CAPABILITY
}
ucp.getResource(name);
为什么开放资源?让我们研究一下方法:this.getResource(var1, true);
,它委托给:
public Resource getResource(String var1, boolean var2) {
if(DEBUG) {
System.err.println("URLClassPath.getResource("" + var1 + "")");
}
URLClassPath.Loader var3;
for(int var4 = 0; (var3 = this.getLoader(var4)) != null; ++var4) {
Resource var5 = var3.getResource(var1, var2); <-------- OPENING STREAM
if(var5 != null) {
return var5;
}
}
return null;
}
为什么Resource var5 = var3.getResource(var1, var2);
正在打开流?进一步看:
Resource getResource(final String var1, boolean var2) {
final URL var3;
try {
var3 = new URL(this.base, ParseUtil.encodePath(var1, false));
} catch (MalformedURLException var7) {
throw new IllegalArgumentException("name");
}
final URLConnection var4;
try {
if(var2) {
URLClassPath.check(var3);
}
var4 = var3.openConnection(); <------------ OPENING STREAM
InputStream var5 = var4.getInputStream();
if(var4 instanceof JarURLConnection) {
JarURLConnection var6 = (JarURLConnection)var4;
this.jarfile = URLClassPath.JarLoader.checkJar(var6.getJarFile());
}
} catch (Exception var8) {
return null;
}
return new Resource() {
public String getName() {
return var1;
}
public URL getURL() {
return var3;
}
public URL getCodeSourceURL() {
return Loader.this.base;
}
public InputStream getInputStream() throws IOException {
return var4.getInputStream();
}
public int getContentLength() throws IOException {
return var4.getContentLength();
}
};
}
我们可以看到未关闭的openConnection()
和getInputStream()
,通过所有返回Resource
的调用,我们最终只使用Resource
中封装的getURL()
方法而不关闭它的InputStream
,只使用该URL
对象打开另一个InputStream
并将其返回给客户端(哪个客户端可以关闭coruse,但我们以第一个未关闭的流结束)。
那么,ClassLaoder.getResourceAsStream是否因资源泄漏而中断
实用方面:我在try-with-resources
块中使用getResourceAsStream
,在生产中仍然存在未关闭的资源问题,每30秒加载一次文件名。此外,所有资源都在垃圾回收上关闭,这与finalize()
方法中的文件流close()
一致。
我制作了一个简单的测试程序来验证实际行为:
System.out.println(System.getProperty("java.version"));
URL testURL = new URL("test", null, 0, "/", new URLStreamHandler() {
protected URLConnection openConnection(URL u) throws IOException {
System.out.println("creating connection to "+u);
return new URLConnection(u) {
InputStream is;
public void connect(){}
@Override
public InputStream getInputStream() throws IOException {
System.out.println("getInputStream() for "+u);
if(is==null) is=new InputStream() {
boolean open=true;
@Override
public void close() throws IOException {
if(!open) return;
System.out.println("One InputStream for "+u+" closed");
open=false;
}
public int read() { return -1; }
};
else System.out.println("COULD be shared");
return is;
}
};
}
});
System.out.println("n trying new ClassLoader");
try(URLClassLoader newlClassLoader=new URLClassLoader(new URL[]{ testURL });
InputStream is=newlClassLoader.getResourceAsStream("foo")) {}
System.out.println("n trying System ClassLoader");
try {
Method m=URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
m.setAccessible(true);
m.invoke(ClassLoader.getSystemClassLoader(), testURL);
} catch(Exception ex) { ex.printStackTrace(); }
try(InputStream is=ClassLoader.getSystemResourceAsStream("foo")) {}
System.out.println("n trying bootstrap ClassLoader");
try {
Method m=ClassLoader.class.getDeclaredMethod("getBootstrapClassPath");
m.setAccessible(true);
Object bootstrap = m.invoke(null);
m=bootstrap.getClass().getDeclaredMethod("addURL", URL.class);
m.setAccessible(true);
m.invoke(bootstrap, testURL);
} catch(Exception ex) { ex.printStackTrace(); }
try(InputStream is=ClassLoader.getSystemClassLoader().getResourceAsStream("foo")) {}
在我的机器上使用(用1.8.0_05
、1.8.0_20
和1.8.0_40
测试)它打印
trying new ClassLoader
creating connection to test:/foo
getInputStream() for test:/foo
One InputStream for test:/foo closed
creating connection to test:/foo
getInputStream() for test:/foo
One InputStream for test:/foo closed
trying System ClassLoader
creating connection to test:/foo
getInputStream() for test:/foo
One InputStream for test:/foo closed
creating connection to test:/foo
getInputStream() for test:/foo
One InputStream for test:/foo closed
trying bootstrap ClassLoader
creating connection to test:/foo
getInputStream() for test:/foo
creating connection to test:/foo
getInputStream() for test:/foo
One InputStream for test:/foo closed
因此,从这个测试中,我可以得出结论,对于通过用户类路径和额外的ClassLoader
访问的所有资源,资源确实打开了两次,但也正确地关闭了,因此在这些情况下没有资源泄漏。
您对引导程序资源行为的代码分析是正确的,存在资源泄漏,但应用程序所需的资源通常不会发生这种情况,因为这些资源应该可以通过用户类路径访问。ClassLoader
首先尝试它们的父级,但您的资源不应在引导类路径中找到,因此该尝试应返回null
,而不打开任何资源。
因此,确保特定于应用程序的资源不能通过JRE的引导类路径访问至关重要,例如,不要操纵引导类路径,也不要将资源放入JRE的扩展目录。这也适用于上面的测试代码,如果您更改测试的顺序,即首先修补引导类路径,则当所有查找首先尝试其父级时,所有测试都将显示泄漏,并在引导加载程序处结束。