5

我将尝试证明ClassLoader.getResourceAsStream()打开两个InputStreams,一个都不关闭,只返回一个给客户。我的逻辑正确吗?JDK 源码选自 jdk1.8.0_25

我在间隔(原始问题)中使用 Spring ClassPathResource 遇到了未关闭的资源问题,该问题ClassLoader.getResourceAsStream用于获取InputStream属性文件。

经过调查,我发现classLoader.getResourceAsStream正在URL通过URL url = getResource(name);然后它正在打开该流,但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)的那一刻ResourceURL 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()and getInputStream(),它们没有关闭,并且通过所有返回的调用回退,Resource我们最终只使用getURL()包装的方法Resource而不关闭它InputStream只是使用该URL对象打开另一个 jetInputStream并将其返回给客户端(客户端可以关闭coruse,但我们以第一个未关闭的流结束)。

那么,ClassLaoder.getResourceAsStream 是否因资源泄漏而中断?

实用方面:我getResourceAsStreamtry-with-resources块中使用,并且在生产中仍然存在未关闭的资源问题,每 30 秒以这种方式加载文件名。此外,所有资源在垃圾回收时都关闭,这与方法中的文件流close()一致finalize()

4

1 回答 1

3

我做了一个简单的测试程序来验证实际行为:

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

所以从这个测试中,我可以得出结论,资源确实打开了两次,但也正确关闭了通过用户类路径和附加ClassLoaders 访问的所有资源,因此在这些情况下没有资源泄漏。

您对引导资源行为的代码分析是正确的,存在资源泄漏,但对于您的应用程序所需的资源,通常不会发生这种情况,因为这些资源应该可以通过用户类路径访问。ClassLoaders 首先尝试他们的父母,但您的资源不应该在引导类路径中找到,因此该尝试应该返回null并且不打开任何资源。

因此,确保应用程序特定资源不能通过 JRE 的引导类路径访问至关重要,例如,不要操纵引导类路径,也不要将资源放入 JRE 的扩展目录。这也适用于上面的测试代码,如果您更改测试的顺序,即首先修补引导类路径,所有测试都将显示泄漏,因为所有查找首先尝试其父项,并在引导加载程序处结束。

于 2015-02-13T10:25:19.780 回答