【问题标题】:potential resource leak (unassigned Closeable) with a HashMap带有 HashMap 的潜在资源泄漏(未分配的 Closeable)
【发布时间】:2014-05-21 09:27:01
【问题描述】:

我的整个系统都有一个静态 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: '&lt;unassigned Closeable value&gt;' may not be closed at this location

为什么 eclipse 会这样告诉我?

【问题讨论】:

  • 能否提供myHash字段声明?
  • whatever 是什么?如果你能把它变成一个简短但完整的例子来演示这个问题,那么帮助你会容易得多。

标签: java memory-leaks lucene hashmap


【解决方案1】:

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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多