這個版本ConcurrentHashMap難度提升了很多,就簡單的談一下常用的方法就好了,可能有些講的不太清楚,麻煩發現的大佬指正一下
主要數據結構
1.8將Segment取消了,保留了table數組的形式,但是不在以HashEntry純鏈表的形式儲存數據了,采用了鏈表+紅黑樹的形式儲存數據;在使用get()方法時,使用純鏈表的時間復雜度時O(n),而在使用紅黑樹的數據結構時,時間復雜度為O(logn),在查詢的速度上有很大的提升;但是在創建的時候并非直接使用紅黑樹儲存數據,而是依舊采用鏈表存儲,但是但鏈表的長度超過8的時候就會轉換成紅黑樹數據結構。
Node
依舊還是跟HashEntry的數據結構一致,采用鏈表的數據結構存儲
static class Node<K,V> implements Map.Entry<K,V> {final int hash;final K key;volatile V val;volatile Node<K,V> next;Node(int hash, K key, V val, Node<K,V> next) {this.hash = hash;this.key = key;this.val = val;this.next = next;}//.....}
TreeNode
紅黑樹的數據結構原型,繼承了Node
/*** Nodes for use in TreeBins*/static final class TreeNode<K,V> extends Node<K,V> {TreeNode<K,V> parent; // red-black tree linksTreeNode<K,V> left;TreeNode<K,V> right;TreeNode<K,V> prev; // needed to unlink next upon deletionboolean red;TreeNode(int hash, K key, V val, Node<K,V> next,TreeNode<K,V> parent) {super(hash, key, val, next);this.parent = parent;}Node<K,V> find(int h, Object k) {return findTreeNode(h, k, null);}//......}
TreeBin
table數組中儲存的就是TreeBin對象,存儲了TreeNode<K,V>的根節點
static final class TreeBin<K,V> extends Node<K,V> {TreeNode<K,V> root;volatile TreeNode<K,V> first;volatile Thread waiter;volatile int lockState;// values for lockStatestatic final int WRITER = 1; // set while holding write lockstatic final int WAITER = 2; // set when waiting for write lockstatic final int READER = 4; // increment value for setting read lock//...}
構造方法
在構造方法中,并沒有做什么操作,僅僅是設置了一個屬性值sizeCtl(也是容器的控制器)
sizeCtl:
負數:表示進行初始化或者擴容,-1表示正在初始化,-N,表示有N-1個線程正在進行擴容。
正數:0 表示還沒有被初始化,>0的數,初始化或者是下一次進行擴容的閾值。
而實際的初始化是在put()方法中加載table數組
/*** The array of bins. Lazily initialized upon first insertion.* Size is always a power of two. Accessed directly by iterators.*/transient volatile Node<K,V>[] table;/*** Table initialization and resizing control. When negative, the* table is being initialized or resized: -1 for initialization,* else -(1 + the number of active resizing threads). Otherwise,* when table is null, holds the initial table size to use upon* creation, or 0 for default. After initialization, holds the* next element count value upon which to resize the table.*/private transient volatile int sizeCtl; /*** Creates a new, empty map with the default initial table size (16).*/public ConcurrentHashMap() {}/*** Creates a new, empty map with an initial table size* accommodating the specified number of elements without the need* to dynamically resize.** @param initialCapacity The implementation performs internal* sizing to accommodate this many elements.* @throws IllegalArgumentException if the initial capacity of* elements is negative*/public ConcurrentHashMap(int initialCapacity) {if (initialCapacity < 0)throw new IllegalArgumentException();int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?MAXIMUM_CAPACITY :tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));this.sizeCtl = cap;}
put()方法
具體調用了putVal(),依舊還是和putIfAbsent()調用的是同一個方法,ConcurrentHashMap容器初始化實在put()方法中加載的即initTable();方法;
這個版本計算hash值的方法為spread(object.hashCode()),在創建完table數組之后,接下來就是創建數組中的Node節點了,會判斷當前是鏈表還是紅黑樹,然后將數據插入到對應的鏈表或樹中,鏈表插入一個數據binCount就會自增,然后當這個值大于一個閾值時就會進入到鏈表轉紅黑樹方法treeifyBin。
/*** Initializes table, using the size recorded in sizeCtl.*/
//采用了CAS設置了sizeCtl的值private final Node<K,V>[] initTable() {Node<K,V>[] tab; int sc;while ((tab = table) == null || tab.length == 0) {if ((sc = sizeCtl) < 0)Thread.yield(); // lost initialization race; just spinelse if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {try {if ((tab = table) == null || tab.length == 0) {int n = (sc > 0) ? sc : DEFAULT_CAPACITY;@SuppressWarnings("unchecked")//創建table數組Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];table = tab = nt;//sc = 0.75n,即擴容因子還是0.75sc = n - (n >>> 2);}} finally {sizeCtl = sc;}break;}}return tab;}//計算key的hash值,與1.7相比,更加均勻static final int spread(int h) {return (h ^ (h >>> 16)) & HASH_BITS;}
/** Implementation for put and putIfAbsent */final V putVal(K key, V value, boolean onlyIfAbsent) {if (key == null || value == null) throw new NullPointerException();int hash = spread(key.hashCode());int binCount = 0;for (Node<K,V>[] tab = table;;) {Node<K,V> f; int n, i, fh;if (tab == null || (n = tab.length) == 0)tab = initTable();else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {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 (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;}/*** Replaces all linked nodes in bin at given index unless table is* too small, in which case resizes instead.*///將Node<>[]中的鏈表換成紅黑樹的TreeBinprivate final void treeifyBin(Node<K,V>[] tab, int index) {Node<K,V> b; int n, sc;if (tab != null) {if ((n = tab.length) < MIN_TREEIFY_CAPACITY)tryPresize(n << 1);else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {synchronized (b) {if (tabAt(tab, index) == b) {TreeNode<K,V> hd = null, tl = null;for (Node<K,V> e = b; e != null; e = e.next) {TreeNode<K,V> p =new TreeNode<K,V>(e.hash, e.key, e.val,null, null);if ((p.prev = tl) == null)hd = p;elsetl.next = p;tl = p;}setTabAt(tab, index, new TreeBin<K,V>(hd));}}}}}
在put()的時候有個擴容的方法helpTransfer(tab, f);?
/*** Helps transfer if a resize is in progress.*/final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {Node<K,V>[] nextTab; int sc;if (tab != null && (f instanceof ForwardingNode) &&(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {int rs = resizeStamp(tab.length);while (nextTab == nextTable && table == tab &&(sc = sizeCtl) < 0) {if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||sc == rs + MAX_RESIZERS || transferIndex <= 0)break;if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {//擴容table數組transfer(tab, nextTab);break;}}return nextTab;}return table;}
get()
首先獲取到key值的hash值,然后去定位是數組中的哪個Node節點,然后去遍歷鏈表或者紅黑樹查找;
public V get(Object key) {Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;int h = spread(key.hashCode());//獲取key的對應的hash值if ((tab = table) != null && (n = tab.length) > 0 &&(e = tabAt(tab, (n - 1) & h)) != null) {if ((eh = e.hash) == h) {//判斷是否為當前數組元素if ((ek = e.key) == key || (ek != null && key.equals(ek)))return e.val;}//從鏈表中獲取數據else if (eh < 0)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;}
結語:這玩意難度有點高啊,想要真正的看懂還需努力!