ConcurrentHashMap涓巗ynchronizedMap婧愮爜瑙f瀽

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ConcurrentHashMap涓巗ynchronizedMap婧愮爜瑙f瀽相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/class' title='class'>class   tran   eof   create   鍦ㄧ嚎   sem   eval   eal   UNC   

銆€銆€涓€銆乻ynchronizedMap

銆€銆€銆€Collections.synchronized*(m)灏嗙嚎绋嬩笉瀹夊叏闆嗗悎鍙樹负绾跨▼瀹夊叏闆嗗悎锛屼粠婧愮爜鏉ョ湅鐢变簬synchronizedMap鐨勪綔鐢ㄥ氨鏄皢Map鐨勫悇绉嶆柟娉曟坊鍔犱簡synchronized鍏抽敭瀛楄繘琛屼慨楗扮殑銆?/p>

  1    private static class SynchronizedMap<K,V>
  2         implements Map<K,V>, Serializable {
  3         private static final long serialVersionUID = 1978198479659022715L;
  4 
  5         private final Map<K,V> m;     // Backing Map
  6         final Object      mutex;        // Object on which to synchronize
  7 
  8         SynchronizedMap(Map<K,V> m) {
  9             this.m = Objects.requireNonNull(m);
 10             mutex = this;
 11         }
 12 
 13         SynchronizedMap(Map<K,V> m, Object mutex) {
 14             this.m = m;
 15             this.mutex = mutex;
 16         }
 17 
 18         public int size() {
 19             synchronized (mutex) {return m.size();}
 20         }
 21         public boolean isEmpty() {
 22             synchronized (mutex) {return m.isEmpty();}
 23         }
 24         public boolean containsKey(Object key) {
 25             synchronized (mutex) {return m.containsKey(key);}
 26         }
 27         public boolean containsValue(Object value) {
 28             synchronized (mutex) {return m.containsValue(value);}
 29         }
 30         public V get(Object key) {
 31             synchronized (mutex) {return m.get(key);}
 32         }
 33 
 34         public V put(K key, V value) {
 35             synchronized (mutex) {return m.put(key, value);}
 36         }
 37         public V remove(Object key) {
 38             synchronized (mutex) {return m.remove(key);}
 39         }
 40         public void putAll(Map<? extends K, ? extends V> map) {
 41             synchronized (mutex) {m.putAll(map);}
 42         }
 43         public void clear() {
 44             synchronized (mutex) {m.clear();}
 45         }
 46 
 47         private transient Set<K> keySet;
 48         private transient Set<Map.Entry<K,V>> entrySet;
 49         private transient Collection<V> values;
 50 
 51         public Set<K> keySet() {
 52             synchronized (mutex) {
 53                 if (keySet==null)
 54                     keySet = new SynchronizedSet<>(m.keySet(), mutex);
 55                 return keySet;
 56             }
 57         }
 58 
 59         public Set<Map.Entry<K,V>> entrySet() {
 60             synchronized (mutex) {
 61                 if (entrySet==null)
 62                     entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
 63                 return entrySet;
 64             }
 65         }
 66 
 67         public Collection<V> values() {
 68             synchronized (mutex) {
 69                 if (values==null)
 70                     values = new SynchronizedCollection<>(m.values(), mutex);
 71                 return values;
 72             }
 73         }
 74 
 75         public boolean equals(Object o) {
 76             if (this == o)
 77                 return true;
 78             synchronized (mutex) {return m.equals(o);}
 79         }
 80         public int hashCode() {
 81             synchronized (mutex) {return m.hashCode();}
 82         }
 83         public String toString() {
 84             synchronized (mutex) {return m.toString();}
 85         }
 86 
 87         // Override default methods in Map
 88         @Override
 89         public V getOrDefault(Object k, V defaultValue) {
 90             synchronized (mutex) {return m.getOrDefault(k, defaultValue);}
 91         }
 92         @Override
 93         public void forEach(BiConsumer<? super K, ? super V> action) {
 94             synchronized (mutex) {m.forEach(action);}
 95         }
 96         @Override
 97         public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
 98             synchronized (mutex) {m.replaceAll(function);}
 99         }
100         @Override
101         public V putIfAbsent(K key, V value) {
102             synchronized (mutex) {return m.putIfAbsent(key, value);}
103         }
104         @Override
105         public boolean remove(Object key, Object value) {
106             synchronized (mutex) {return m.remove(key, value);}
107         }
108         @Override
109         public boolean replace(K key, V oldValue, V newValue) {
110             synchronized (mutex) {return m.replace(key, oldValue, newValue);}
111         }
112         @Override
113         public V replace(K key, V value) {
114             synchronized (mutex) {return m.replace(key, value);}
115         }
116         @Override
117         public V computeIfAbsent(K key,
118                 Function<? super K, ? extends V> mappingFunction) {
119             synchronized (mutex) {return m.computeIfAbsent(key, mappingFunction);}
120         }
121         @Override
122         public V computeIfPresent(K key,
123                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
124             synchronized (mutex) {return m.computeIfPresent(key, remappingFunction);}
125         }
126         @Override
127         public V compute(K key,
128                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
129             synchronized (mutex) {return m.compute(key, remappingFunction);}
130         }
131         @Override
132         public V merge(K key, V value,
133                 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
134             synchronized (mutex) {return m.merge(key, value, remappingFunction);}
135         }
136 
137         private void writeObject(ObjectOutputStream s) throws IOException {
138             synchronized (mutex) {s.defaultWriteObject();}
139         }
140     }

銆€銆€浜屻€?span class="15">ConcurrentHashMap

銆€銆€ConcurrentMap鎺ュ彛涓嬫湁涓や釜閲嶈鐨勫疄鐜帮細

銆€銆€ConcurrentHashMap

銆€銆€ConcurrentskipListMap(鏀寔骞跺彂鎺掑簭鍔熻兘锛屽讥琛oncurrentHashMap)

銆€銆€ConcurrentHashMap鍐呴儴浣跨敤娈碉紙Segment锛夋潵琛ㄧず杩欎簺涓嶅悓鐨勯儴鍒嗭紝姣忎釜娈靛叾瀹炲氨鏄竴涓皬鐨凥ashTable锛屽畠浠湁鑷繁鐨勯攣銆傚彧瑕佸涓慨鏀规搷浣滃彂鐢熷湪涓嶅悓鐨勬涓婏紝瀹冧滑灏卞彲浠ュ苟鍙戣繘琛屻€傛妸涓€涓暣浣撳垎鎴愪簡16娈碉紙Segment涔熷氨鏄渶楂樻敮鎸?6涓嚎绋嬬殑骞跺彂淇敼鎿嶄綔锛岃繖涔熸槸鍦ㄩ噸绾跨▼鍦烘櫙鏃跺噺灏忛攣鐨勭矑搴︿粠鑰岄檷浣庨攣绔炰簤鐨勪竴绉嶆柟妗堛€傚苟涓斾唬鐮佷腑澶у鍏变韩鍙橀噺浣跨敤volatile鍏抽敭瀛楀0鏄庯紝鐩殑鏃剁涓€鏃堕棿鑾峰彇淇敼鐨勫唴瀹癸紝鎬ц兘闈炲父濂斤級銆?/span>

銆€銆€閿佸垎娈垫妧鏈?/span>

銆€銆€ConcurrentHashMap鏄皢Map鍒嗘垚寰堝灏忔鐨凥ashTable锛岀敱浜嶩ashTable瀹瑰櫒鍦ㄧ嚎绋嬬珵浜夋縺鐑堢殑鎯呭喌涓嬫晥鐜囦綆涓嬬殑鍘熷洜锛屾墍鏈夌殑绾跨▼閮藉幓绔炰簤涓€鎶婇攣銆侰oncurrentHashMap灏辨槸浣跨敤閿佸垎娈垫妧鏈皢鏁版嵁鍒嗘垚澶氭杩涜瀛樺偍锛岀劧鍚庣粰姣忎竴娈垫暟鎹厤涓€鎶婇攣锛屽綋绾跨▼鍗犵敤閿佽闂叾涓竴娈垫暟鎹殑鏃跺€欙紝鍏朵粬娈电殑鏁版嵁涔熻兘琚叾浠栫嚎绋嬭闂紝浠庤€屽苟鍙戞彁楂樻晥鐜囥€?/span>

1     /**
2      * Creates a new, empty map with the default initial table size (16).
3      *瀹归噺鏄?6
4      */
5     public ConcurrentHashMap() {
6     }
 1 /**
 2      * Maps the specified key to the specified value in this table.
 3      * Neither the key nor the value can be null.
 4      *
 5      * <p>The value can be retrieved by calling the {@code get} method
 6      * with a key that is equal to the original key.
 7      *
 8      * @param key key with which the specified value is to be associated
 9      * @param value value to be associated with the specified key
10      * @return the previous value associated with {@code key}, or
11      *         {@code null} if there was no mapping for {@code key}
12      * @throws NullPointerException if the specified key or value is null
13      */
14     public V put(K key, V value) {
15         return putVal(key, value, false);
16     }
17 
18     /** Implementation for put and putIfAbsent */
19     final V putVal(K key, V value, boolean onlyIfAbsent) {
20         if (key == null || value == null) throw new NullPointerException();
21         int hash = spread(key.hashCode());
22         int binCount = 0;
23         for (Node<K,V>[] tab = table;;) {
24             Node<K,V> f; int n, i, fh;
25             if (tab == null || (n = tab.length) == 0)
26                 tab = initTable();
27             else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
28                 if (casTabAt(tab, i, null,
29                              new Node<K,V>(hash, key, value, null)))
30                     break;                   // no lock when adding to empty bin
31             }
32             else if ((fh = f.hash) == MOVED)
33                 tab = helpTransfer(tab, f);
34             else {
35                 V oldVal = null;
36                 synchronized (f) {
37                     if (tabAt(tab, i) == f) {
38                         if (fh >= 0) {
39                             binCount = 1;
40                             for (Node<K,V> e = f;; ++binCount) {
41                                 K ek;
42                                 if (e.hash == hash &&
43                                     ((ek = e.key) == key ||
44                                      (ek != null && key.equals(ek)))) {
45                                     oldVal = e.val;
46                                     if (!onlyIfAbsent)
47                                         e.val = value;
48                                     break;
49                                 }
50                                 Node<K,V> pred = e;
51                                 if ((e = e.next) == null) {
52                                     pred.next = new Node<K,V>(hash, key,
53                                                               value, null);
54                                     break;
55                                 }
56                             }
57                         }
58                         else if (f instanceof TreeBin) {
59                             Node<K,V> p;
60                             binCount = 2;
61                             if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
62                                                            value)) != null) {
63                                 oldVal = p.val;
64                                 if (!onlyIfAbsent)
65                                     p.val = value;
66                             }
67                         }
68                     }
69                 }
70                 if (binCount != 0) {
71                     if (binCount >= TREEIFY_THRESHOLD)
72                         treeifyBin(tab, i);
73                     if (oldVal != null)
74                         return oldVal;
75                     break;
76                 }
77             }
78         }
79         addCount(1L, binCount);
80         return null;
81     }
 1 /**
 2      * Returns the value to which the specified key is mapped,
 3      * or {@code null} if this map contains no mapping for the key.
 4      *
 5      * <p>More formally, if this map contains a mapping from a key
 6      * {@code k} to a value {@code v} such that {@code key.equals(k)},
 7      * then this method returns {@code v}; otherwise it returns
 8      * {@code null}.  (There can be at most one such mapping.)
 9      *
10      * @throws NullPointerException if the specified key is null
11      */
12     public V get(Object key) {
13         Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
14         int h = spread(key.hashCode());
15         if ((tab = table) != null && (n = tab.length) > 0 &&
16             (e = tabAt(tab, (n - 1) & h)) != null) {
17             if ((eh = e.hash) == h) {
18                 if ((ek = e.key) == key || (ek != null && key.equals(ek)))
19                     return e.val;
20             }
21             else if (eh < 0)
22                 return (p = e.find(h, key)) != null ? p.val : null;
23             while ((e = e.next) != null) {
24                 if (e.hash == h &&
25                     ((ek = e.key) == key || (ek != null && key.equals(ek))))
26                     return e.val;
27             }
28         }
29         return null;
30     }

 

以上是关于ConcurrentHashMap涓巗ynchronizedMap婧愮爜瑙f瀽的主要内容,如果未能解决你的问题,请参考以下文章

spark1.3.x涓巗park2.x鍚姩executor涓嶅悓鐨刢pu core鍒嗛厤鏂瑰紡

ConcurrentHashMap源码分析(1.8)

ConcurrentHashMap

JDK1.7中的ConcurrentHashMap

ConcurrentHashMap

ConcurrentHashmap原理