I have a singleton class:
public class MySingleton {
private static MySingleton instance;
// here the Map entry's value is also a Map
private Map<String, Map> dataMap;
private MySingleton() {
dataMap = new HashMap<String, Map>();
Map<String, String> dataTypeOneMap = new HashMap<String, String>();
Map<String, String> dataTypeTwoMap = new HashMap<String, String>();
dataMap.put("dataTypeOne", dataTypeOneMap);
dataMap.put("dataTypeTwo", dataTypeTwoMap);
}
public static MySingleton getInstance() {
if(instance == null) {
instance = new MySingleton();
}
return instance;
}
public synchronized void storeData(String data, String type) {
dataMap.get(type).put("my_data", data);
}
public synchronized String getData(type) {
return dataMap.get(type).get("my_data");
}
}
Multiple threads can access the public methods storeData(...)
& getData(...)
. e.g.:
MySingleton.getInstance().storeData("hello", "dataTypeOne");
MySingleton.getInstance().getData("dataTypeOne");
Do I need to use ConcurrentHashMap
type for dataMap
? or is it already thread safe? I feel my code is already thread safe but just want to make sure no corner case would break it. Thanks.