深入JDK源码之Hashtable

来源:互联网 发布:mac 设置成代理服务器 编辑:程序博客网 时间:2024/06/05 09:03

数据结构

数组实现的Hash表

    /**     * The hash table data.     */    private transient Entry<?,?>[] table; // HashMap中的table使用默认修饰符,即同一包内可见

Entry<?,?>

    /**     * 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;        }        @SuppressWarnings("unchecked")        protected Object clone() {            return new Entry<>(hash, key, value,                                  (next==null ? null : (Entry<K,V>) next.clone()));        }        // Map.Entry Ops        public K getKey() {            return key;        }        public V getValue() {            return value;        }        public V setValue(V value) {            // 进行判断value是否为空,即不允许value为空,其实key也不能为空,下文会说的            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() {            // 直接用hash进行异或,与HashMap不同            return hash ^ Objects.hashCode(value);        }        public String toString() {            return key.toString()+"="+value.toString();        }    }

  HashMap中使用了Node<K,V>实现数组,而在Hashtable中使用了Entry<K,V>,并且是私有的。在HashMap中key和value都可以为空,而在Hashtable中key和value都不能为空。

属性

    /**     * The total number of entries in the hash table.     * 当前表中的Entry数量,如果超过了阈值,就会扩容,即调用rehash方法     */    private transient int count;    /**      * 加载因子,默认为0.75f     */    private float loadFactor;    /**     * 阈值,值为 (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1)     * initialCapacity可以由用户指定,如果不指定,那么默认为11,即Hashtable默认阈值为8     * Hashtable默认大小是11是因为除(近似)质数求余的分散效果好 https://www.zhihu.com/question/29587252     */    private int threshold;    /**     * 用来实现“fail-fast”机制的(也就是快速失败)。所谓快速失败就是在并发集合中,其进行     * 迭代操作时,若有其他线程对其进行结构性的修改,这时迭代器会立马感知到,并且立即抛出     * ConcurrentModificationException异常,而不是等到迭代完成之后才告诉你(你已经出错了)。     * 参考文章:http://www.cnblogs.com/dolphin0520/p/3933551.html     */    private transient int modCount = 0;

  这就是Hashtable的主要属性。

方法

put

  源码:

    // 使用 synchronized 关键字保证线程安全    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;        /**          * 这就是为什么key不能为空的原因,key的hashCode是调用Object的hashCode()方法,         * 是native的方法,如果为null,就会抛出空指针异常         */         int hash = key.hashCode();         /**          * 因为hash可能为负数,所以就先和0x7FFFFFFF相与         * 在HashMap中,是用 (table.length - 1) & hash 计算要放置的位置         */        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;            }        }        // 如果key对应的值不存在,就调用addEntry方法加入        addEntry(hash, key, value, index);        return null;    }

  接下来看addEntry(hash, key, value, index)方法。

addEntry

    private void addEntry(int hash, K key, V value, int index) {        modCount++;        Entry<?,?> tab[] = table;        if (count >= threshold) { // 当前元素大于等于阈值,就扩容并且再计算hash值            // 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];        // 和HashMap不同,Hashtable选择把新插入的元素放到链表最前边,而且没有使用红黑树        tab[index] = new Entry<>(hash, key, value, e);        count++;    }

rehash

    @SuppressWarnings("unchecked")    protected void rehash() {        int oldCapacity = table.length;        Entry<?,?>[] oldMap = table;        // overflow-conscious code        /**         * 新的大小为  原大小 * 2 + 1         * 虽然不保证capacity是一个质数,但至少保证它是一个奇数         */        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;            }        }    }

get

    @SuppressWarnings("unchecked")    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;    }

  get方法没什么好说的,简单看一下源码即可。

总结

两个疑问

  在看源码的过程中,通过对比HashMap和Hashtable的不同点,有两个疑问:
  1. HashMap和HashTable,一个采用(table.length - 1) & hash 计算要放置的位置,一个采用取模的 方法,这有什么不同吗?为什么要这样做?
  2. HashTable为什么不用红黑树了?
  通过查阅资料发现,Hashtable是 JDK 1.0 就引入的类,而 HashMap 是 JDK 1.2 才引入的一个Map接口的实现,而Hashtable设计的时候就采用了取模的方法计算位置,也没有设计红黑树进行优化,而添加HashMap的时候选择了不同的方法,刚开始的时候HashMap也没有使用红黑树,是在 JDK 1.8 的时候才引入了红黑树进行优化。
  看到有篇博客写的很好,应该是比我大一届的学生。

HashMap和Hashtable的区别

  1. HashMap是非线程安全的,Hashtable是线程安全的,所以Hashtable重量级一些,因为使用了synchronized关键字来保证线程安全,当一个线程在使用一个synchronized修饰的方法时,其他被synchronized修饰的方法都不能使用。
  2. HashMap允许key和value都为null,而Hashtable都不能为null。
  3. Hashtable继承自 JDK 1.0 的 Dictionary 虚拟类,而HashMap是 JDK 1.2 引进的 Map 接口的一个实现。
  4. Hashtable和HashMap扩容的方法不一样,Hashtable中数组默认大小11,扩容方式是 old*2+1。HashMap中数组的默认大小是16,而且一定是2的指数,增加为原来的2倍。
  5. 两者通过hash值散列到hash表的算法不一样,Hashtable是古老的除留余数法,直接使用Object的hashcode,而后者是强制容量为2的幂,重新根据hashcode计算hash值,在使用hash和(hash表长度 – 1)进行与运算,也等价取膜,但更加高效,取得的位置更加分散,偶数,奇数保证了都会分散到。前者就不能保证。
  6. HashMap的迭代器(Iterator)是fail-fast迭代器,而Hashtable的enumerator迭代器不是fail-fast的。所以当有其它线程改变了HashMap的结构(增加或者移除元素),将会抛出ConcurrentModificationException,但迭代器本身的remove()方法移除元素则不会抛出ConcurrentModificationException异常。参考文章。
      大致就是这些,学无止境,加油。–201703042011
0 0