一、前言
基于mina-core(2.0.4)包中org.apache.mina.util.CopyOnWriteMap自定义实现可读写的Map,在操作Map时,通过synchronized多线程同步控制,每次创建新的HashMap进行put、remove等操作,具体源码如下所示
二、源码说明
package org.apache.mina.util;@b@@b@import java.util.Collection;@b@import java.util.HashMap;@b@import java.util.Map;@b@import java.util.Map.Entry;@b@import java.util.Set;@b@@b@public class CopyOnWriteMap<K, V>@b@ implements Map<K, V>, Cloneable@b@{@b@ private volatile Map<K, V> internalMap;@b@@b@ public CopyOnWriteMap()@b@ {@b@ this.internalMap = new HashMap();@b@ }@b@@b@ public CopyOnWriteMap(int initialCapacity)@b@ {@b@ this.internalMap = new HashMap(initialCapacity);@b@ }@b@@b@ public CopyOnWriteMap(Map<K, V> data)@b@ {@b@ this.internalMap = new HashMap(data);@b@ }@b@@b@ public V put(K key, V value)@b@ {@b@ synchronized (this) {@b@ Map newMap = new HashMap(this.internalMap);@b@ Object val = newMap.put(key, value);@b@ this.internalMap = newMap;@b@ return val;@b@ }@b@ }@b@@b@ public V remove(Object key)@b@ {@b@ synchronized (this) {@b@ Map newMap = new HashMap(this.internalMap);@b@ Object val = newMap.remove(key);@b@ this.internalMap = newMap;@b@ return val;@b@ }@b@ }@b@@b@ public void putAll(Map<? extends K, ? extends V> newData)@b@ {@b@ synchronized (this) {@b@ Map newMap = new HashMap(this.internalMap);@b@ newMap.putAll(newData);@b@ this.internalMap = newMap;@b@ }@b@ }@b@@b@ public void clear()@b@ {@b@ synchronized (this) {@b@ this.internalMap = new HashMap();@b@ }@b@ }@b@@b@ public int size()@b@ {@b@ return this.internalMap.size();@b@ }@b@@b@ public boolean isEmpty()@b@ {@b@ return this.internalMap.isEmpty();@b@ }@b@@b@ public boolean containsKey(Object key)@b@ {@b@ return this.internalMap.containsKey(key);@b@ }@b@@b@ public boolean containsValue(Object value)@b@ {@b@ return this.internalMap.containsValue(value);@b@ }@b@@b@ public V get(Object key)@b@ {@b@ return this.internalMap.get(key);@b@ }@b@@b@ public Set<K> keySet()@b@ {@b@ return this.internalMap.keySet();@b@ }@b@@b@ public Collection<V> values()@b@ {@b@ return this.internalMap.values();@b@ }@b@@b@ public Set<Map.Entry<K, V>> entrySet()@b@ {@b@ return this.internalMap.entrySet();@b@ }@b@@b@ public Object clone()@b@ {@b@ try {@b@ return super.clone();@b@ } catch (CloneNotSupportedException e) {@b@ throw new InternalError();@b@ }@b@ }@b@}