1. 程式人生 > >HashMap和ConcurrentHashMap

HashMap和ConcurrentHashMap

otherwise fab use row tno must head () greate

http://www.cnblogs.com/chengxiao/p/6059914.html

http://blog.csdn.net/zldeng19840111/article/details/6703104

http://www.importnew.com/26049.html

http://www.importnew.com/19685.html

HashMap

技術分享圖片

hashmap本質數組+鏈表+紅黑樹(鏈地址法,解決hash沖突問題)。根據key取得hash值,然後計算出數組下標,如果多個key對應到同一個下標,就用鏈表串起來,新插入的在前面。

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) //最多容納的Entry數,如果當前元素個數多於這個就要擴容

}

public V get(Object key) {

Node<K,V> e;

return (e = getNode(hash(key), key)) == null ? null : e.value;

}

final Node<K,V> getNode(int hash, Object key) {

  Node<K,V>[] tab; Node<K,V> 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<K,V>)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;

}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {

Node<K,V>[] tab; Node<K,V> p; int n, i;

if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; //擴充空表

   //&:兩個數都轉為二進制,然後從高位開始比較,如果兩個數都為1則為1,否則為0。取最小

if ((p = tab[i = (n - 1) & hash]) == null)  //p取hash鏈頭,並判斷是否已存在hash鏈

tab[i] = newNode(hash, key, value, null);   //賦值-新hash鏈

else {

   //存在hash鏈,hash鏈中key值不唯一

Node<K,V> e; K k;

if (p.hash == hash &&

((k = p.key) == key || (key != null && key.equals(k)))) //p同key

e = p; //取原值

else if (p instanceof TreeNode) //紅黑樹

e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

else {

for (int binCount = 0; ; ++binCount) {

if ((e = p.next) == null) { //從表鏈中取數據e:p的下一個;判斷是否有p以外(其他k)的Node

p.next = newNode(hash, key, value, null); //插入新值

if (binCount >= TREEIFY_THRESHOLD - 1) // 8-1

        treeifyBin(tab, hash);

/** TREEIFY_THRESHOLD
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/超過數量裝換list為tree

break;

}

if (e.hash == hash &&

((k = e.key) == key || (key != null && key.equals(k)))) //e同key

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;

/** modCount
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/fail-fast
機制是java集合(Collection)中的一種錯誤機制。當多個線程對同一個集合的內容進行操作時,就可能會產生fail-fast事件。
//if (modCount != expectedModCount) throw new ConcurrentModificationException();

  if (++size > threshold) resize();

  afterNodeInsertion(evict);

  return null;

}

HashMap是線程不安全的:在多線程的環境下,其他的元素也在同時進行put操作,如果hash值相同,可能出現同時在同一數組下用鏈表表示,造成閉環,導致在get時會出現死循環。

final Node<K,V>[] resize() {

Node<K,V>[] 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<K,V>[] newTab = (Node<K,V>[])new Node[newCap];

table = newTab;

if (oldTab != null) {

for (int j = 0; j < oldCap; ++j) {

Node<K,V> 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<K,V>)e).split(this, newTab, j, oldCap);

else { // preserve order

Node<K,V> loHead = null, loTail = null;

Node<K,V> hiHead = null, hiTail = null;

Node<K,V> 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;

}

HashMap和ConcurrentHashMap