应该关闭Class.getResourceAsStream吗? [英] should Class.getResourceAsStream be closed?

查看:1824
本文介绍了应该关闭Class.getResourceAsStream吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这是否是必需的,因为当我使用这个方法时,正在从类路径中读取文件。 不关闭会导致内存泄漏。

I was wondering if this is required since when i use this method, the file is being read from the classpath. Does "not closing" it lead to a memory leak.

我如何测试此类内存泄漏?

How can i test for such memory leaks?

推荐答案

您假设 Class.getResourceAsStream()将始终返回指向类JAR文件中的文件的流。这是不正确的。您的类路径也可能包含文件夹,在这种情况下, Class.getResourceAsStream()将返回 FileInputStream 。其他一些类加载器也可能返回其他类型的资源,例如远程文件(在URLClassLoader的情况下)。

You are assuming that Class.getResourceAsStream() will always return a stream that points to a file inside your class' JAR file. This is incorrect. Your classpath may also contains folders, in which case Class.getResourceAsStream() will return a FileInputStream. Some other class loaders might also return other type of resources, such as remote files (in the case of a URLClassLoader).

即使在JAR文件的情况下,它也是如此有可能该实现通过任何方式维护JAR文件中的持久视图到您正在访问的文件的压缩字节。也许它持有内存映射 ByteBuffer ...

Even in the case of a JAR file, it is possible that the implementation maintain, by whatever mean, a persistant view inside the JAR file to the compressed bytes of the file you are accessing. Maybe it is holding upon a memory mapped ByteBuffer...

为什么要抓住机会?你应该总是关闭流(以及其他任何Closeable,实际上),无论它们是如何给你的。

Why take the chance? You should always close streams (and any other Closeable, actually), no matter how they were given to you.

至于检测泄漏,最好的策略是获得一个VM关闭时的内存转储,然后用一些工具进行分析。两个流行的工具是 jhat Eclipse垫

As for detecting leaks, the best strategy is to obtain a memory dump at the time the VM is shut down, then analyze it with some tool. Two popular tools are jhat and Eclipse mat.

这篇关于应该关闭Class.getResourceAsStream吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆