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

时间:2014-05-21 09:27:02

标签: 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<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

为什么日食会告诉我这个?

1 个答案:

答案 0 :(得分:4)

DirectoryCloseable,它没有在实例化的同一方法中关闭,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
    }
}