首页 > 编程语言 > 详细

3.3.2线程安全的HashMap

时间:2018-02-24 12:50:02      阅读:221      评论:0      收藏:0      [点我收藏+]
代码: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

原文:https://www.cnblogs.com/anxbb/p/8464774.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!