常量属性
/**
- The default initial capacity - MUST be a power of two.
- 默认初始容量大小
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
- MUST be a power of two <= 1<<30.
- hashMap最大容量,可装元素个数
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
- The load factor used when none specified in constructor.
- 加载因子,如容量为16,默认阈值即为16*0.75=12,元素个数超过(包含)12且,扩容
/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/* - 空数组,默认数组为空,初始化后才才有内存地址,第一次put元素时判断,延迟初始化
*/
static final Entry<?,?>[] EMPTY_TABLE = {};
2、存在的死循环问题
扩容导致的死循环,jdk1.7中在多线程高并发环境容易出死循环,导致cpu使用率过高问题,问题出在扩容方法resize()中,更具体内部的transfer方法:将旧数组元素转移到新数组过程中,源码如下:
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
//1.如果原来数组容量等于最大值了,2^30,设置扩容阈值为Integer最大值,不需要再扩容
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
//2.创建新数组对象
Entry[] newTable = new Entry[newCapacity];
//3.将旧数组元素转移到新数组中,分析一
transfer(newTable, initHashSeedAsNeeded(newCapacity));
//4.重新引用新数组对象和计算新的阈值
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
transfer方法
/**
- Transfers all entries from current table to newTable.
- 从当前数组中转移所有的节点到新数组中
*/
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
//遍历旧数组
for (Entry<K,V> e : table) {
//1,首先获取数组下标元素
while(null != e) {
//2.获取数组该桶位置链表中下一个元素
Entry<K,V> next = e.next;
//3.是否需要重新该元素key的hash值
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
//4,重新确定在