「这是我参与11月更文挑战的第11天,活动详情查看:2021最后一次更文挑战」
HashMap
摘要
HashMap是Map中常见的一种,也是Collection中的重要成员,底层基于数组+链表组成,在1.7和1.8中具体实现略有不同
Base1.7
数据结构图
实现
其中几个主要的参数
- 初始化桶大小,因为底层是数组,所以这是数组默认的大小。
- 桶最大值。
- 默认的负载因子(0.75)
table
真正存放数据的数组。
Map
存放数量的大小。- 桶大小,可在初始化时显式指定。
- 负载因子,可在初始化时显式指定。
负载因子:由于初始化的HashMap的容量是固定,如:
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
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;
threshold = initialCapacity;
init();
}
给定的默认容量是16,负载因子是0.75,HashMap在使用过程中添加元素,当数量达到0.75 * 16 = 12时,就需要将当前容量为16的HashMap扩容,这个过程中涉及到 复制操作、refresh等,会消耗性能,所有建议在初始化时给定大小 ,减少由于扩容带来的性能损耗。
根据代码可以看到其实真正存放数据的是
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
Entry是HashMap中的一个内部类,从成员变量可以看出:
- key就是写入时的键
- value是写入的值
- HashMap是由数组和离那边组成,next用于实现链表结构
- hash是存放当前key的hashCode
put方法
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
- 判断数组是否为空,为空则初始化
- 判断key是否为空
- 计算出key的hashCode
- 找到hashCode在位置
- 遍历链表,查找是否已经存在key相同的值,若存在则覆盖,并返回原值
- 操作数+1
- 如果未找到,新增一个Entry
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
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++;
}
当调用addEntry写入Entry时,需要判断是否需要扩容
若需要扩容,则进行两倍扩充,并将当前的可以重新hash并并定位,而createEntry会将当前的数据复制到新数组中。
get方法
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
- 根据key计算hashCode,定位到数组位置
- 遍历链表,通过key的equals方法对比插找对应的记录
Base1.8
当hash冲突时,在数组的同一位置上的链表会变长,这样的查询效率会越来越低,1.8针对此问题进行了优化
结构图
其中几个主要的成员变量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
transient Node<K,V>[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* The number of key-value mappings contained in this map.
*/
其中与1.7的区别:
TREEIFY_THRESHOLD:将链表转行为红黑树的阈值
Entry改为Node,与Entry相同
put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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))))//hash冲突,覆盖值
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;
}
get方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {//选择对应的方式获取匹配值
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
遍历方式
Iterator<Map.Entry<String, Integer>> entryIterator = map.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<String, Integer> next = entryIterator.next();
System.out.println("key=" + next.getKey() + " value=" + next.getValue());
}
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()){
String key = iterator.next();
System.out.println("key=" + key + " value=" + map.get(key));
}
建议使用第一种方式,第二种需要通过key获取value,效率略低
ConcurrentHashMap
ConcurrentHashMap 同样也分为 1.7 、1.8 版,两者在实现上略有不同
Base1.7
结构图
由Segment数组和hashEntry组成,和HashMap一样,仍然采用数组+链表
核心成员变量
/**
* Segment 数组,存放数据时首先需要定位到具体的 Segment 中。
*/
final Segment<K,V>[] segments;
transient Set<K> keySet;
transient Set<Map.Entry<K,V>> entrySet;
Segment是ConcurrentHashMap的一个内部类,主要组成如下:
static final class Segment<K,V> extends ReentrantLock implements Serializable {
private static final long serialVersionUID = 2249069246763182397L;
// 和 HashMap 中的 HashEntry 作用一样,真正存放数据的桶
transient volatile HashEntry<K,V>[] table;
transient int count;
transient int modCount;
transient int threshold;
final float loadFactor;
}
其中HashEntry组成:
和HashMap很相似,唯一的区别就是其中核心数据如value及链表都是用volatile修饰的,保证了获取数据时的可见性。
原理上来说,ConcurrentHashMap采用了分段锁,Segment继承自ReentrantLock,不会像HashTable那样不管是put还是get操作都需要做同步处理,理论上ConcurrentHashMap支持CurrencyLevel(segment个数)的线程并发。
put方法
public V put(K key, V value) {
Segment<K,V> s;
if (value == null)
throw new NullPointerException();
int hash = hash(key);
int j = (hash >>> segmentShift) & segmentMask;
if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck
(segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment
s = ensureSegment(j);
return s.put(key, hash, value, false);
}
首先通过key定位到Setment,之后再对应的Segment中进行具体的put
final V put(K key, int hash, V value, boolean onlyIfAbsent) {
HashEntry<K,V> node = tryLock() ? null :
scanAndLockForPut(key, hash, value);
V oldValue;
try {
HashEntry<K,V>[] tab = table;
int index = (tab.length - 1) & hash;
HashEntry<K,V> first = entryAt(tab, index);
for (HashEntry<K,V> e = first;;) {
if (e != null) {
K k;
if ((k = e.key) == key ||
(e.hash == hash && key.equals(k))) {
oldValue = e.value;
if (!onlyIfAbsent) {
e.value = value;
++modCount;
}
break;
}
e = e.next;
}
else {
if (node != null)
node.setNext(first);
else
node = new HashEntry<K,V>(hash, key, value, first);
int c = count + 1;
if (c > threshold && tab.length < MAXIMUM_CAPACITY)
rehash(node);
else
setEntryAt(tab, index, node);
++modCount;
count = c;
oldValue = null;
break;
}
}
} finally {
unlock();
}
return oldValue;
}
value使用voliatile关键词修饰,但是并不能保证并发的原子性,所以put操作时仍然需要加锁处理。
首先尝试获取锁,如果获取失败则有其他线程存在竞争,这时使用scanAndLockForPut自旋锁取锁
1.尝试自旋锁取锁
2.如果重试的次数达到Max_Scan_retries,则改为阻塞锁获取,保证获取成功
\
put流程:
1.通过key的hashCode定位到HashEntry
2.遍历HashEntry,查找对于key是否存在,存在则覆盖旧value
3.为空则新疆一个HashEntry,判断是否需要扩容后添加
4.解除Segment锁
get方法
public V get(Object key) {
Segment<K,V> s; // manually integrate access methods to reduce overhead
HashEntry<K,V>[] tab;
int h = hash(key);
long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
(tab = s.table) != null) {
for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
(tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
e != null; e = e.next) {
K k;
if ((k = e.key) == key || (e.hash == h && key.equals(k)))
return e.value;
}
}
return null;
}
通过key的hashCode定位到Segment,再通过hashCode定位到HashEntry获取元素
Base1.8
1.7中解决了并发的问题,并且能支持最多N个Segment次的并发,仍然存在的问题,查找效率低
1.8中的数据结构
结构同1.8中的HashMap,其中抛弃了原有的Segment分段锁,采用CAS+synchronized来保证并发的安全性。
将HashEntry改为Node,但作用相同,其中val和next都使用了volatile,包住了可见性。
put方法
1.根据key计算出hashCode
2.判断是否需要初始化
3.根据key定位到的Node如果为空,可以写入数据,利用CAS写入,失败则自旋保证成功
4.当前位置的hashCode == -1,则需要进行扩容
5.如果都不满足,利用synchronized锁写入数据
6.如果数据大于TREEIFY_THRESHOLD,转换位红黑树
get方法
1.计算hashCode
2.是红黑树,使用红黑树的方法获取值
3.使用链表方式变量获取值
总结
- 谈谈你理解的 HashMap,讲讲其中的 get put 过程。
- 1.8 做了什么优化?
- 是线程安全的嘛?
- 不安全会导致哪些问题?
- 如何解决?有没有线程安全的并发容器?
- ConcurrentHashMap 是如何实现的? 1.7、1.8 实现有何不同?为什么这么做?
HashTable
HashTable的操作几乎和HashMap一致,主要的区别在于HashTable为了实现多线程安全,在几乎所有的方法上都加上了synchronized锁,而加锁的结果就是HashTable操作的效率十分低下。
HashTable与HashMap对比
- 线程安全:HashMap是线程不安全的类,多线程下会造成并发冲突,但单线程下运行效率较高;HashTable是线程安全的类,很多方法都是用synchronized修饰,但同时因为加锁导致并发效率低下,单线程环境效率也十分低;
- 插入null:HashMap允许有一个键为null,允许多个值为null;但HashTable不允许键或值为null;
- 容量:HashMap底层数组长度必须为2的幂,这样做是为了hash准备,默认为16;而HashTable底层数组长度可以为任意值,这就造成了hash算法散射不均匀,容易造成hash冲突,默认为11;
- Hash映射:HashMap的hash算法通过非常规设计,将底层table长度设计为2的幂,使用位与运算代替取模运算,减少运算消耗;而HashTable的hash算法首先使得hash值小于整型数最大值,再通过取模进行散射运算;
- 扩容机制:HashMap创建一个为原先2倍的数组,然后对原数组进行遍历以及rehash;HashTable扩容将创建一个原长度2倍的数组,再使用头插法将链表进行反序;
- 结构区别:HashMap是由数组+链表形成,在JDK1.8之后链表长度大于8时转化为红黑树;而HashTable一直都是数组+链表;
- 继承关系:HashTable继承自Dictionary类;而HashMap继承自AbstractMap类;
- 迭代器:HashMap是fail-fast;而HashTable不是。
建议
不建议使用HashTable,Oracle官方也将其废弃,建议在多线程环境下使用ConcurrentHashMap类。