我有以下代碼:填充單地圖
public class SomeClass{
private static volatile TreeMap<String, SomeData> map;
public static TreeMap<String,String> getSingletonMap(){
if(map=null){
synchronized(SomeClass.class){
if(map==null){
map = new TreeMap<>();
}
}
}
return map;
}
public static synchronized void add(SomeData data){
TreeMap<String,String> treeMap = getSingletonMap();
treeMap.put(data.key, data);
}
public final class SomeData{
String key;
public SomeData(String key){
this.key = key;
}
}
}
public class SomeOtherClass{
//this method is called by multiple threads
public static synchronized collectData(){
try{
//do some iteration here and add data at every iteration
for(String str : strings){
SomeClass.add(new SomeClass.SomeData(string));
}
}
finally{
//do some processing of collected data by main Thread
// at this point TreeMap of SomeClass is null;
}
}
}
}
每次不同的線程訪問循環和添加數據,樹形圖再次被初始化。並且在finally塊中,當主線程繼續時,它也會被重新初始化,但是TreeMap應該是一個單例。我在這裏錯過了什麼?有任何想法嗎?
請告訴我們真正的代碼,或者更好的是一個完整的小例子,重現問題。這段代碼甚至不會編譯。 –
您的代碼無法編譯,因此請向我們展示您真正使用的代碼。謝謝。 – Tom
我無法重現您的問題。也許你的測試結構有問題:確保'collectData()'中的'strings'不總是相同的,因爲如果它們是* equal *,新的'key'將覆蓋舊的密鑰。並且確保在「睡眠」或「等待」一段時間後檢查'map'的內容,因爲主線程不會等待直到子線程填充該映射。 – Tom