public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
Collections.synchronizedMap() guarantees that each atomic operation I want to run on the map will be synchronized. It creates a blocking Map which will degrade performance, however it ensure consistency (if used properly).
Let's see at a sample code:
Map<String, List<String>> myMap;
myMap = new HashMap<String, List<String>>();
private static Map<String, List<String>> synchroMap = Collections.synchronizedMap(myMap);
public static void addToMyMap(String myKey, String myValue) {
synchronized (synchroMap) {
if (!synchroMap.containsKey(myKey)) {
List<String> listOfValues = new ArrayList<String>();
listOfValues.add(myValue);
synchroMap.put(myKey, listOfValues);
}else{
synchroMap.get(myKey).add(myValue);
}
}
}
And what about java.util.concurrent.ConcurrentHashMap?
It allows concurrent changes of the Map from several threads without the need to block them. We can use it when the performance is critical.
No comments:
Post a Comment