1. 程式人生 > >3.3.2線程安全的HashMap

3.3.2線程安全的HashMap

pos font lec serializa exceptio pan private 代碼 nsvalue

代碼:public class SysHashMao {
private static Map<String,String> map= Collections.synchronizedMap(new HashMap<String,String>());
public static void main(String[] args) {
map.put("11","11");
map.get("11");
}
}

源碼解讀:可以看到,SynchronizedMap的每一個方法 都加上了Synchronized關鍵字,通過鎖定mutex,達到加鎖的限制,從而保障了線程的安全性


private static class SynchronizedMap<K,V>
implements Map<K,V>, Serializable {
private static final long serialVersionUID = 1978198479659022715L;

private final Map<K,V> m; // Backing Map
final Object mutex; // Object on which to synchronize

SynchronizedMap(Map<K,V> m) {

if (m==null)
throw new NullPointerException();
this.m = m;
mutex = this;
}

SynchronizedMap(Map<K,V> m, Object mutex) {
this.m = m;
this.mutex = mutex;
}

public int size() {
synchronized (mutex) {return m.size();}
}
public boolean isEmpty() {

synchronized (mutex) {return m.isEmpty();}
}
public boolean containsKey(Object key) {
synchronized (mutex) {return m.containsKey(key);}
}
public boolean containsValue(Object value) {
synchronized (mutex) {return m.containsValue(value);}
}
public V get(Object key) {
synchronized (mutex) {return m.get(key);}
}

public V put(K key, V value) {
synchronized (mutex) {return m.put(key, value);}
}
public V remove(Object key) {
synchronized (mutex) {return m.remove(key);}
}
public void putAll(Map<? extends K, ? extends V> map) {
synchronized (mutex) {m.putAll(map);}
}
public void clear() {
synchronized (mutex) {m.clear();}
}


3.3.2線程安全的HashMap