如果我们有一个Contact对象的集合:联系人名单集合,然后给这个名单中每个联系人发送Email: public void sendMessages(Map contactMap) { sendEmail(contactMap.values()); } contactMap是Contact集合,contactMap.values是遍历contactMap中元素Contact对象。如果在遍历发生Email同时,有新的Contact对象加入到contactMap集合中,这时会抛出并发错误。当然,可以使用ConcurrentMap来实现Map。
但是该文提出一个不可变Map也许能获得更好地并发性能。
publicclass ImmutableMap implements Map {
privatefinal Map map;
public ImmutableMap() {
this(Collections.EMPTY_MAP);
}
public ImmutableMap immutablePut(K key, V value) {
Map newMap = new HashMap(map);
newMap.put(key, value);
returnnew ImmutableMap(newMap);//创新新的不可变Map
}
public ImmutableMap immutableRemove(K key) {
Map newMap = new HashMap(map);
newMap.remove(key);
returnnew ImmutableMap(newMap);
}
private ImmutableMap(Map delegate) {
this.map = Collections.unmodifiableMap(delegate);
}
// All the map methods are simply delegated to the map field.// To conserve space they are not shown here.
}
<p class="indent">