Java容器——Hashtable(Java8)源码解析

    Hashtable是一种键值对型Java存储容器,自JDK1.0沿用至今。经常有将Hashtable和HashMap进行比较的例子和文章,实际上早期二者的实现原理基本一致,而HashTable的操作方法都进行了加锁,因而线程安全。本文从源码角度介绍HashTable的实现。

    一 组成元素

    1 关键变量

     /**
     * Hashtable bucket collision list 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;
        }
         ...
    
        // 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);
        }
    }

    前面说到,Hashtable是存储键值对的容器,Entry<K,V>这个内部类就是实现键值对的最小组成元素。如执行下面的这段代码 Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();numbers.put("one", 1); ("one",1)就组成了<String,Integer>的Entry。而整个Hashtable的操作实际上也就是Entry的增删改查等的操作,归根到底,最需要关注的是Entry的存储方式,这样才能理解各个操作的步骤和含义。

     /**
     * The hash table data.
     */
    private transient Entry<?,?>[] table;

    /**
     * The total number of entries in the hash table.
     */
    private transient int count;

    /**
     * The table is rehashed when its size exceeds this threshold.  (The
     * value of this field is (int)(capacity * loadFactor).)
     */
    private int threshold;

    /**
     * The load factor for the hashtable.
     */
    private float loadFactor;

    Hashtable实际上是一个一维数组,也就是table[],数组元素是以Entry为组成单元的单向链表。变量count显示了当前的Hashtable中的元素个数。threshold代表了Hashtable需要扩容时的数量阈值,loadFactor是扩容的百分比阈值。

     Hashtable的构造如上图所示,每一个白色框代表了一个table元素,存放的是单向链表的首个元素,后继元素按顺序排列。

     2 构造函数

   /**
     * Constructs a new, empty hashtable with the specified initial
     * capacity and the specified load factor.
     *
     * @param      initialCapacity   the initial capacity of the hashtable.
     * @param      loadFactor        the load factor of the hashtable.
     * @exception  IllegalArgumentException  if the initial capacity is less
     *             than zero, or if the load factor is nonpositive.
     */
    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);
    }

    /**
     * Constructs a new, empty hashtable with the specified initial capacity
     * and default load factor (0.75).
     *
     * @param     initialCapacity   the initial capacity of the hashtable.
     * @exception IllegalArgumentException if the initial capacity is less
     *              than zero.
     */
    public Hashtable(int initialCapacity) {
        this(initialCapacity, 0.75f);
    }

    /**
     * Constructs a new, empty hashtable with a default initial capacity (11)
     * and load factor (0.75).
     */
    public Hashtable() {
        this(11, 0.75f);
    }

    /**
     * Constructs a new hashtable with the same mappings as the given
     * Map.  The hashtable is created with an initial capacity sufficient to
     * hold the mappings in the given Map and a default load factor (0.75).
     *
     * @param t the map whose mappings are to be placed in this map.
     * @throws NullPointerException if the specified map is null.
     * @since   1.2
     */
    public Hashtable(Map<? extends K, ? extends V> t) {
        this(Math.max(2*t.size(), 11), 0.75f);
        putAll(t);
    }

    Hashtable的构造函数指定了两个关键变量,初始容量,和承载因子。承载因子被设定为0.75,按照官方文档的说明,是综合了时间和空间的利用效率的经验值。另外,初始化大小都设定为2的倍数,相乘起来可以承载的元素个数就是整数,便于使用。

    二 函数概述

    1 关键函数

    Hashtable的优势在于通过hash计算下标,可以以常数时间查找元素。这里会有三个问题

  •     怎么计算下标
  •     如果下标重叠了如何处理  
  •     何时扩容,如何扩容
 int hash = key.hashCode();
 int index = (hash & 0x7FFFFFFF) % tab.length;

    首先计算Key的哈希值,然后对下标数组取余找到数组下标。前面我们说到,Hashtable是单链表的数组,出现哈希碰撞的情况,就在该下标所存储的链表中遍历查找需要操作的元素位置进行后续操作。

 Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
               ...
            }
        }

    当Hashtable存储了超过threshold的Entry(count / capacity >= loadFactor),就需要对Hashtable进行扩容,这也是Hashtable常用的关键步骤。

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

        // 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;
                e.next = (Entry<K,V>)newMap[index];
                newMap[index] = e;
            }
        }
    }

    如rehash所描述的,首先对存储数组进行扩容,方式是原数组长度的二倍加一,并创建新的table。接下来就要将存在原table中的各个链表转移到新table中。具体操作如下

    1  遍历原table,找到一条链表的首元素;

    2  计算该元素在新table中的index,将该元素的next指针指向newtable[index],并以此元素为该槽位的首元素;

    3  后续元素依次遍历处理。

    这里可能需要注意的地方是步骤2,不同於单向链表的末尾添加元素,这里是每次在队首添加元素,避免了遍历该单链表。

    2 增删改查

    理解一个容器关键在于理解容器元素的存放方式。前面我们说明了Hashtable的构成和存储方式,下面列举的增删改查实际上都是针对这种结构类型的操作。而Hashtable的增删改查,其共性在于查,找到元素了才可以进行下一步的操作。以查找元素为例。先找下标,找到目标table[index]后,再逐个遍历链表元素直到找到目标。

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

    对于添加操作,首先是找到了要添加元素Key的哈希对应的table的下标,如果为空则添加为链表头,如果有元素则添加到该链表的末尾。添加和删除元素也是同理,先找到元素的位置,然后进行链表的添加和删除操作。

 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;
    }
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)) {
                if (prev != null) {
                    prev.next = e.next;
                } else {
                    tab[index] = e.next;
                }
                modCount++;
                count--;
                V oldValue = e.value;
                e.value = null;
                return oldValue;
            }
        }
        return null;
    }

    理解了增删改查的基本操作,对于Hashtable的用法和原理也就基本都了解了。

    三 小结

    本文对Hashtable的组成和基本操作进行了介绍,行文至此,有一个问题很容易提出,Hashtable自JDK1.0就存在,为何现在使用率越来越低?为何越来越多转而使用HashMap或ConcurrentHashMap?

    笔者列出几个因素抛砖引玉:

    1 Hashtable计算table下标的方式简单粗暴,直接使用hash对table长度取余,如果table长度较短,或Hash值末尾几位相同,那么将有多个元素存放于一个table的槽内。

    2 对于Hash碰撞的,Hashtable采用单链表形式存放元素,对这些元素的各种操作都需要对单链表进行遍历,效率低下,完全丧失了Hashtable查找的速度优势。

    3 Hashtable的重要操作包括查询都是synchronized操作,保证或了线程安全但同时非常耗时。

    那么,常用的HashMap和同步的ConcurrentHashMap是如何解决这些问题的呢?读者可以阅读相应源码理解一探究竟。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章