jdk1.7中的HashMap
在jdk1.8中对HashMap做了很多优化,这里先分析在jdk1.7中的问题,相信大家都知道在jdk1.7多线程环境下HashMap容易出现死循环,这里我们先用代码来模拟出现死循环的情况:

public class HashMapTest {

public static void main(String[] Fargs) {
    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 map = new HashMap<>();

@Override
public void run() {
    while (ai.get() < 1000000) {
        map.put(ai.get(), ai.get());
        ai.incrementAndGet();
    }
}

}
从堆栈信息中可以看到出现死循环的位置,通过该信息可明确知道死循环发生在HashMap的扩容函数中,根源在transfer函数中,jdk1.7中HashMap的transfer函数如下:

void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry e : table) {
while(null != e) {
Entry 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;
}
}
}

亚马逊测评 www.yisuping.com