Java 使用HashMap的潜在资源泄漏(未分配可关闭)

Java 使用HashMap的潜在资源泄漏(未分配可关闭),java,memory-leaks,lucene,hashmap,Java,Memory Leaks,Lucene,Hashmap,我的整个系统有一个静态HashMap,其中包含一些对象的引用;让我们称之为myHash。这些对象仅在我需要它们时实例化,例如 private static HashMap<String, lucene.store.Directory> directories; public static Object getFoo(String key) { if (directories == null) { directories = new HashMap<St

我的整个系统有一个静态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
}
私有静态HashMap目录;
公共静态对象getFoo(字符串键){
如果(目录==null){
directories=newhashmap();
}
if(directories.get(key)==null){
directories.put(key,new-RAMDirectory());
}
返回目录。获取(键);//警告
}
现在,Eclipse在return语句中告诉我一个警告:

此位置可能无法关闭潜在的资源泄漏:“”


为什么eclipse会告诉我这一点?

目录
是一个可关闭的目录,它没有以实例化它的相同方法关闭,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
    }
}

目录
是一个
可关闭的
目录,它不是以实例化它的相同方法关闭的,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
    }
}

你能提供
myHash
字段声明吗?什么是
which
?如果您能将此转化为一个简短但完整的示例来演示问题,那么将更容易为您提供帮助。您能提供
myHash
字段声明吗?以及什么是
whatever
?如果你能把它变成一个简短但完整的例子来演示这个问题,那么帮助你就容易多了。