文章已經收錄在 Github.com/niumoo/JavaNotes ,更有 Java 程序員所須要掌握的核心知識,歡迎Star和指教。
歡迎關注個人 公衆號,文章每週更新。
上一篇文章介紹了 HashMap 源碼,反響不錯,也有不少同窗發表了本身的觀點,此次又來了,此次是 ConcurrentHashMap
了,做爲線程安全的HashMap ,它的使用頻率也是很高。那麼它的存儲結構和實現原理是怎麼樣的呢?java
Java 7 中 ConcurrentHashMap 的存儲結構如上圖,ConcurrnetHashMap 由不少個 Segment 組合,而每個 Segment 是一個相似於 HashMap 的結構,因此每個 HashMap 的內部能夠進行擴容。可是 Segment 的個數一旦初始化就不能改變,默認 Segment 的個數是 16 個,你也能夠認爲 ConcurrentHashMap 默認支持最多 16 個線程併發。node
經過 ConcurrentHashMap 的無參構造探尋 ConcurrentHashMap 的初始化流程。git
/** * Creates a new, empty map with a default initial capacity (16), * load factor (0.75) and concurrencyLevel (16). */ public ConcurrentHashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); }
無參構造中調用了有參構造,傳入了三個參數的默認值,他們的值是。程序員
/** * 默認初始化容量 */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * 默認負載因子 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * 默認併發級別 */ static final int DEFAULT_CONCURRENCY_LEVEL = 16;
接着看下這個有參構造函數的內部實現邏輯。github
@SuppressWarnings("unchecked") public ConcurrentHashMap(int initialCapacity,float loadFactor, int concurrencyLevel) { // 參數校驗 if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0) throw new IllegalArgumentException(); // 校驗併發級別大小,大於 1<<16,重置爲 65536 if (concurrencyLevel > MAX_SEGMENTS) concurrencyLevel = MAX_SEGMENTS; // Find power-of-two sizes best matching arguments // 2的多少次方 int sshift = 0; int ssize = 1; // 這個循環能夠找到 concurrencyLevel 之上最近的 2的次方值 while (ssize < concurrencyLevel) { ++sshift; ssize <<= 1; } // 記錄段偏移量 this.segmentShift = 32 - sshift; // 記錄段掩碼 this.segmentMask = ssize - 1; // 設置容量 if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; // c = 容量 / ssize ,默認 16 / 16 = 1,這裏是計算每一個 Segment 中的相似於 HashMap 的容量 int c = initialCapacity / ssize; if (c * ssize < initialCapacity) ++c; int cap = MIN_SEGMENT_TABLE_CAPACITY; //Segment 中的相似於 HashMap 的容量至少是2或者2的倍數 while (cap < c) cap <<= 1; // create segments and segments[0] // 建立 Segment 數組,設置 segments[0] Segment<K,V> s0 = new Segment<K,V>(loadFactor, (int)(cap * loadFactor), (HashEntry<K,V>[])new HashEntry[cap]); Segment<K,V>[] ss = (Segment<K,V>[])new Segment[ssize]; UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0] this.segments = ss; }
總結一下在 Java 7 中 ConcurrnetHashMap 的初始化邏輯。面試
接着上面的初始化參數繼續查看 put 方法源碼。數組
/** * Maps the specified key to the specified value in this table. * Neither the key nor the value can be null. * * <p> The value can be retrieved by calling the <tt>get</tt> method * with a key that is equal to the original key. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt> * @throws NullPointerException if the specified key or value is null */ public V put(K key, V value) { Segment<K,V> s; if (value == null) throw new NullPointerException(); int hash = hash(key); // hash 值無符號右移 28位(初始化時得到),而後與 segmentMask=15 作與運算 // 其實也就是把高4位與segmentMask(1111)作與運算 int j = (hash >>> segmentShift) & segmentMask; if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck (segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment // 若是查找到的 Segment 爲空,初始化 s = ensureSegment(j); return s.put(key, hash, value, false); } /** * Returns the segment for the given index, creating it and * recording in segment table (via CAS) if not already present. * * @param k the index * @return the segment */ @SuppressWarnings("unchecked") private Segment<K,V> ensureSegment(int k) { final Segment<K,V>[] ss = this.segments; long u = (k << SSHIFT) + SBASE; // raw offset Segment<K,V> seg; // 判斷 u 位置的 Segment 是否爲null if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) { Segment<K,V> proto = ss[0]; // use segment 0 as prototype // 獲取0號 segment 裏的 HashEntry<K,V> 初始化長度 int cap = proto.table.length; // 獲取0號 segment 裏的 hash 表裏的擴容負載因子,全部的 segment 的 loadFactor 是相同的 float lf = proto.loadFactor; // 計算擴容閥值 int threshold = (int)(cap * lf); // 建立一個 cap 容量的 HashEntry 數組 HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry[cap]; if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) { // recheck // 再次檢查 u 位置的 Segment 是否爲null,由於這時可能有其餘線程進行了操做 Segment<K,V> s = new Segment<K,V>(lf, threshold, tab); // 自旋檢查 u 位置的 Segment 是否爲null while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) { // 使用CAS 賦值,只會成功一次 if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s)) break; } } } return seg; }
上面的源碼分析了 ConcurrentHashMap 在 put 一個數據時的處理流程,下面梳理下具體流程。安全
若是指定位置的 Segment 爲空,則初始化這個 Segment.併發
初始化 Segment 流程:app
上面探究了獲取 Segment 段和初始化 Segment 段的操做。最後一行的 Segment 的 put 方法尚未查看,繼續分析。
final V put(K key, int hash, V value, boolean onlyIfAbsent) { // 獲取 ReentrantLock 獨佔鎖,獲取不到,scanAndLockForPut 獲取。 HashEntry<K,V> node = tryLock() ? null : scanAndLockForPut(key, hash, value); V oldValue; try { HashEntry<K,V>[] tab = table; // 計算要put的數據位置 int index = (tab.length - 1) & hash; // CAS 獲取 index 座標的值 HashEntry<K,V> first = entryAt(tab, index); for (HashEntry<K,V> e = first;;) { if (e != null) { // 檢查是否 key 已經存在,若是存在,則遍歷鏈表尋找位置,找到後替換 value K k; if ((k = e.key) == key || (e.hash == hash && key.equals(k))) { oldValue = e.value; if (!onlyIfAbsent) { e.value = value; ++modCount; } break; } e = e.next; } else { // first 有值沒說明 index 位置已經有值了,有衝突,鏈表頭插法。 if (node != null) node.setNext(first); else node = new HashEntry<K,V>(hash, key, value, first); int c = count + 1; // 容量大於擴容閥值,小於最大容量,進行擴容 if (c > threshold && tab.length < MAXIMUM_CAPACITY) rehash(node); else // index 位置賦值 node,node 多是一個元素,也多是一個鏈表的表頭 setEntryAt(tab, index, node); ++modCount; count = c; oldValue = null; break; } } } finally { unlock(); } return oldValue; }
因爲 Segment 繼承了 ReentrantLock,因此 Segment 內部能夠很方便的獲取鎖,put 流程就用到了這個功能。
scanAndLockForPut
方法繼續獲取。遍歷 put 新元素,爲何要遍歷?由於這裏獲取的 HashEntry 多是一個空元素,也多是鏈表已存在,因此要區別對待。
若是這個位置上的 HashEntry 不存在:
若是這個位置上的 HashEntry 存在:
不一致,獲取鏈表下一個節點,直到發現相同進行值替換,或者鏈表表裏完畢沒有相同的。
這裏面的第一步中的 scanAndLockForPut 操做這裏沒有介紹,這個方法作的操做就是不斷的自旋 tryLock()
獲取鎖。當自旋次數大於指定次數時,使用 lock()
阻塞獲取鎖。在自旋時順表獲取下 hash 位置的 HashEntry。
private HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) { HashEntry<K,V> first = entryForHash(this, hash); HashEntry<K,V> e = first; HashEntry<K,V> node = null; int retries = -1; // negative while locating node // 自旋獲取鎖 while (!tryLock()) { HashEntry<K,V> f; // to recheck first below if (retries < 0) { if (e == null) { if (node == null) // speculatively create node node = new HashEntry<K,V>(hash, key, value, null); retries = 0; } else if (key.equals(e.key)) retries = 0; else e = e.next; } else if (++retries > MAX_SCAN_RETRIES) { // 自旋達到指定次數後,阻塞等到只到獲取到鎖 lock(); break; } else if ((retries & 1) == 0 && (f = entryForHash(this, hash)) != first) { e = first = f; // re-traverse if entry changed retries = -1; } } return node; }
ConcurrentHashMap 的擴容只會擴容到原來的兩倍。老數組裏的數據移動到新的數組時,位置要麼不變,要麼變爲 index+ oldSize,參數裏的 node 會在擴容以後使用鏈表頭插法插入到指定位置。
private void rehash(HashEntry<K,V> node) { HashEntry<K,V>[] oldTable = table; // 老容量 int oldCapacity = oldTable.length; // 新容量,擴大兩倍 int newCapacity = oldCapacity << 1; // 新的擴容閥值 threshold = (int)(newCapacity * loadFactor); // 建立新的數組 HashEntry<K,V>[] newTable = (HashEntry<K,V>[]) new HashEntry[newCapacity]; // 新的掩碼,默認2擴容後是4,-1是3,二進制就是11。 int sizeMask = newCapacity - 1; for (int i = 0; i < oldCapacity ; i++) { // 遍歷老數組 HashEntry<K,V> e = oldTable[i]; if (e != null) { HashEntry<K,V> next = e.next; // 計算新的位置,新的位置只多是不便或者是老的位置+老的容量。 int idx = e.hash & sizeMask; if (next == null) // Single node on list // 若是當前位置還不是鏈表,只是一個元素,直接賦值 newTable[idx] = e; else { // Reuse consecutive sequence at same slot // 若是是鏈表了 HashEntry<K,V> lastRun = e; int lastIdx = idx; // 新的位置只多是不便或者是老的位置+老的容量。 // 遍歷結束後,lastRun 後面的元素位置都是相同的 for (HashEntry<K,V> last = next; last != null; last = last.next) { int k = last.hash & sizeMask; if (k != lastIdx) { lastIdx = k; lastRun = last; } } // ,lastRun 後面的元素位置都是相同的,直接做爲鏈表賦值到新位置。 newTable[lastIdx] = lastRun; // Clone remaining nodes for (HashEntry<K,V> p = e; p != lastRun; p = p.next) { // 遍歷剩餘元素,頭插法到指定 k 位置。 V v = p.value; int h = p.hash; int k = h & sizeMask; HashEntry<K,V> n = newTable[k]; newTable[k] = new HashEntry<K,V>(h, p.key, v, n); } } } } // 頭插法插入新的節點 int nodeIndex = node.hash & sizeMask; // add the new node node.setNext(newTable[nodeIndex]); newTable[nodeIndex] = node; table = newTable; }
有些同窗可能會對最後的兩個 for 循環有疑惑,這裏第一個 for 是爲了尋找這樣一個節點,這個節點後面的全部 next 節點的新位置都是相同的。而後把這個做爲一個鏈表賦值到新位置。第二個 for 循環是爲了把剩餘的元素經過頭插法插入到指定位置鏈表。這樣實現的緣由多是基於機率統計,有深刻研究的同窗能夠發表下意見。
到這裏就很簡單了,get 方法只須要兩步便可。
public V get(Object key) { Segment<K,V> s; // manually integrate access methods to reduce overhead HashEntry<K,V>[] tab; int h = hash(key); long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE; // 計算獲得 key 的存放位置 if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null && (tab = s.table) != null) { for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE); e != null; e = e.next) { // 若是是鏈表,遍歷查找到相同 key 的 value。 K k; if ((k = e.key) == key || (e.hash == h && key.equals(k))) return e.value; } } return null; }
能夠發現 Java8 的 ConcurrentHashMap 相對於 Java7 來講變化比較大,再也不是以前的 Segment 數組 + HashEntry 數組 + 鏈表,而是 Node 數組 + 鏈表 / 紅黑樹。當衝突鏈表達到必定長度時,鏈表會轉換成紅黑樹。
/** * Initializes table, using the size recorded in sizeCtl. */ private final Node<K,V>[] initTable() { Node<K,V>[] tab; int sc; while ((tab = table) == null || tab.length == 0) { // 若是 sizeCtl < 0 ,說明另外的線程執行CAS 成功,正在進行初始化。 if ((sc = sizeCtl) < 0) // 讓出 CPU 使用權 Thread.yield(); // lost initialization race; just spin else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { try { if ((tab = table) == null || tab.length == 0) { int n = (sc > 0) ? sc : DEFAULT_CAPACITY; @SuppressWarnings("unchecked") Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n]; table = tab = nt; sc = n - (n >>> 2); } } finally { sizeCtl = sc; } break; } } return tab; }
從源碼中能夠發現 ConcurrentHashMap 的初始化是經過自旋和 CAS 操做完成的。裏面須要注意的是變量 sizeCtl
,它的值決定着當前的初始化狀態。
直接過一遍 put 源碼。
public V put(K key, V value) { return putVal(key, value, false); } /** Implementation for put and putIfAbsent */ final V putVal(K key, V value, boolean onlyIfAbsent) { // key 和 value 不能爲空 if (key == null || value == null) throw new NullPointerException(); int hash = spread(key.hashCode()); int binCount = 0; for (Node<K,V>[] tab = table;;) { // f = 目標位置元素 Node<K,V> f; int n, i, fh;// fh 後面存放目標位置的元素 hash 值 if (tab == null || (n = tab.length) == 0) // 數組桶爲空,初始化數組桶(自旋+CAS) tab = initTable(); else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { // 桶內爲空,CAS 放入,不加鎖,成功了就直接 break 跳出 if (casTabAt(tab, i, null,new Node<K,V>(hash, key, value, null))) break; // no lock when adding to empty bin } else if ((fh = f.hash) == MOVED) tab = helpTransfer(tab, f); else { V oldVal = null; // 使用 synchronized 加鎖加入節點 synchronized (f) { if (tabAt(tab, i) == f) { // 說明是鏈表 if (fh >= 0) { binCount = 1; // 循環加入新的或者覆蓋節點 for (Node<K,V> e = f;; ++binCount) { K ek; if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { oldVal = e.val; if (!onlyIfAbsent) e.val = value; break; } Node<K,V> pred = e; if ((e = e.next) == null) { pred.next = new Node<K,V>(hash, key, value, null); break; } } } else if (f instanceof TreeBin) { // 紅黑樹 Node<K,V> p; binCount = 2; if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) p.val = value; } } } } if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } addCount(1L, binCount); return null; }
hashcode == MOVED == -1
,則須要進行擴容。TREEIFY_THRESHOLD
則要轉換爲紅黑樹。get 流程比較簡單,直接過一遍源碼。
public V get(Object key) { Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek; // key 所在的 hash 位置 int h = spread(key.hashCode()); if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) { // 若是指定位置元素存在,頭結點hash值相同 if ((eh = e.hash) == h) { if ((ek = e.key) == key || (ek != null && key.equals(ek))) // key hash 值相等,key值相同,直接返回元素 value return e.val; } else if (eh < 0) // 頭結點hash值小於0,說明正在擴容或者是紅黑樹,find查找 return (p = e.find(h, key)) != null ? p.val : null; while ((e = e.next) != null) { // 是鏈表,遍歷查找 if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) return e.val; } } return null; }
總結一下 get 過程:
總結:
總的來講 ConcruuentHashMap 在 Java8 中相對於 Java7 來講變化仍是挺大的,
Java7 中 ConcruuentHashMap 使用的分段鎖,也就是每個 Segment 上同時只有一個線程能夠操做,每個 Segment 都是一個相似 HashMap 數組的結構,它能夠擴容,它的衝突會轉化爲鏈表。可是 Segment 的個數一但初始化就不能改變。
Java8 中的 ConcruuentHashMap 使用的 Synchronized 鎖加 CAS 的機制。結構也由 Java7 中的 Segment 數組 + HashEntry 數組 + 鏈表 進化成了 Node 數組 + 鏈表 / 紅黑樹,Node 是相似於一個 HashEntry 的結構。它的衝突再達到必定大小時會轉化成紅黑樹,在衝突小於必定數量時又退回鏈表。
有些同窗可能對 Synchronized 的性能存在疑問,其實 Synchronized 鎖自從引入鎖升級策略後,性能再也不是問題,有興趣的同窗能夠本身瞭解下 Synchronized 的鎖升級。
最後的話
文章已經收錄在 Github.com/niumoo/JavaNotes ,歡迎Star和指教。更有一線大廠面試點,Java程序員須要掌握的核心知識等文章,也整理了不少個人文字,歡迎 Star 和完善,但願咱們一塊兒變得優秀。
文章有幫助能夠點個「贊」或「分享」,都是支持,我都喜歡! 文章每週持續更新,要實時關注我更新的文章以及分享的乾貨,能夠關注「 未讀代碼 」公衆號