我有一个包含 hahsmap 的单例类,hashmap 被初始化为类变量。该地图已正确更新,因为当我添加并打印它更改的大小时,但是当我从不同的线程调用它时,地图始终为空。发生这种情况是否有特殊原因?
如果这有什么不同,我正在使用 ConccurentHashMap。
谢谢
Singleton decleration:
public class ClientRegistryDetailsSingleton {
private static ClientRegistryDetailsSingleton instance = null;
private ConcurrentHashMap<String, Integer> tickerToNumberRegistered = new ConcurrentHashMap<String,Integer>();
protected ClientRegistryDetailsSingleton() {
// Exists only to defeat instantiation.
}
public static ClientRegistryDetailsSingleton getInstance() {
if(instance == null) {
instance = new ClientRegistryDetailsSingleton();
}
return instance;
}
public void setTickerToNumberRegistered(ConcurrentHashMap<String, Integer> tickerToNumberRegistered) {
this.tickerToNumberRegistered = tickerToNumberRegistered;
}
public ConcurrentHashMap<String, Integer> getTickerToNumberRegistered() {
return tickerToNumberRegistered;
}
public void addToClienets(String ticker){}
public void removeFromClients(String ticker){}
}
从另一个线程调用它:
String[] splitForTicker = message.split(",");
ConcurrentHashMap<String, Integer> map = ClientRegistryDetailsSingleton.getInstance().getTickerToNumberRegistered();
System.out.println("The number of items in the map from senders persepctive" + map.size());
输出:
The number of items in the map from senders persepctive 0 2012-11-12 14:29:12,495 [Process messages received] INFO com.feed.feedReceive.ProcessFeedStreamLine - Successfully received a message from the feed The number of items in the map from senders persepctive 0 1 :the size of the map now someone has added 2012-11-12 14:29:15,495 [Process messages received] INFO com.feed.feedReceive.ProcessFeedStreamLine - Successfully received a
来自提要的消息 来自发件人的地图中的项目数 persepctive 0
单例的新代码
public class ClientRegistryDetailsSingleton {
private static ClientRegistryDetailsSingleton instance = new ClientRegistryDetailsSingleton();
private volatile ConcurrentHashMap<String, Integer> tickerToNumberRegistered = new ConcurrentHashMap<String,Integer>();
protected ClientRegistryDetailsSingleton() {
// Exists only to defeat instantiation.
}
public static synchronized ClientRegistryDetailsSingleton getInstance() {
return instance;
}
public synchronized ConcurrentHashMap<String, Integer> getTickerToNumberRegistered() {
return tickerToNumberRegistered;
}
public void addToClienets(String ticker){}
public void removeFromClients(String ticker){}
}