Java - Hashtable 源码阅读笔记

in Tech Java

简介

  Hashtable since JDK1.0 ,比较老古董的玩意啦。跟早期版本的HashMap几乎一致,除了直接加 synchronized锁全表 来支持并发操作,并发高的情况下,性能较低。推荐ConcurrentHashMap,锁粒度更细,并发性能表现更优异。

数据结构

  数组+链表。当key的hash值出现碰撞,也就是算出来的下标相同时,则用链表来存储数据。

源码

构造方法

  可以指定初始容量、加载因子。默认初始容量11、加载因子0.75

    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
        table = new Entry<?,?>[initialCapacity];
        threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    }

新增or修改

put() 方法

    // synchronized 锁整个表
    public synchronized V put(K key, V value) {
        // 不允许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;
    }

addEntry() 方法

    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;
        }
        // 取出index的链表
        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        // 创建Entry,并链接原链表。最后赋值tab[index]
        tab[index] = new Entry<>(hash, key, value, e);
        // 计数
        count++;
    }

查询节点

get() 方法

    public synchronized V get(Object key) {
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        // 计算索引
        int index = (hash & 0x7FFFFFFF) % tab.length;
        // 遍历链表
        for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                return (V)e.value;
            }
        }
        return null;
    }

删除节点

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;
            }
        }
        // 不存在key的节点
        return null;
    }

扩容

rehash() 方法

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

        // 新容量 = 2倍旧容量 + 1
        // overflow-conscious code
        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;
        // 搬运旧表的数据到新表
        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;
                // hash冲突,转用链表存储
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
            }
        }
    }