使用HashMap的潜在资源泄漏(未分配Closeable) [英] potential resource leak (unassigned Closeable) with a HashMap
问题描述
我在整个系统中都有一个静态HashMap,其中包含一些对象的引用;我们称之为myHash
.这些对象仅在我需要它们时被实例化,例如
I have one static HashMap for my entire system which contains some object's references; let's call it myHash
. The objects are only instantiated once I needed them such as
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语句中告诉我一个警告:
Now, Eclipse is telling me a warning in the return statement:
Potential resource leak: '<unassigned Closeable value>' may not be closed at this location
为什么月食会告诉我?
推荐答案
Directory
是一个Closeable
,它没有使用实例化的相同方法被关闭,Eclipse警告您,如果不关闭它,可能会造成潜在的资源泄漏别的地方.换句话说,Closeable
实例应该始终在某个位置关闭,无论可能引发什么错误.
Directory
is a Closeable
that is not closed in the same method it is instantiated in, Eclipse warns you this could create potential resource leaks if not closed somewhere else. In other words, a Closeable
instance should always be closed somewhere, whatever error could have been thrown.
这是在Java 7+中使用Closeable
的常用方法:
Here is the usual way to use a Closeable
in Java 7+:
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
}
}
这篇关于使用HashMap的潜在资源泄漏(未分配Closeable)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!