前言

线程安全的map类,底层对传递的map进行加锁处理。

初始化

数据全部存储在m中,进行了一层包装处理。

  1. private final Map<K,V> m; // Backing Map
  2. final Object mutex; // Object on which to synchronize
  3. SynchronizedMap(Map<K,V> m) {
  4. this.m = Objects.requireNonNull(m);
  5. mutex = this;
  6. }
  7. SynchronizedMap(Map<K,V> m, Object mutex) {
  8. this.m = m;
  9. this.mutex = mutex;
  10. }

主要方法

主要方法都是对mutex进行加锁处理,以便安全访问。

  1. public int size() {
  2. synchronized (mutex) {return m.size();}
  3. }
  4. public boolean isEmpty() {
  5. synchronized (mutex) {return m.isEmpty();}
  6. }
  7. public boolean containsKey(Object key) {
  8. synchronized (mutex) {return m.containsKey(key);}
  9. }
  10. public boolean containsValue(Object value) {
  11. synchronized (mutex) {return m.containsValue(value);}
  12. }
  13. public V get(Object key) {
  14. synchronized (mutex) {return m.get(key);}
  15. }
  16. public V put(K key, V value) {
  17. synchronized (mutex) {return m.put(key, value);}
  18. }
  19. public V remove(Object key) {
  20. synchronized (mutex) {return m.remove(key);}
  21. }
  22. public void putAll(Map<? extends K, ? extends V> map) {
  23. synchronized (mutex) {m.putAll(map);}
  24. }
  25. public void clear() {
  26. synchronized (mutex) {m.clear();}
  27. }