JDK1.7HashMap
HashMap数据结构
HashMap的数据结构是由数组+Entry实现的,而Entry是一个链表。
每一个数组存储的是一个Entry链表。
HashMap的存储方式
在HashMap的数据结构是由数组+Entry实现,如果一个Key,Value键值对插入的时候(在HashMap已经初始化的前提下),首先计算Key的hashCode值,根据hashCode值进行位运算取得素组的下标,然后将Key存储在对应的数组下标位置的链表中,当第二个Key,Value键值对插入的时候,会使用头差法,将第二个Key便变成table[i],而table[i]的next指向之前的Key,Value键值对。
Entry结构
/**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
HashMap的常量
- DEFAULT_INITAL_CAPACITY: HashMap的初始容量,如果没有设置HashMap的初始容量,那么默认为16
- MAXINUM_CAPACITY: HashMap存储容量的最大值
- DEFAULT_LOAD_FACTOR:加载因子
- threshold: 扩容阈值,同时也代表刚创建HashMap时的initalCapacity
- loadFacotr:扩容因子,与HashMap扩容有关,threshold = loadFactor * capacity
构造方法
HashMap(int)
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
this调用的是HashMap(int,float)
HashMap(int,float)
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);
}
如果初始容量<0则直接抛出异常,如果大于最大容量,则initalCapacity = MAXINUM_CAPACITY
如果loadFactor <= 0,并且 loadFactor != loadFactor则抛出异常
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);初始化成功
put
public V put(K key, V value) {
//当第一次调用put方法时才对table进行初始化
if (table == EMPTY_TABLE) {
//创建table
inflateTable(threshold);
}
//由此可见,jdk1.7版本下的HashMap支持Key为null的键值对
//如果要put元素的key为null,则直接将该元素存储到table[0]链表中
if (key == null)
return putForNullKey(value);
//根据key散列出hash值,里面使用了位运算
int hash = hash(key);
//根据hashCode和table.length使用位运算计算出数组的下标值,确保每一个数组下标都要被计算出来
int i = indexFor(hash, table.length);
//如果table[i]不等于null
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
// 如果 hashCode相等,并且key相等,或者key.equals(k)
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
// 记录e的value
V oldValue = e.value;
// value的替换
e.value = value;
e.recordAccess(this);
// 返回记录的value
return oldValue;
}
}
//方法执行到此处时,说明原链表中不存在与插入元素key相同的元素,那么,就需要创建一个Entry并插入
//向HashMap添加一个元素时,modCount需要自增
modCount++;
//添加Entry
addEntry(hash, key, value, i);
return null;
}
inflateTable()
//方法参数toSize就是HashMap初始容量
private void inflateTable(int toSize) {
// roundUpToPowerOf2是根据初始容量计算出一个值capacity,作为table的长度
// 该值满足:capacity >= toSize,并且capacity为2的整数次幂
int capacity = roundUpToPowerOf2(toSize);
// 重新计算扩容阈值:threshold = capacity * loadFactor
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
//创建数组
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
private static int roundUpToPowerOf2(int number) {
// 如果number>=MXINUM_CAPACITY,则返回MAX;否则,如果number>1则
// (number - 1) << 1 左移一位
return number >= MAXIMUM_CAPACITY
? MAXIMUM_CAPACITY
: (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
}
public static int highestOneBit(int i) {
//该方法是通过多次或运算,将i的低位全都变成1,最后再进行右移再相减,就只保留了最高位的1
//如:1001,经过五次或运算,变成1111,最后一步为1111 - 0111 = 1000
// 左移或运算
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
return i - (i >>> 1);
}
hash()
//HashMap中的hash算法要求算法散列性尽可能的高
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// 通过多次位运算,提高算法散列性
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
indexFor()
static int indexFor(int h, int length) {
/**
* 计算下标i,可以使用取模%操作,也可以使用按位&操作,但是计算机底层运算实际上还是2进制的位运
* 算,所以按位&操作效率会更高。
*
*
* 此处就可以解释Q1:为什么table的长度必须为2的整数次幂?
* 因为我们此处求下标i使用的是按位&操作,如果length - 1中某一位为0,
* 则该位上按位&操作必然为0,如:length为1011
* length - 1:1010,
* 则进行按位与操作时,数组上的有些位置将永远访问不到,造成空间的浪费,而且也增加了
* hash冲突的可能性。而如果length满足2的整数次幂,那么put操作时要插入的元素可以被散列到数组的所
* 有位置。
*/
return h & (length-1);
}
addEntry()
void addEntry(int hash, K key, V value, int bucketIndex) {
//jdk1.7版本HashMap的扩容条件:(size >= threshold) && (null != table[bucketIndex])
//扩容条件:1、当前HashMap中Entry个数 >= threshold 2、要插入位置的链表不为空
//jdk1.7和1.8中HashMap的扩容条件有一些差异,需要注意!!!
if ((size >= threshold) && (null != table[bucketIndex])) {
//扩容,新数组的长度为原数组的2倍
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
//扩容后需要重新计算index
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
resize()
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
//创建新数组
Entry[] newTable = new Entry[newCapacity];
//将原table中的元素转移到新table中
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
//重新计算扩容阈值
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
//转移元素
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;
}
}
}
createEntry()
// 头插法
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
扩容机制
void resize(int newCapacity) {
//把原哈希表数组赋值给oldTable
Entry[] oldTable = table;
//把原哈希表容量赋值给oldCapacity
int oldCapacity = oldTable.length;
//如果当前的哈希表容量已经达到允许的容量最大值(2的30次幂),则不再进行扩容
//且把当前哈希表的负载门槛设置为Integer的最大值。返回,跳过。
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
//创建一个新的哈希数组,容量为新传入的容量值
//该容量值必须是2的n次幂,且大于原数组容量大小
Entry[] newTable = new Entry[newCapacity];
//开始把原哈希表数组数据转入新创建的哈希表数组中
transfer(newTable, initHashSeedAsNeeded(newCapacity));
//转存完成后把新表内容放到HashMap的哈希表值中
table = newTable;
//设置当前容量下的负载门槛
//(新容量 * 负载因子)的值与(HashMap允许的最大容量(2的30次幂)+1) 进行比较,
//取值小的那一个
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
void transfer(Entry[] newTable, boolean rehash) {
//获取新哈希表的容量
int newCapacity = newTable.length;
//循环原哈希表
for (Entry<K,V> e : table) {
//循环原Entry线性链表
while(null != e) {
Entry<K,V> next = e.next;
//根据是否启用rehash判断是否为每一个key生成新的哈希值
//如果当前entry的key等于null,则重新设置当前entry的哈希值为0
//如果不为null,则对当前entyr的哈希值根据哈希干扰因子(HashSeed)进行重
//新计算赋值
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
//根据新的哈希值和新的容量计算该entry应该存放的数组下标位置
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
首先获取newTable的长度,然后循环旧的hashTable,拿到每一个Key,如果key不等于null,则先拿到他的下一个元素,把key的hash与newCapacity进行计算,得出新的下标位置,之后让e.next指向newTable的下标,把元素e给赋值到newTable下标位置,然后e=next,位移一位。
图解:
假设初始时数组长度2,key = 3, 7, 5 ,初始在表table[1]节点;3:然后resize后,hash数组长度为4
第一次循环,我们拿到的元素为3,经过计算数组下标,得出在newTable的3位置,将e.next指向newTable的位置,此时newTable[i]的位置为null,所以e.next = null。然后将e(3)h移动到newTbale的位置。然后e = next,此时next=7,相当于后移一位找到7.
第二次循环,拿到的元素为7,将e.next指向newTable的下标位置,此时newTable[i]的值为3,所以e.next = 3,
之后newTable[i] = e,将newTable[i]位置的引用指向7,然后e位移一位。
JDK1.7-Hashmap扩容死锁问题
JDK1.7HashMap中当两个线程同时操作HashMap扩容的时候,如果有一个线程挂起,而另一个线程顺利执,那么会造成循环链表的问题。
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];
//假设线程A在此处挂起,此时e.next = null;
newTable[i] = e;
e = next;
}
}
}
当A挂起后,线程B顺利执行完成
这个时候在JVM中的主存newTable[i]的指向的元素为7,而e(7).next指向的是3,e(3).next指向的是null。
而线程A当时执行完代码0后挂起,此时线程A中next = 7 , e = 3 ,e.next = null,然后执行代码 1和代码2
newTable[i] = e,此时的e=3,这个时候newTable[i]的值发生了改变
e = next ----> e = 7
e.next = newTable[i]; // 0
//假设线程A在此处挂起,此时e.next = null;
newTable[i] = e; // 1
e = next; // 2
然后进行第二次循环,e = 7。
Entry<K,V> next = e.next; // 3 从主存中取值
e.next = newTable[i]; // 7.next = 3 从主存中取值
newTable[i] = e; // 7
e = next; // 3
首先next = e.next从主存中取值为3(线程B操作的值),然后e.next = newTable[i],此时的newTable[i]的值等于3,因为刚才被唤醒的线程A将值替换了,所以e.next = 3。然后newTable[i] = 7这里有发生了一次值得替换。e = next = 3;
然后进入第三次循环,这个时候e的值等于3
next = 3.next , next = null;
e.next = newTable[i];此时newTable[i]的值等于7,所以3.next = 7
newTable[i] = e;此时e的值=3,所以newTable[i] = 3;
e = next,e = null;
此次循环后3.next = 7 ; 7.next = 3形成了环形链表