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?
Directory
is aCloseable
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, aCloseable
instance should always be closed somewhere, whatever error could have been thrown.Here is the usual way to use a
Closeable
in Java 7+:In Java 6-: