本文基于JDK1.8对HashTable源码分析。HashTable和HashMap一样,也是基于哈希表存储数据,HashTable底层是基于数组+链表方式存储,而HashMap是基于数组+链表或者红黑树的方式存储。HashTable是线程安全的,底层使用synchronized同步锁实现确保线程安全,HashMap非线程安全。
1.类底层结构
2.类结构
HashTable包含的几个常用变量:
//存储数据的数组,数组类型为Entry<?,?>
private transient Entry<?,?>[] table;
//数组元素个数
private transient int count;
//数组扩容阈值,计算公式为:capacity * loadFactor
private int threshold;
//加载因子
private float loadFactor;
HashTable底层使用数组存储数据,数组的类型为Entry<?,?>
private static class Entry<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Entry<K,V> next;
protected Entry(int hash, K key, V value, Entry<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
@SuppressWarnings("unchecked")
protected Object clone() {
return new Entry<>(hash, key, value,
(next==null ? null : (Entry<K,V>) next.clone()));
}
// Map.Entry Ops
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
if (value == null)
throw new NullPointerException();
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
(value==null ? e.getValue()==null : value.equals(e.getValue()));
}
public int hashCode() {
return hash ^ Objects.hashCode(value);
}
public String toString() {
return key.toString()+"="+value.toString();
}
}
2.1 构造函数
public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load: "+loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
//创建数组,数组长度为指定容量
table = new Entry<?,?>[initialCapacity];
threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}
public Hashtable(int initialCapacity) {
//指定初始容量,使用默认加载因子
this(initialCapacity, 0.75f);
}
public Hashtable() {
//无参构造函数,默认初始容量为11
this(11, 0.75f);
}
可以看到,当使用无参构造函数创建Hashtable时,会初始化数组的长度为11。而HashMap则不同,在构造方法中,不会初始化数组,调用put()方法是,才初始化数组。
2.2 put(K key, V value)
put(K key, V value) 添加元素
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
//直接调用key.hashCode()方法计算hash值,所以当key为null时,将报NullPointerException异常
int hash = key.hashCode();
//通过对数组长度取模的计算元素在数组中存放的下标值
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
//获取数组指定下标index位置的元素
Entry<K,V> entry = (Entry<K,V>)tab[index];
//遍历链表,查询是否存在对应key的元素
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
//如果下标当前元素和待插入的元素的哈希值、key值匹配,替换旧制
V old = entry.value;
entry.value = value;
return old;
}
}
//否则,数组中不存在要插入的key,当待插入的元素加入到数组中
addEntry(hash, key, value, index);
return null;
}
private void addEntry(int hash, K key, V value, int index) {
//计算器递增
modCount++;
Entry<?,?> tab[] = table;
//如果数组中元素个数大于等于扩容阈值threshold,调用rehash()方法扩容
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
//扩容方法
rehash();
//将扩容后的数组table赋值给临时数组tab
tab = table;
hash = key.hashCode();
//计算元素在扩容后的数组中存放的下标值
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
//获取数组指定下标index位置的元素
Entry<K,V> e = (Entry<K,V>) tab[index];
//使用头插法插入元素,将创建的新节点的next节点之前数组中该下标的原节点e
tab[index] = new Entry<>(hash, key, value, e);
//数组元素个数递增
count++;
}
put()方法使用了synchronized 关键字加锁,同一时刻只能有一个线程访问,其他线程阻塞,所以效率比较低。
2.3 rehash()
rehash()是数组扩容方法
protected void rehash() {
//扩容前老数组的容量
int oldCapacity = table.length;
//申明临时数组 oldMap
Entry<?,?>[] oldMap = table;
// overflow-conscious code
//新数组的容量为 老数组容量的2倍+1
int newCapacity = (oldCapacity << 1) + 1;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
//如果新数组的容量大于MAX_ARRAY_SIZE,并且老数组的容量等于MAX_ARRAY_SIZE,旧不扩容了
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
//否则新数组的容量为MAX_ARRAY_SIZE
newCapacity = MAX_ARRAY_SIZE;
}
//创建新的数组,新数组长度为newCapacity
Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
//计数器+1
modCount++;
//使用新数组的容量计算数组扩容阈值,
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
//将新数组赋值给数组table属性
table = newMap;
//遍历老数组,将老数组中的元素转移到新数组中
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
//计算老数组中元素在新数组中的下标值
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
//使用头插法插入,待插入元素的next节点指向新数组中的原头节点
e.next = (Entry<K,V>)newMap[index];
newMap[index] = e;
}
}
}
HashTable扩容后新数组的容量为老数组容量的2倍+1,HashMap扩容后新数组的容量为老数组的2倍。HashTable采用头插法插入节点(将新节点的next节点指向当前位置的节点,newNode.next=currentNode),HashMap采用尾插法插入节点(当前位置节点的next节点指向新节点,currentNode.next=newNode)
2.4 get(Object key)
get(Object key) 获取指定元素
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
//获取hash值
int hash = key.hashCode();
//计算元素在数组中存放的下标值
int index = (hash & 0x7FFFFFFF) % tab.length;
//遍历链表,如果有匹配的节点,则返回节点的值,否则返回null
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
使用synchronized关键字加锁。
2.5 remove(Object key)
remove(Object key) 删除指定元素
public synchronized V remove(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
//计算元素在数组中存放的下标值
int index = (hash & 0x7FFFFFFF) % tab.length;
//获取数组中指定下标index的元素
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>)tab[index];
//遍历链表
for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
modCount++;
if (prev != null) {
//如果当前节点的前置节点prev不为null,将当前节点的前置节点的next节点指向当前节点的next节点
//a->b->c remove b,则a.next=b.next
prev.next = e.next;
} else {
//如果当前节点的前置节点prev为null,说明当前节点就是头节点,将当前节点的next节点放到数组的index位置
tab[index] = e.next;
}
//计数器递减
count--;
V oldValue = e.value;
//删除节点的value置空,便于回收
e.value = null;
//返回旧值
return oldValue;
}
}
return null;
}
remove()方法也使用了synchronized关键字加锁。
3.总结
通过分析代码,可以发现,HashTable的增删改查操作都使用了synchronized 关键字加锁。同一时刻只能有一个线程访问,其他线程阻塞,所以效率不高,如果要实现线程安全的HashMap,推荐使用ConcurrentHashMap。下篇我们再单独分析。