遗留线程安全类Vector和HashTable简要源码分析

总结

总结放前面防止太长不看

Vector

  1. Vector就是使用synchronized限制线程安全的一个List实现。
  2. Vector是基于数组实现的,默认初始容量是10,在构造的时候可以指定初始容量和一个capacityIncrement,扩容时默认翻倍扩容,如果指定了capacityIncrement则每次扩容增加capacityIncrement容量。
  3. Stack是基于Vector实现的。

HashTable

  1. HashTable只用数组+链表存储节点。
  2. HashTable添加节点的时候把节点连在链表的头部而不是尾部。
  3. HashTable的节点类型是内部类Entry。
  4. HashTable的数组下标与哈希值的对应关系是(hash & 0x7FFFFFFF) % tab.length,本质上只是把HashMap的tab.length-1换成了0x7FFFFFFF,保证最高位符号位不为1,但HashMap把模运算换成了位运算,提高了效率。
  5. HashTable的数组初始容量为11,不要求必须是2的整数次幂,甚至扩容的时候使用2*oldCapacity+1来扩容保证奇数。

Vector

构造函数

public Vector() {
    this(10);
}

public Vector(int initialCapacity) {
    this(initialCapacity, 0);
}

public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                            initialCapacity);
    this.elementData = new Object[initialCapacity];
    this.capacityIncrement = capacityIncrement;
}

可以知道Vector也是基于数组实现的,默认初始容量是10,在构造的时候可以指定初始容量和一个capacityIncrement,可以猜到和扩容相关。

Add

public synchronized boolean add(E e) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = e;
    return true;
}

使用synchronized将整个函数限制了同步,重点看扩容:

private void ensureCapacityHelper(int minCapacity) {
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    // 翻倍扩容,如果指定了capacityIncrement则每次扩容增加capacityIncrement容量
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                        capacityIncrement : oldCapacity);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    elementData = Arrays.copyOf(elementData, newCapacity);
}

扩容机制和ArrayList稍有不同,默认翻倍扩容,如果指定了capacityIncrement则每次扩容增加capacityIncrement容量。

remove

public synchronized E remove(int index) {
    modCount++;
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);
    E oldValue = elementData(index);

    int numMoved = elementCount - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                            numMoved);
    elementData[--elementCount] = null; // Let gc do its work

    return oldValue;
}

删除机制和ArrayList一样,就是用synchronized把整个函数修饰了。

HashTable

构造方法

public Hashtable() {
    this(11, 0.75f);
}

public Hashtable(int initialCapacity) {
    this(initialCapacity, 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];
    threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}

可以看出,和HashMap类似,也有loadFactor,默认位0.75f,而initialCapacity默认为11,不是一个2的整数次幂。

put

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;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K,V> entry = (Entry<K,V>)tab[index];
    for(; entry != null ; entry = entry.next) {
        //如果原来存在旧值,替换旧值
        if ((entry.hash == hash) && entry.key.equals(key)) {
            V old = entry.value;
            entry.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];
    //把e赋值给了新节点的next,可见是把新节点放在了链表的头部
    tab[index] = new Entry<>(hash, key, value, e);
    count++;
}

通过这个函数发现它和JDK1.8的HashMap还是有挺大不同的:
1. HashTable只用数组+链表存储节点,JDK1.8的HashMap增加了红黑树。
2. HashTable添加节点的时候把节点连在链表的头部而不是尾部。
3. HashTable的节点类型是内部类Entry,而HashMap是Node。
4. 数组下标与哈希值的对应关系不同,HashTable是(hash & 0x7FFFFFFF) % tab.length,本质上只是把HashMap的tab.length-1换成了0x7FFFFFFF,但HashMap把模运算换成了位运算,提高了效率。

然后来看扩容:扩容只发生在count >= threshold的时候

protected void rehash() {
    int oldCapacity = table.length;
    Entry<?,?>[] oldMap = table;

    // overflow-conscious code
    // 新的容量:旧容量的两倍+1
    int newCapacity = (oldCapacity << 1) + 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++;
    threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    table = newMap;
    // 重建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

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;
}

没什么好说的,正常的链表移除节点的方法。

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/%e9%81%97%e7%95%99%e7%ba%bf%e7%a8%8b%e5%ae%89%e5%85%a8%e7%b1%bbvector%e5%92%8chashtable%e7%ae%80%e8%a6%81%e6%ba%90%e7%a0%81%e5%88%86%e6%9e%90/

(0)
彭晨涛彭晨涛管理者
上一篇 2020年2月15日
下一篇 2020年2月15日

相关推荐

发表回复

登录后才能评论