table屬性即為分桶。
size屬性表示HashMap中存儲的Key-Value對兒的個數。
threshold為判斷是否需要進行擴容的門限值。
構造函數
- /**
- * Constructs an empty HashMap with the specified initial
- * capacity and load factor.
- *
- * @param initialCapacity the initial capacity
- * @param loadFactor the load factor
- * @throws IllegalArgumentException if the initial capacity is negative
- * or the load factor is nonpositive
- */
- public HashMap(int initialCapacity, float loadFactor) {
- if (initialCapacity < 0)
- throw new IllegalArgumentException("Illegal initial capacity: " +
- initialCapacity);
- if (initialCapacity > MAXIMUM_CAPACITY)
- initialCapacity = MAXIMUM_CAPACITY;
- if (loadFactor <= 0 || Float.isNaN(loadFactor))
- throw new IllegalArgumentException("Illegal load factor: " +
- loadFactor);
- this.loadFactor = loadFactor;
- this.threshold = tableSizeFor(initialCapacity);
- }
- /**
- * Constructs an empty HashMap with the specified initial
- * capacity and the default load factor (0.75).
- *
- * @param initialCapacity the initial capacity.
- * @throws IllegalArgumentException if the initial capacity is negative.
- */
- public HashMap(int initialCapacity) {
- this(initialCapacity, DEFAULT_LOAD_FACTOR);
- }
- /**
- * Constructs an empty HashMap with the default initial capacity
- * (16) and the default load factor (0.75).
- */
- public HashMap() {
- this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
- }
- /**
- * Constructs a new HashMap with the same mappings as the
- * specified Map. The HashMap is created with
- * default load factor (0.75) and an initial capacity sufficient to
- * hold the mappings in the specified Map.
- *
- * @param m the map whose mappings are to be placed in this map
- * @throws NullPointerException if the specified map is null
- */
- public HashMap(Map extends K, ? extends V> m) {
- this.loadFactor = DEFAULT_LOAD_FACTOR;
- putMapEntries(m, false);
- }
- /**
- * Implements Map.putAll and Map constructor
- *
- * @param m the map
- * @param evict false when initially constructing this map, else
- * true (relayed to method afterNodeInsertion).
- */
- final void putMapEntries(Map extends K, ? extends V> m, boolean evict) {
- int s = m.size();
- if (s > 0) {
- if (table == null) { // pre-size
- float ft = ((float)s / loadFactor) + 1.0F;
- int t = ((ft < (float)MAXIMUM_CAPACITY) ?
- (int)ft : MAXIMUM_CAPACITY);
- if (t > threshold)
- threshold = tableSizeFor(t);
- }
- else if (s > threshold)
- resize();
- for (Map.Entry extends K, ? extends V> e : m.entrySet()) {
- K key = e.getKey();
- V value = e.getValue();
- putVal(hash(key), key, value, false, evict);
- }
- }
- }
其中最為重要的就是根據傳入的initialCapacity計算threshold的方法,如下所示:
- /**
- * Returns a power of two size for the given target capacity.
- */
- static final int tableSizeFor(int cap) {
- int n = cap - 1;
- n |= n >>> 1;
- n |= n >>> 2;
- n |= n >>> 4;
- n |= n >>> 8;
- n |= n >>> 16;
- return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
- }
其功能在於計算得到大於等於initialCapacity的最小的2的正整數冪。
添加KV
添加KV方法算是HashMap中最為重要的幾個方法之一了。
先上源碼:
-
- /**
- * Associates the specified value with the specified key in this map.
- * If the map previously contained a mapping for the key, the old
- * value is replaced.
- *
- * @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 key, or
- * null if there was no mapping for key.
- * (A null return can also indicate that the map
- * previously associated null with key.)
- */
- public V put(K key, V value) {
- return putVal(hash(key), key, value, false, true);
- }
- static final int hash(Object key) {
- int h;
- return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
- }
- final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
- boolean evict) {
- Node
[] tab; Node p; int n, i; - if ((tab = table) == null || (n = tab.length) == 0)
- n = (tab = resize()).length;
- if ((p = tab[i = (n - 1) & hash]) == null)
- tab[i] = newNode(hash, key, value, null);
- else {
- Node
e; K k; - if (p.hash == hash &&
- ((k = p.key) == key || (key != null && key.equals(k))))
- e = p;
- else if (p instanceof TreeNode)
- e = ((TreeNode
)p).putTreeVal(this, tab, hash, key, value); - else {
- for (int binCount = 0; ; ++binCount) {
- if ((e = p.next) == null) {
- p.next = newNode(hash, key, value, null);
- if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
- treeifyBin(tab, hash);
- break;
- }
- if (e.hash == hash &&
- ((k = e.key) == key || (key != null && key.equals(k))))
- break;
- p = e;
- }
- }
- if (e != null) { // existing mapping for key
- V oldValue = e.value;
- if (!onlyIfAbsent || oldValue == null)
- e.value = value;
- afterNodeAccess(e);
- return oldValue;
- }
- }
- ++modCount;
- if (++size > threshold)
- resize();
- afterNodeInsertion(evict);
- return null;
- }
個人感覺該方法中的信息量還是比較大的,該方法在1.8版本中,在處理落入同一個分桶的數據時,較歷史版本有所更新。
之前版本中,對於該方法的處理是這樣的流程:
- 根據給出的key,計算hash值(key的hashCode方法),從而定位到分桶;
- 檢查定位到的分桶中是否已經存在了數據。如果沒有,則直接將數據放入分桶中;反之,則將數據加入分桶的鏈表中。
以上操作存在一個問題,那就是當分桶中數據比較多的時候,get方法需要在根據key的hash值定位到具體分桶後,還需要進行鏈表遍歷才能找到需要獲取到的value。假設鏈表長度為n,則時間複雜度為O(n),效率不夠理想。
有什麼辦法進行改進呢?對數據結構有所瞭解的同學們立刻就能反應到,相對於鏈表的遍歷,二叉樹的遍歷往往能夠減小時間複雜度。因此在JDK8中對此進行了功能增強,變為如下流程:
- 據給出的key,計算hash值(key的hashCode方法),從而定位到分桶,此步驟與改版前一致;
- 檢查分桶中是否有數據,如果沒有數據則直接將數據放入分桶中;反之,更精細化地進行處理。對於分桶中不太多數據的場景(個數小於TREEIFY_THRESHOLD-1)採用鏈表的方式,將新節點放到鏈表的尾部;對於分桶中較多數據的場景(個數大於等於TREEIFY_THRESHOLD-1),採用紅黑樹的方式,將節點進行存儲。這樣一來,既減輕了數據結構的複雜程度(紅黑樹較鏈表要複雜一些),又在鏈表較長的情況下,有效地減少了遍歷節點的時間複雜度。個人覺得,這算是JDK8中,對於解決此問題的很精巧的一點。
下面我們仔細地看一下這個方法的代碼。
首先,需要先根據key找到對應的分桶,所使用的方法是key.hashCode()右移16位,再與自身按位異或運算得到的hash值,再與分桶總數-1進行按位與操作。初看這個方法的時候,你一定很疑惑,取了hashCode之後為什麼還要如此複雜地右移16位,再與自身按位異或才能獲取到hash值。原因在於,hashCode方法返回的hash值並不夠完全隨機,為了更好地使得不同的key均勻地散落在不同的分桶中(換句話說,為了不同key的hash值分佈得更加均勻),在原有的調用hashCode方法的基礎上,又做了一次運算,將結果進一步地隨機化。之後邏輯上需要將計算得來的h值,按照分桶總數取模,這樣才能儘可能地保證均勻地分配到不同的分桶中。但是,計算機取模運算的效率不高,所以採用了與分桶總數-1進行按位與操作,也能達到同樣的效果。
接下來,根據分桶中已有的數據的情況來判斷如何將輸入的Key-Value存儲到分桶中。如果分桶中沒有數據,那麼就將輸入的Key-Value轉化成存儲節點Node,存儲到分桶中;如果分桶中有數據,且已採用紅黑樹進行存儲了,則將該存儲節點插入到紅黑樹中,以優化後續查找性能;如果分桶中的數據依然是使用鏈表進行存儲,則存儲到鏈表的尾部,之後判斷是否達到樹化條件(鏈表中存儲的數據個數大於等於TREEIFY_THRESHOLD-1),達到的話就將鏈表轉成紅黑樹存儲。具體的插入紅黑樹的代碼就不再這裡贅述了,感興趣的同學可在參照紅黑樹的介紹文章:https://baike.baidu.com/item/%E7%BA%A2%E9%BB%91%E6%A0%91。
最後,在插入節點之後,判斷是否要進行擴容(resize),擴容的條件是加入新節點後,存儲的Key-Value的個數大於threshold(threshold的賦值參見構造函數中,為大於等於initialCapacity的最小的2的正整數冪)。擴容的具體操作步驟如下:
- /**
- * Initializes or doubles table size. If null, allocates in
- * accord with initial capacity target held in field threshold.
- * Otherwise, because we are using power-of-two expansion, the
- * elements from each bin must either stay at same index, or move
- * with a power of two offset in the new table.
- *
- * @return the table
- */
- final Node
[] resize() { - Node
[] oldTab = table; - int oldCap = (oldTab == null) ? 0 : oldTab.length;
- int oldThr = threshold;
- int newCap, newThr = 0;
- if (oldCap > 0) {
- if (oldCap >= MAXIMUM_CAPACITY) {
- threshold = Integer.MAX_VALUE;
- return oldTab;
- }
- else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
- oldCap >= DEFAULT_INITIAL_CAPACITY)
- newThr = oldThr << 1; // double threshold
- }
- else if (oldThr > 0) // initial capacity was placed in threshold
- newCap = oldThr;
- else { // zero initial threshold signifies using defaults
- newCap = DEFAULT_INITIAL_CAPACITY;
- newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
- }
- if (newThr == 0) {
- float ft = (float)newCap * loadFactor;
- newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
- (int)ft : Integer.MAX_VALUE);
- }
- threshold = newThr;
- @SuppressWarnings({"rawtypes","unchecked"})
- Node
[] newTab = (Node [])new Node[newCap]; - table = newTab;
- if (oldTab != null) {
- for (int j = 0; j < oldCap; ++j) {
- Node
e; - if ((e = oldTab[j]) != null) {
- oldTab[j] = null;
- if (e.next == null)
- newTab[e.hash & (newCap - 1)] = e;
- else if (e instanceof TreeNode)
- ((TreeNode
)e).split(this, newTab, j, oldCap); - else { // preserve order
- Node
loHead = null, loTail = null; - Node
hiHead = null, hiTail = null; - Node
next; - do {
- next = e.next;
- if ((e.hash & oldCap) == 0) {
- if (loTail == null)
- loHead = e;
- else
- loTail.next = e;
- loTail = e;
- }
- else {
- if (hiTail == null)
- hiHead = e;
- else
- hiTail.next = e;
- hiTail = e;
- }
- } while ((e = next) != null);
- if (loTail != null) {
- loTail.next = null;
- newTab[j] = loHead;
- }
- if (hiTail != null) {
- hiTail.next = null;
- newTab[j + oldCap] = hiHead;
- }
- }
- }
- }
- }
- return newTab;
- }
首先計算得到擴充後的threshold和capacity,然後將擴容前的各分桶中的數據按照新分桶的定位計算方法,定位到新分桶中,然後依次進行遷移。注意代碼中涉及到的HashMap中的table屬性在多線程操作時是臨界資源,因此HashMap不是線程安全的,需要在代碼中做線程安全保護。此外,我們觀察到HashMap的resize方法,需要進行新分桶的threshold/capacity重新計算,舊數據按照新分桶進行重新定位,舊分桶中的數據按新規則向新分桶中遷移,這裡邊的開銷還是比較大的,因此比較建議在創建HashMap實例的時候,儘可能地根據業務需求對HashMap的capacity進行一個預估,避免HashMap在程序運行過程中頻繁進行擴容計算,提升性能。
根據Key獲取Value
在瞭解了Key-Value的插入方法之後,再瞭解如何根據Key獲取Value就會簡單許多。get方法代碼如下:
- /**
- * Returns the value to which the specified key is mapped,
- * or {@code null} if this map contains no mapping for the key.
- *
- *
More formally, if this map contains a mapping from a key
- * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
- * key.equals(k))}, then this method returns {@code v}; otherwise
- * it returns {@code null}. (There can be at most one such mapping.)
- *
- *
A return value of {@code null} does not necessarily
- * indicate that the map contains no mapping for the key; it's also
- * possible that the map explicitly maps the key to {@code null}.
- * The {@link #containsKey containsKey} operation may be used to
- * distinguish these two cases.
- *
- * @see #put(Object, Object)
- */
- public V get(Object key) {
- Node
e; - return (e = getNode(hash(key), key)) == null ? null : e.value;
- }
- /**
- * Implements Map.get and related methods
- *
- * @param hash hash for key
- * @param key the key
- * @return the node, or null if none
- */
- final Node
getNode(int hash, Object key) { - Node
[] tab; Node first, e; int n; K k; - if ((tab = table) != null && (n = tab.length) > 0 &&
- (first = tab[(n - 1) & hash]) != null) {
- if (first.hash == hash && // always check first node
- ((k = first.key) == key || (key != null && key.equals(k))))
- return first;
- if ((e = first.next) != null) {
- if (first instanceof TreeNode)
- return ((TreeNode
)first).getTreeNode(hash, key); - do {
- if (e.hash == hash &&
- ((k = e.key) == key || (key != null && key.equals(k))))
- return e;
- } while ((e = e.next) != null);
- }
- }
- return null;
- }
整體步驟分為以下幾步:
- 按照put方法中描述的規則,根據key定位到分桶;
- 將key與分桶中第一個節點的key做equals比較,如果相等則返回;不相等則考慮與後續節點進行比對。分兩種情況,如果分桶中存儲的是紅黑樹,則做樹的遍歷查找;如果存儲的是鏈表,則做鏈表的遍歷查找。如果遍歷結束依然沒有找到,則返回null。
根據Key刪除
remove方法的操作步驟如下:
- /**
- * Removes the mapping for the specified key from this map if present.
- *
- * @param key key whose mapping is to be removed from the map
- * @return the previous value associated with key, or
- * null if there was no mapping for key.
- * (A null return can also indicate that the map
- * previously associated null with key.)
- */
- public V remove(Object key) {
- Node
e; - return (e = removeNode(hash(key), key, null, false, true)) == null ?
- null : e.value;
- }
- /**
- * Implements Map.remove and related methods
- *
- * @param hash hash for key
- * @param key the key
- * @param value the value to match if matchValue, else ignored
- * @param matchValue if true only remove if value is equal
- * @param movable if false do not move other nodes while removing
- * @return the node, or null if none
- */
- final Node
removeNode(int hash, Object key, Object value, - boolean matchValue, boolean movable) {
- Node
[] tab; Node p; int n, index; - if ((tab = table) != null && (n = tab.length) > 0 &&
- (p = tab[index = (n - 1) & hash]) != null) {
- Node
node = null, e; K k; V v; - if (p.hash == hash &&
- ((k = p.key) == key || (key != null && key.equals(k))))
- node = p;
- else if ((e = p.next) != null) {
- if (p instanceof TreeNode)
- node = ((TreeNode
)p).getTreeNode(hash, key); - else {
- do {
- if (e.hash == hash &&
- ((k = e.key) == key ||
- (key != null && key.equals(k)))) {
- node = e;
- break;
- }
- p = e;
- } while ((e = e.next) != null);
- }
- }
- if (node != null && (!matchValue || (v = node.value) == value ||
- (value != null && value.equals(v)))) {
- if (node instanceof TreeNode)
- ((TreeNode
)node).removeTreeNode(this, tab, movable); - else if (node == p)
- tab[index] = node.next;
- else
- p.next = node.next;
- ++modCount;
- --size;
- afterNodeRemoval(node);
- return node;
- }
- }
- return null;
- }
- 根據key定位到分桶;
- 從分桶中找到要刪除的節點;
- 刪除節點,並將size-1。
ConcurrentHashMap
ConcurrentHashMap是線程安全的HashMap,在JDK8中,ConcurrentHashMap為進一步優化多線程下的併發性能,不再採用分段鎖對分桶進行保護,而是採用CAS操作(Compare And Set)。這個改變在思想上很像是樂觀鎖與悲觀鎖。
在JDK8之前,ConcurrentHashMap採用分段鎖的方式來保證線程安全性,相對於CAS操作,量級更重一些,因為需要做加鎖、解鎖操作。這很類似於悲觀鎖的思想,即假設多線程併發操作臨界資源的幾率比較大,因此採用加鎖的方式來應對。
JDK8中,採用了輕量級的CAS操作來獲取及向分桶中寫入元素(當分桶中沒有元素存儲時),採用類似LongAdder的方式計算ConcurrentHashMap的size,使得多線程操作時,採用更輕量級的方式加以應對。CAS很類似於樂觀鎖的思想,而LongAdder是將多線程的+1操作隨機地定位到不同分桶中來避免寫入時的衝突,在計算size時,通過將各分桶中的數值進行疊加從而得到總的size值,從而很好地解決了多線程+1寫操作的衝突和加鎖等待問題。
構造函數
與HashMap相類似,ConcurrentHashMap的構造函數也分為以下幾個:
- 默認構造函數:空實現;
- 給定initialCapacity的構造函數;
- 拷貝構造函數。
這裡我們關注以下給定initialCapacity的構造函數,之所以關注這個構造函數,是因為HashMap與ConcurrentHashMap的reSize擴容過程都屬於開銷比較大的操作,所以期望使用者在使用的時候儘可能地根據業務需求對size有一個大致的預估,並使用該構造函數對Map進行構造,以避免後續不斷地擴容操作,給性能帶來不利的影響。
我們都還記得上文中提到的HashMap的size計算,其值等於大於等於initialCapacity的最小的2的正整數冪。而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;
- }
從中不難看出,ConcurrentHashMap的sizeCtl值大於等於1.5倍的initialCapacity+1的最小2的正整數冪。
而拷貝構造函數的思路則是遍歷入參中的Map,然後依次將其put到本次創建的ConcurrentHashMap中,put方法的操作過程我會在下邊加以詳細介紹,所以此處不再贅述。
添加KV
put方法與HashMap的put方法在基本思路上是一致的,主要分以下步驟:
- 對傳入的key計算hashCode,然後計算獲取到index,即指向哪個分桶;
- 訪問到指定的分桶,如果分桶中此時沒有節點,則將KV做插入處理;如果分桶中已經有節點了,則判斷是樹節點還是鏈表節點,然後根據樹或是鏈表進行遍歷。如果該Key已經存儲到了Map中了,則將新值寫入,舊值返回;反之,則創建新節點,存儲到樹的合適位置,或者是鏈表的尾節點(當然還會根據鏈表中存儲的節點數來判斷是否應該進行樹化處理);
- 將size自增1,並判斷是否需要進行reSize擴容操作,是則進行擴容,即生成新的分桶,將舊有分桶中的節點根據新的規則拷貝並創建到新的分桶中。
只不過ConcurrentHashMap為了保證其是線程安全的,因此採用了一系列的手段來保證這一點。
- /**
- * Maps the specified key to the specified value in this table.
- * Neither the key nor the value can be null.
- *
- *
The value can be retrieved by calling the {@code get} 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 {@code key}, or
- * {@code null} if there was no mapping for {@code key}
- * @throws NullPointerException if the specified key or value is null
- */
- 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) {
- if (key == null || value == null) throw new NullPointerException();
- int hash = spread(key.hashCode());
- int binCount = 0;
- for (Node
[] tab = table;;) { - Node
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
(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
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
pred = e; - if ((e = e.next) == null) {
- pred.next = new Node
(hash, key, - value, null);
- break;
- }
- }
- }
- else if (f instanceof TreeBin) {
- Node
p; - binCount = 2;
- if ((p = ((TreeBin
)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;
- }
關注其中在獲取分桶中節點的tabAt方法,和向分桶中添加節點的casTabAt方法,二者在底層都使用到了sun.misc.Unsafe。關於Unsafe,可參考文章:https://blog.csdn.net/anla_/article/details/78631026。簡單說就是,Unsafe提供了硬件級別的原子操作。藉助於Unsafe類,tabAt方法能夠獲取到分桶中的節點,casTabAt方法能夠採用CAS的方式將新節點寫入到分桶中,即如果分桶中如果當前存儲的節點與剛才使用tabAt方法獲取到的相同,則將新節點覆蓋之前的節點;反之,則說明在當前線程設置之前,其他線程已經改變了分桶中的節點,因此本線程的設置操作失敗。
如果CAS操作失敗了,則進入到下邊的分支,首先check是否該節點在遷移中(遷移中的節點的hash值為-1,有可能是在reSize擴容中),如果不在遷移過程中,則採用synchronized關鍵字,對tabAt獲取到的節點加鎖,然後像上文中陳述的步驟2那樣完成新KV的寫入操作。
最後一步則是將ConcurrentHashMap的size+1,並根據已存儲的節點的個數判斷是否要進行reSize擴容操作。為了滿足線程安全性,並儘可能地提升size+1的性能,ConcurrentHashMap採用的是類似於LongAdder的方式來完成size+1這個操作的。可參考文章:https://www.cnblogs.com/ten951/p/6590596.html。LongAdder的思想本質上就是將多線程操作同一個變量(將同一個size做+1操作),轉變為多線程隨機向一組cell做寫入,通過將各cell中的value累加,即可得到總的值,雖然這個值可能不準。這樣即可由多線程集中寫,轉變為多線程分散寫,有效地減輕了多線程操作時的競爭。
根據Key獲取Value
在瞭解了put方法之後,再去看get方法就會明晰很多。
- /**
- * Returns the value to which the specified key is mapped,
- * or {@code null} if this map contains no mapping for the key.
- *
- *
More formally, if this map contains a mapping from a key
- * {@code k} to a value {@code v} such that {@code key.equals(k)},
- * then this method returns {@code v}; otherwise it returns
- * {@code null}. (There can be at most one such mapping.)
- *
- * @throws NullPointerException if the specified key is null
- */
- public V get(Object key) {
- Node
[] tab; Node e, p; int n, eh; K ek; - int h = spread(key.hashCode());
- 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;
- }
從代碼中不難看出,ConcurrentHashMap的get方法與HashMap的get方法的大致思路是一致的。
按Key刪除
remove方法的源碼如下:
- /**
- * Removes the key (and its corresponding value) from this map.
- * This method does nothing if the key is not in the map.
- *
- * @param key the key that needs to be removed
- * @return the previous value associated with {@code key}, or
- * {@code null} if there was no mapping for {@code key}
- * @throws NullPointerException if the specified key is null
- */
- public V remove(Object key) {
- return replaceNode(key, null, null);
- }
- /**
- * Implementation for the four public remove/replace methods:
- * Replaces node value with v, conditional upon match of cv if
- * non-null. If resulting value is null, delete.
- */
- final V replaceNode(Object key, V value, Object cv) {
- int hash = spread(key.hashCode());
- for (Node
[] tab = table;;) { - Node
f; int n, i, fh; - if (tab == null || (n = tab.length) == 0 ||
- (f = tabAt(tab, i = (n - 1) & hash)) == null)
- break;
- else if ((fh = f.hash) == MOVED)
- tab = helpTransfer(tab, f);
- else {
- V oldVal = null;
- boolean validated = false;
- synchronized (f) {
- if (tabAt(tab, i) == f) {
- if (fh >= 0) {
- validated = true;
- for (Node
e = f, pred = null;;) { - K ek;
- if (e.hash == hash &&
- ((ek = e.key) == key ||
- (ek != null && key.equals(ek)))) {
- V ev = e.val;
- if (cv == null || cv == ev ||
- (ev != null && cv.equals(ev))) {
- oldVal = ev;
- if (value != null)
- e.val = value;
- else if (pred != null)
- pred.next = e.next;
- else
- setTabAt(tab, i, e.next);
- }
- break;
- }
- pred = e;
- if ((e = e.next) == null)
- break;
- }
- }
- else if (f instanceof TreeBin) {
- validated = true;
- TreeBin
t = (TreeBin )f; - TreeNode
r, p; - if ((r = t.root) != null &&
- (p = r.findTreeNode(hash, key, null)) != null) {
- V pv = p.val;
- if (cv == null || cv == pv ||
- (pv != null && cv.equals(pv))) {
- oldVal = pv;
- if (value != null)
- p.val = value;
- else if (t.removeTreeNode(p))
- setTabAt(tab, i, untreeify(t.first));
- }
- }
- }
- }
- }
- if (validated) {
- if (oldVal != null) {
- if (value == null)
- addCount(-1L, -1);
- return oldVal;
- }
- break;
- }
- }
- }
- return null;
- }
從中不難看出,其操作流程與put方法極為類似。
- 通過key計算hashCode,繼而計算index;
- 根據index,定位到具體的分桶,如果分桶中沒有數據,返回,說明要刪除的key並不存在;
- 如果定位到的分桶中的節點的hash值為-1,則說明節點在遷移過程中,則helpTransfer;
- 2,3都不滿足,則通過synchronized鎖住節點,根據該分桶中存儲的節點是採用紅黑樹進行存儲還是鏈表進行存儲,進行相應的刪除處理操作。
Set
Set與List的區別在於,Set中存儲的元素是經過了去重的(即如果a.equals(b),則Set中只可能存在一個)。
Set的典型實現是HashSet,其主要方法add,remove,contains,均是通過內置的HashMap來進行實現的。
比如add方法,本質上是調用了HashMap的put方法,以傳入的object為Key,並以dummy value(private static final Object PRESENT = new Object();)為Value。
remove方法,也是在內部調用了HashMap的remove方法,將傳入的object作為key,從而對HashSet中保存的object進行刪除。
如果大家喜歡這篇文章的話,希望大家能夠收藏,轉發 謝謝!更多相關資訊可以關注西安華美校區,免費獲得java零基礎教程!額外附送excel教程!
閱讀更多 西安北大青鳥華美教育 的文章