hahsmapを含むシングルトンクラスがあります。ハッシュマップはクラス変数として初期化されます。サイズを追加して印刷すると変更されたため、このマップは正しく更新されますが、別のスレッドから呼び出すと、マップは常に空になります。これが発生する可能性がある特別な理由はありますか?
これで違いが生じる場合は、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
フィードからのメッセージ送信者からのマップ内のアイテムの数persepctive0
シングルトンの新しいコード
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){}
}