为什么hashMap不仅仅用数组一种数据结构?
因为数组虽然查询的时间复杂度为O1,但是数组有个缺陷就是不能动态改变大小,一旦超出数组长度,就需要创建一个新的数组,数组默认长度是16
链表是怎么插入的?
java1.7采用头部插入法,后来的数据插入链表的头部,而1.8采用的时尾部插入法
红黑树
hashMap在扩容的时候遇到的问题?
在并发情况下,每个线程都同时申请扩容hashMap,这就造成声明多个数组,会导致内存溢出和频繁gc
hashMap 1.7为什么会出现死锁?
/**
* Transfers all entries from current table to newTable.
*/
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
//Step1 : 首先便利索引数组中的元素,Entry<K,V> e 存储了链表的入口元素
for (Entry<K,V> e : table) {
//Step2: 对链表上的每一个元素进行遍历,从Hash表的头部第一个元素开始
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;
}
}
}
可以看到转移过程是逆序的,转移前链表顺序是1->2->3,逆序转移后新的t顺序变成 3->2->1。现在就应该才得八九不离十了,是不是有可能在转移的过程中 出现1>2>3>1这种情况,形成一个头尾相连的链表。
ConcurrentHashMap是如何解决线程安全的?
当put一个值是,首先通过CAS判断该数组索引位置是否为空?如果为空则直接插入,如果不为空则通过加锁插入到链表中,锁的颗粒度相对于hashTable要小,而且concurrentHashMap是不允许key和value为null
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
}
//MOVED是表示正在扩容,这个状态如果存在,则其它线程会优先帮助其扩容
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;
}