我需要对一个map及其内容进行惰性初始化。到目前为止,我有以下代码:
class SomeClass {
private Map<String, String> someMap = null;
public String getValue(String key) {
if (someMap == null) {
synchronized(someMap) {
someMap = new HashMap<String, String>();
// initialize the map contents by loading some data from the database.
// possible for the map to be empty after this.
}
}
return someMap.get(key); // the key might not exist even after initialization
}
}
如果一个线程在someMap
为空的时候进来,然后把字段初始化为new HashMap
,并且在加载映射中的数据时,另一个线程执行了getValue
操作,那么它可能无法获取数据(即使数据可能已经存在)。
我该如何确保只有第一次调用getValue
时才加载映射中的数据。
请注意,初始化后key
可能不存在于映射中。另外,也可能在初始化后映射为空。
synchronized(someMap)
这一行会收到NullPointerException异常,因为someMap
是空的。 - Idolon