![](/img/trans.png)
[英]Why I get 'Resource leak: '<unassigned Closeable value>' ' error even when I use close() method in Java?
[英]potential resource leak (unassigned Closeable) with a HashMap
我的整个系统都有一个静态HashMap,其中包含一些对象的引用。 我们称之为myHash
。 对象仅在需要时实例化,例如
private static HashMap<String, lucene.store.Directory> directories;
public static Object getFoo(String key) {
if (directories == null) {
directories = new HashMap<String, Directory>();
}
if (directories.get(key) == null) {
directories.put(key, new RAMDirectory());
}
return directories.get(key); // warning
}
现在,Eclipse在return语句中告诉我一个警告:
Potential resource leak: '<unassigned Closeable value>' may not be closed at this location
蚀为什么告诉我?
Directory
是一个Closeable
,不会以实例化该方法的相同方法关闭,Eclipse警告您,如果未在其他位置关闭,则可能造成潜在的资源泄漏。 换句话说,无论可能引发了什么错误, Closeable
实例都应该始终在某个位置关闭。
这是在Java 7+中使用Closeable
的常用方法:
try (Directory dir = new RAMDirectory()) {
// use dir here, it will be automatically closed at the end of this block.
}
// exception catching omitted
在Java 6-中:
Directory dir = null;
try {
dir = new RAMDirectory();
// use dir here, it will be automatically closed in the finally block.
} finally {
if (dir != null) {
dir.close(); // exception catching omitted
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.