potential resource leak (unassigned Closeable) with a HashMap

旧巷老猫 提交于 2019-12-25 07:38:10

问题


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
}

Now, Eclipse is telling me a warning in the return statement:

Potential resource leak: '<unassigned Closeable value>' may not be closed at this location

Why is eclipse telling me that?


回答1:


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.

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

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


来源:https://stackoverflow.com/questions/23779163/potential-resource-leak-unassigned-closeable-with-a-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!