2014-05-21 124 views
0

我有一个静态HashMap为我的整个系统,其中包含一些对象的引用;我们称之为myHash。一旦我需要他们如潜在的资源泄漏(未分配的可关闭)与HashMap

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

你能提供'myHash'字段声明? – sp00m

+0

什么是“什么”?如果你可以把它变成一个简短但完整的例子来说明问题,那么帮助你会容易得多。 –

回答

4

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