3.3.2线程安全的HashMap

Posted anxbb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3.3.2线程安全的HashMap相关的知识,希望对你有一定的参考价值。

代码: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的主要内容,如果未能解决你的问题,请参考以下文章

编程实践用 go 语言实现线程安全的 hashmap

HashMap为啥不安全?

Java并发多线程编程——集合类线程不安全之HashMap的示例及解决方案

都说知道 HashMap 线程不安全,那它为啥就不安全?

Java - HashMap 多线程安全解析

HashMap 对于不同的键是线程安全的吗?