全到哭!阿里P7梳理的Hsahtable原理解析Github新开源,送你上岸

50 篇文章 0 订阅

上一篇分享的是《深入源码,深度解析Java 线程池的实现原理》,这篇给大家分享《Hashtable原理解析》。

概述

  本文是基于jdk8_271版本进行分析的。
  Hashtable与HashMap一样,是一个存储key-value的双列集合。底层是基于数组+链表实现的,没有红黑树结构。Hashtable默认初始化容量为11,Hashtable也会动态扩容,与HashMap不同的是,每次扩容的容量是原容量2倍+1(2倍+1是为了避免hash冲突)。Hashtable的key和value都不允许为null。Hashtable在计算hashcode与index方法上与HashMap也是不同的。Hashtable在方法上添加了synchronized同步锁。所以Hashtable是线程安全的,同时Hashtable的效率也相对较低。

数据结构

  • 实现继承关系
public class Hashtable<K,V>
     extends Dictionary<K,V>
     implements Map<K,V>, Cloneable, java.io.Serializable
  1. Dictionary:Dictionary 类是一个抽象类,用来存储键/值对,作用和Map类相似。Dictionary类已经过时了,所以Hashtable类使用也相对较少。
  2. Map:实现Map接口,使用Map定义的统一规范。
  3. Cloneable:重写Cloneable拷贝方法。
  4. Serializable:重写序列化方法。
  • 成员变量
// 存放hash表数据
    private transient Entry<?,?>[] table;
    // 元素数量
    private transient int count;
    // 阈值。元素数量达到该值,进行扩容
    private int threshold;
    // 加载因子,默认是0.75
    private float loadFactor;
    // 修改次数
    private transient int modCount = 0;
  • 构造函数

  Hashtable默认初始化容量为11,默认加载因子的值为0.75(与HashMap一样)。选择0.75作为默认的加载因子,完全是时间和空间成本上寻求的一种折中选择。加载因子过高虽然减少了空间开销,但同时也增加了查询成本;加载因子过低虽然可以减少查询时间成本,但是空间利用率很低。

  Hashtable初始化容量值使用传入的值(0除外),不会重新计算(HashMap需要重新计算,使得容量大小为2的指数次幂)。在构造方法创建对象时,会直接初始化数组,没有采用懒加载的方式。

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);
        // 如果初始化容量传入的是0,则默认使用1
        if (initialCapacity==0)
            initialCapacity = 1;
        this.loadFactor = loadFactor;
        table = new Entry<?,?>[initialCapacity];
        // 计算阈值。预计的阈值为初始化容量*加载因子,预计的阈值如果大于MAX_ARRAY_SIZE + 1,则实际阈值设置为MAX_ARRAY_SIZE + 1
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }
    public Hashtable(int initialCapacity) {
        // 传入初始化容量,加载因子使用默认值0.75。初始化容量传入的是多少就初始化多大(0除外;传入的如果0,默认使用1),不需要再重新计算
        this(initialCapacity, 0.75f);
    }
    public Hashtable() {
        // 默认初始化容量11,默认加载因子0.75
        this(11, 0.75f);
    }
    public Hashtable(Map<? extends K, ? extends V> t) {
        // 初始化容量为传入集合元素数量的2倍(至少为11),加载因子使用默认值0.75
        this(Math.max(2*t.size(), 11), 0.75f);
        putAll(t);
    }

主要方法解析

  • 扩容方法

  这里与HashMap扩容时候有点区别,链表数据迁移时候,Hashtable是在链表头部插入(和之前链表反过来),HashMap是在在jdk8开始是尾部插入。

protected void rehash() {
        int oldCapacity = table.length; // 原容量值
        Entry<?,?>[] oldMap = table;    // 原数组
        // overflow-conscious code
        int newCapacity = (oldCapacity << 1) + 1;   // 预计扩容的容量为原容量的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++; // 修改次数+1
        // 计算阈值。新容量值*加载因子,与容量最大值+1,两个比较取最小值
        threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
        table = newMap;
        for (int i = oldCapacity ; i-- > 0 ;) {
            // 遍历原数组,从后往前
            for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
                // 遍历该索引位链表,这里与jdk8中hashmap有点区别,这里是在链表头部插入(和之前链表会反过来),hashmap是在尾部插入
                Entry<K,V> e = old;
                old = old.next;
                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
            }
        }
    }
  • 添加元素

  添加元素时,Hashtable与HashMap有3点区别:

  1. Hashtable的key-value都不允许为null。
  2. Hashtable是在链表头部插入(和之前链表反过来),HashMap是在尾部插入。
  3. Hashtable是先判断是否需要扩容,再插入元素;jdk8HashMap是先插入元素再判断是否需要扩容。
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            // value为空,会抛出空指针异常
            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)) {
                // 该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];
        // 插入元素是在链表头部插入
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
    }
  • 删除元素
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;
    }
    public synchronized boolean remove(Object key, Object value) {
        Objects.requireNonNull(value);
        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) && e.value.equals(value)) {
                modCount++;
                if (prev != null) {
                    prev.next = e.next;
                } else {
                    tab[index] = e.next;
                }
                count--;
                e.value = null;
                return true;
            }
        }
        return false;
    }
  • 序列化/反序列化方法
private void writeObject(java.io.ObjectOutputStream s)
            throws IOException {
        Entry<Object, Object> entryStack = null;
        synchronized (this) {
            // Write out the threshold and loadFactor
            s.defaultWriteObject();
            // Write out the length and count of elements
            s.writeInt(table.length);
            s.writeInt(count);
            // Stack copies of the entries in the table
            for (int index = 0; index < table.length; index++) {
                Entry<?,?> entry = table[index];
                while (entry != null) {
                    entryStack =
                        new Entry<>(0, entry.key, entry.value, entryStack);
                    entry = entry.next;
                }
            }
        }
        // Write out the key/value objects from the stacked entries
        while (entryStack != null) {
            s.writeObject(entryStack.key);
            s.writeObject(entryStack.value);
            entryStack = entryStack.next;
        }
    }
    private void readObject(java.io.ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {
        // Read in the threshold and loadFactor
        s.defaultReadObject();
        // Validate loadFactor (ignore threshold - it will be re-computed)
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new StreamCorruptedException("Illegal Load: " + loadFactor);
        // Read the original length of the array and number of elements
        int origlength = s.readInt();
        int elements = s.readInt();
        // Validate # of elements
        if (elements < 0)
            throw new StreamCorruptedException("Illegal # of Elements: " + elements);
        // Clamp original length to be more than elements / loadFactor
        // (this is the invariant enforced with auto-growth)
        origlength = Math.max(origlength, (int)(elements / loadFactor) + 1);
        // Compute new length with a bit of room 5% + 3 to grow but
        // no larger than the clamped original length.  Make the length
        // odd if it's large enough, this helps distribute the entries.
        // Guard against the length ending up zero, that's not valid.
        int length = (int)((elements + elements / 20) / loadFactor) + 3;
        if (length > elements && (length & 1) == 0)
            length--;
        length = Math.min(length, origlength);
        if (length < 0) { // overflow
            length = origlength;
        }
        // Check Map.Entry[].class since it's the nearest public type to
        // what we're actually creating.
        SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, length);
        table = new Entry<?,?>[length];
        threshold = (int)Math.min(length * loadFactor, MAX_ARRAY_SIZE + 1);
        count = 0;
        // Read the number of elements and then all the key/value objects
        for (; elements > 0; elements--) {
            @SuppressWarnings("unchecked")
                K key = (K)s.readObject();
            @SuppressWarnings("unchecked")
                V value = (V)s.readObject();
            // sync is eliminated for performance
            reconstitutionPut(table, key, value);
        }
    }
  • 以上就是《Hashtable原理解析》的分享。
  • 也欢迎大家交流探讨,该文章若有不正确的地方,希望大家多多包涵。
  • 创作不易,你们的支持就是我最大的动力,如果对大家有帮忙给个赞哦~~~

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值