• 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();}
    }


  • 相关阅读:
    反射-特性
    反射-2
    反射-1
    智能楼宇管理实用手册
    山光凝翠,川容如画——太原西山地区的历史营建与遗存
    城市逆向规划建设:基于城市生长点形态与机制的研究
    建筑快题设计50问与100例
    明清建筑二论·斗栱的起源与发展
    建筑工程计量与计价实训教程(甘肃版)
    室内设计手绘快速表现技法火星课堂
  • 原文地址:https://www.cnblogs.com/anxbb/p/8464774.html
Copyright © 2020-2023  润新知