我们经常说Hashtable是线程安全的,HashMap是线程不安全的。现在我们就来了解一下Hashtable到底是如何实现线程安全且看一下它的各种重要方法的实现。
我们先看一下Hashtable调用无参的构造参数发生了什么。
public Hashtable() {
this(11, 0.75f);//调用这个构造方法
}
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];//从这里可以看到,在还没添加元素之前就已经把hash表的初始容量创建好了,还发现数据元素存储在静态内部类Entry中。
threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);//threshold为阈值,容量*0.75
}
我们看一下put(K k,V v)方法。
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) { //说明value不可为null
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();//这里key如果为null,也会报错,所以key也不能为null
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {//顺着tab[index]位置的链表找是否有相同的key,若有,返回旧value
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;//赋新value
return old;
}
}
addEntry(hash, key, value, index);//添加新元素
return null;
}
private void addEntry(int hash, K key, V value, int index) {
modCount++;
Entry<?,?> tab[] = table;
if (count >= threshold) { //如果元素个数大于阈值,就扩容
// Rehash the table if the threshold is exceeded
rehash();//扩容
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e); //从上面一行和这一行,可以看出,Hashtable采用的是头插法
count++;//元素个数加1
}
我们在看一下扩容rehash()。
protected void rehash() {
int oldCapacity = table.length;//旧hash表容量
Entry<?,?>[] oldMap = table;
// overflow-conscious code
int newCapacity = (oldCapacity << 1) + 1; //新hash表的容量,为:旧容量*2+1
if (newCapacity - MAX_ARRAY_SIZE > 0) {//基本不可能进入
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
newCapacity = MAX_ARRAY_SIZE;
}
Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
modCount++;
//新阈值还是为新容量的3/4
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
//下面这个循环,依次从后往前找每个元素,重新hash,加入新hash表,依然采用头插法
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;
e.next = (Entry<K,V>)newMap[index];
newMap[index] = e;
}
}
}
我们看一下remove(K k)方法。
//这个方法没啥说的,就是先hash后顺着链表找,找到,返回要删除的value,否则返回null
public synchronized V remove(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@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.next = e.next;
} else {
tab[index] = e.next;
}
count--;
V oldValue = e.value;
e.value = null;
return oldValue;
}
}
return null;
}
我们发现,Hashtable其实并没有当一个位置上的结点数过多而采用红黑树存储,而是继续采用链表存储,还有它的hash算法采用的是(hashCode&0X7FFFFFFF)%hash.length的。