public class HashMapTest { public static void main(String[] args) { HashMapThread thread0 = new HashMapThread(); HashMapThread thread1 = new HashMapThread(); HashMapThread thread2 = new HashMapThread(); HashMapThread thread3 = new HashMapThread(); HashMapThread thread4 = new HashMapThread(); thread0.start(); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } } class HashMapThread extends Thread { private static AtomicInteger ai = new AtomicInteger(); private static Map<Integer, Integer> map = new HashMap<>(); @Override public void run() { while (ai.get() < 1000000) { map.put(ai.get(), ai.get()); ai.incrementAndGet(); } } }
void transfer(Entry[] newTable, boolean rehash) { int newCapacity = newTable.length; for (Entry<K,V> e : table) { while(null != e) { Entry<K,V> next = e.next; if (rehash) { e.hash = null == e.key ? 0 : hash(e.key); } int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } } }
newTable[3]=e ----> newTable[3]=3 e=next ----> e=7
e=7 next=e.next ----> next=3【从主存中取值】 e.next=newTable[3] ----> e.next=3【从主存中取值】 newTable[3]=e ----> newTable[3]=7 e=next ----> e=3
e=3 next=e.next ----> next=null e.next=newTable[3] ----> e.next=7 即:3.next=7 newTable[3]=e ----> newTable[3]=3 e=next ----> e=null
e=5 next=e.next ----> next=null,从主存中取值 e.next=newTable[1] ----> e.next=5,从主存中取值 newTable[1]=e ----> newTable[1]=5 e=next ----> e=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; if ((p = tab[i = (n - 1) & hash]) == null) // 如果没有hash碰撞则直接插入元素 tab[i] = newNode(hash, key, value, null); else { Node<K,V> 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<K,V>)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; }