您的位置:首页 > 编程语言 > Java开发

java容器源码--hashmap源码解读

2016-02-19 09:46 696 查看
趁着过年有时间,把java集合中常见的几个集合的源码都稍微读了一下,写一点自己的浅见吧。以下均基于mac os x,jdk1.8,ide为InteliJ idea 14.

1、总体分析

hashmap在日常开发中使用的比较多,先hashmap的继承关系。



可以看出hashmap继承抽象类AbstractMap,实现了Cloneable, Serializable, Map接口。Cloneable, Serializable, 这2个接口为标记接口,hashmap也分别实现了writeObject、readObject、clone方法。后面会有一点writeObject的小玄机。

对于Map的所有接口,看下图:



其中部分的接口在AbstractMap中有实现,今天主要分析hashmap中部分常用方法。

我们先看HashMap的内部类和常量:



先看常量:

[code]static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;


这3个分别指代的含义是默认初始化容量,最大容量,默认负载因子,后面会有讲解。

[code]static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;


这3个是当hash冲突时,jdk1.8所改用的红黑树的默认设定值。

[code]transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
transient int size;
transient int modCount;
int threshold;
final float loadFactor;


其中有4个常量有修饰符transient,这个关键词的含义是在进行序列化时,被该关键词修饰的属性或者对象不被自动序列化与反序列化。

在用迭代器进行遍历等操作时,modCount会起类似于乐观锁的作用。

而threshold可理解为hashmap的容量阈值,超过这个阈值时,则会触发一些操作(如resize);

loadFactor前面的final表明这个常量仅能被赋值一次,是该hashmap实例的负载因子,根据当前分配容量*负载因子可以计算出该hashmap实例内的size大于多少时要进行resize。

再看内部类,关键的2个:

[code]static class Node<K,V> implements Map.Entry<K,V>;
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V>


Node与TreeNode为HashMap内部存储数据的两种不同数据结构,node为链表式结构,TreeNode为红黑树(这个,哈哈哈,忘的差不多了)

2、核心方法分析

说实话,hashmap内部的方法很多,而且部分方法1.8和1.8以下是变了个样。我选其中几个分析一下(分析的不对请指出)。

2.0 构造函数,三个

这个嘛,看看就懂了,不分析了。

2.1 tableSizeFor

[code]static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }


这个方法的作用是得出hashmap的当前分配容量。进行位移操作后,那么可以保证容量是2的n次方。而hashmap中决定一个元素存储的位置是(cap-1)&hashcode,如果容量保证是2的n次方,那么末位必定是1,在进行与操作得出存储位置时,可以保证hashmap的所有位置都可以均匀的存储(key均匀分布的情况下)。

2.2 resize

[code]final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    //原hashmap有数据
    if (oldCap > 0) {
        //若原hashmap的数组不小于最大容量,扩到最大,返回
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //原数组容量翻倍后小于最大容量,且原数组大于初始化大小,容量翻倍,阈值也翻倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    //hashmap无数据,阈值大于0,直接将容量变成与原阈值等同大小
    //这种情况是hashmap进行实例化时声明了大小
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    //hashmap无数据,阈值为0,那么此时就为空map,赋予默认值    
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    //新阈值为0,对应上面的第二种情况
    //此时根据容量*负载因子得出一个阈值,判断扩充后的容量是否小于最大容量且新阈值是否小于最大容量,
    //是:新阈值则为刚得出的值,否则新阈值则为Inter.maxValue
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    //new一个新的node数组实例
    @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    //原node数组不为空
    //此时要将原node数组的数据复制到新的node数组实例中
    if (oldTab != null) {
        //遍历原node数组
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            //第j个桶不为空
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                //该位置的next为空,则表明该位桶没有发生hashmap冲突
                //直接将该位桶的对象放置到新node数组对应的位桶上
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                //该位桶的next不为空,此时判断该元素是否为TreeNode的实例
                //若是,则表明此时该hash位桶有冲突,且存储的数据大于8,将进行红黑树的复制    
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                //该位桶的next不为空,且该位桶存储的非红黑树实例
                //此时该位桶存储的为基于node的链表
                //在保留该链表顺序的情况下进行复制
                else { // preserve order
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        //hash值和原容量进行与操作,结果为0
                        //因为容量只会是2的n次方,那么就是判断该对象的hash值其中一位与容量进行与操作
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        //与的结果不为0
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    //lo数组放在原位桶
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    //hi数组放在j+oldCap位桶
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}


这段代码分为2大块,一块是进行扩容,一段是当原hashmap不为空时进行元素复制存储。

2.3 hash

[code]static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }


所有对hashmap进行增删查操作,都会调用这段代码。

key不为空时,会将key的hashcode 的高位与其无符号右移16位后的数进行异或。这样做,会将高位与低位进行与操作,均匀桶位的存储。

在jdk1.8之前,这个方法如下,其中h为key.hashcode:

[code]static int hash(int h) {
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}


与1.8之前的hash方法相比,就是操作更少。至于两者的性能差异(hash冲突率、执行效率等),还有待考验。

2.4 put方法

1.8的hashmap put方法也改写了。对putval后面2个标志位不太理解。

[code]public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //若原hashmap为空或为空map
        //resize并得出length
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //若hashmap第n-1个位桶上为空,则直接存(因为length是从1开始计数的)
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //hash值相同且key相等,此时新插入的key重复,覆盖赋值
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //判断该位桶元素是否为红黑树实例,是的话进行红黑树节点插入
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //新插入的元素在现有位桶中不存在,且不为红黑树存储方式
            //那么就要进行node链表的遍历查询
            else {
                for (int binCount = 0; ; ++binCount) {
                    //下一个元素无值
                    if ((e = p.next) == null) {
                        //new一个新链表节点
                        p.next = newNode(hash, key, value, null);
                        //若该位桶存储的数据个数不小于7,则该位桶转化为红黑树存储
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //hash值相同且key相等,此时则说明该key在位桶中存在,覆盖赋值后终端
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //向后继续循环
                    p = e;
                }
            }
            //该位桶存储对象不为空
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //onlyIfAbsent在hashmap中为false
                //将value赋值给该位桶首个对象
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                //linkedhashmap使用
                //设计的比较巧妙
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //并发控制标志位,作用类似于乐观锁
        ++modCount;
        //当前size自增后大于该hashmap实例阈值,重新分配空间
        if (++size > threshold)
            resize();
        //linkedHashmap使用
        afterNodeInsertion(evict);
        return null;
    }


从这段代码也可以看出,在进行对象插入的时候,也是要先判断对象是否在位桶中存在,并且根据位桶的情况进行插入操作。

2.5 get操作

[code] public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        //table不为空,n-1位桶存储对象不为空
        //否则返回null
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //判断n-1位桶的第一个元素的key是否等同于入参key
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //遍历n-1位桶
            if ((e = first.next) != null) {
                //若n-1位桶为红黑树,遍历之
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                //n-1位桶不为红黑树,循环该位桶
                do {
                    //链表该节点的hash是否与入参相同,key是否相等
                    //是则返回该节点
                    //否则继续下一次循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }


get方法与put方法类似

2.6 remove

[code]public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        //类似于getNode
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            //该位桶存储对象不为空,且,
            //标志位matchvalue为false或节点的value与key相同或者相等
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                //红黑树节点,进行红黑树节点删除操作 
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //非红黑树节点
                //首节点,指针后移
                else if (node == p)
                    tab[index] = node.next;
                //非首节点,指针后移
                else
                    p.next = node.next;
                //并发控制
                ++modCount;
                //从这个地方可以看出size是怎么得出的
                //size为所有元素,length为位桶的数据
                --size;
                //linkedHashmap使用
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }


remove与put、get不同在于其进行remove时,可能涉及要进行指针后移

2.7 writeObject 序列化

[code]private void writeObject(java.io.ObjectOutputStream s)
        throws IOException {
        int buckets = capacity();
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();
        s.writeInt(buckets);
        s.writeInt(size);
        internalWriteEntries(s);
    }


还记得上面说的关于序列化的彩蛋么,that’s it.

这段代码比较隐藏的亮点在s.writeInt(size);

先看hashmap的内部全局变量transient Node[] table;这个node数组使用了transient修饰符,表明该node数组不参与序列化。而在数据传输,又必须要进行序列化,那么就在writeObject内显式的使用node的size来表明有多少个对象需要进行序列化,避免对空对象进行序列化,节约资源。

关于java序列化机制,我还有一篇文章,有兴趣可以看看。

/article/3703962.html

3、小结

这篇文章其实还有很多没写到的地方,比如序列化的io机制,位桶存储之红黑树(说实话,也没深入去了解)。若不限于源码解读,hashmap里面还有很多值得分析的内容,如由在hash冲突时存储结构由纯链表改为链表+红黑树的原因及效率分析,并发异常等。

后续还有java容器的其他源码解读,也欢迎阅读和指出其中的错误之处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: