Java源码阅读(一)—— HashMap

HashMap 简介

产生的背景

有1w条数据,要对其进行存储,要求做到快速查找或占用较小的空间。

如果内存空间足够大,则可以对每一个key都做一个索引,能够快速查找。

如果查询时间可以足够长,但要节省空间,就可以放到数组中顺序查找。

对二者折中,在时间和空间中寻找一个平衡,由此就有了散列表,在Java中的对应实现就是HashMap。

描述

HashMap是一种散列表的结构,

HashMap 主要用来存放键值对,它基于哈希表的Map接口实现,是常用的Java集合之一。

JDK1.8 之前 HashMap 由 数组+链表 组成的,数组是 HashMap 的主体,链表则是主要为了解决哈希冲突而存在的(“拉链法”解决冲突)。

JDK1.8 以后在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为 8)时,将链表转化为红黑树,以减少搜索时间。

HashMap 源码分析

1、继承关系


    
public abstract class AbstractMap<K,V> implements Map<K,V> {}

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {}


在这里插入图片描述

2、Map接口

定义了Map的常用方法以及Entry接口


public interface Map<K,V> {

	    int size();
	    boolean containsKey(Object key);
	    V get(Object key);
	    Set<Map.Entry<K, V>> entrySet();
	    interface Entry<K,V> {
	    	
	    	K getKey();
	    	V getValue();
	    	int hashCode();
	    	
	    }

}


3、AbstractMap抽象类

实现公有方法


public abstract class AbstractMap<K,V> implements Map<K,V> {

	
	protected AbstractMap() {
    }
    
   public int size() {
        return entrySet().size();
    }
		
	public V get(Object key) {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        if (key==null) {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getKey()==null)
                    return e.getValue();
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (key.equals(e.getKey()))
                    return e.getValue();
            }
        }
        return null;
    }
    
    public int hashCode() {
            return (key   == null ? 0 :   key.hashCode()) ^
                   (value == null ? 0 : value.hashCode());
    }
    
    public static class SimpleImmutableEntry<K,V>
        implements Entry<K,V>, java.io.Serializable{
    
    		......
    		
    }
	

}

4、构造方法



public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    	
    	//数组初始化大小
    	static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
		
		//数组的最大元素数2^30    
    	static final int MAXIMUM_CAPACITY = 1 << 30;

    	//负载因子,默认为0.75是对时间空间成本进行一个好的折衷
    	static final float DEFAULT_LOAD_FACTOR = 0.75f;
    	
    	// 当桶(bucket)上的结点数大于这个值时会转成红黑树
    	static final int TREEIFY_THRESHOLD = 8; 
    	
    	// 当桶(bucket)上的结点数小于这个值时树转链表
    	static final int UNTREEIFY_THRESHOLD = 6;
    	
    	// 桶中结构转化为红黑树对应的table的最小大小
    	static final int MIN_TREEIFY_CAPACITY = 64;
    	
    	//构造方法,多用于resize时调用
    	public HashMap(int initialCapacity, float loadFactor) {
    		
    		//初始化大小不能小于0
    		if (initialCapacity < 0)
            	throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
    		
    		//大小大于最大数量,则不再扩容
    		if (initialCapacity > MAXIMUM_CAPACITY)
            	initialCapacity = MAXIMUM_CAPACITY;
            
        	//负载因子不为负数,NaN是Not a Number的意思,如输入0f / 0f,则返回true
          	if (loadFactor <= 0 || Float.isNaN(loadFactor))
            	throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
    		
    		this.loadFactor = loadFactor;
        	//tableSizeFor的作用是保证每次的resize的大小都是2的指数倍
                // 输入13,返回的是16
                //只有当length = 2的指数时, (length- 1) & a.hashCode() 等价于
               // a.hashCode() % (i)));
               // 也就是说length为2的指数次幂的意义在于,能够支持与运算,保证结果在0 - (length-1)之间。
        	this.threshold = tableSizeFor(initialCapacity);
    		
    	}
    
    	public HashMap(int initialCapacity) {
        	this(initialCapacity, DEFAULT_LOAD_FACTOR);
    	}

    
    	//我们常用的构造方法。
   		public HashMap() {
        	this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    	}
    	
    	//使用transient关键字,进行反序列化
    	transient Node<K,V>[] table;
    	transient Set<Map.Entry<K,V>> entrySet;
    	
    }

5. 负载因子

loadFactor负载因子控制数组存放数据的疏密程度

loadFactor越趋近于1,那么 数组中存放的数据(entry)也就越多,也就越密,也就是会让链表的长度增加。导致查找元素效率低。

loadFactor越小,也就是趋近于0,存放的数据会很分散,导致数组的利用率低,

loadFactor的默认值为0.75f,是官方给出的一个比较好的临界值,是对时间空间成本进行一个好的折中。

threshold

官方解释是The next size value at which to resize (capacity * load factor),可以理解为数组扩容的标准值。threshold = capacity * loadFactor,当Size>=threshold的时候,那么就需要对数组进行扩容。

6、hash方法

先复习下移位操作

2 << 2  //向左移动2位,因为int类型有32位,所以由0...010变为0...1000,值为8
8 >> 2  //向右移动2位,由0...1000变为0...010,值为2
-8 >> 2  //有符号向右移动2位,由1...1000变为1...0010,值为-2
//原码 1000 0000 0000 0000 0000 0000 0000 1000
//补码,对原码取反加1得到 1111 1111 1111 1111 1111 1111 1111 1000
//右移2位,高位补1得到 1111 1111 1111 1111 1111 1111 1111 1110
//针对补码写出的原码为我们要的结果,保留符号位,然后按位取反再加上1
//1000 0000 0000 0000 0000 0000 0000 0010 结果为-2
-8 >>> 2  //有符号向右移动2位,取反码+1,然后右移2位,值为1073741822
//原码 1000 0000 0000 0000 0000 0000 0000 1000
//补码,对原码取反加1得到 1111 1111 1111 1111 1111 1111 1111 1000
//右移2位
//0011 1111 1111 1111 1111 1111 1111 1110 值为1073741822

HashMap的hash方法,hash方法可以防止key实现的hashCode较差,导致的hash冲撞较多的情况。使用了hash方法,可以更好的减少hash冲撞。
以下为JDK1.8的实现方式,相比于JDK1.7的性能要好很多,原因是减少了移位操作的次数。


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

//将key和value进行hashCode计算,然后两个值进行异或操作
public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
    }
    

JDK1.7的实现方式


static int hash(int h) {

    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}

Object的hashCode方法,使用native修饰,说明该方法是由非Java语言实现。

public native int hashCode();

Node


static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        //定义Key为不可变
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }



    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    	
    	TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }
        
       //返回根节点
       final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }
    	
    }

6、插入值方法

HashMap的putVal方法


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;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            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);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    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;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }


8、get方法


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;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

多线程下的resize()


final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        // 假设oldCap = 16
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        // 那么oldThr = 16 * 2 = 32,threshold为下一次resize时的大小
        int oldThr = threshold;
        // newCap 新的数组容量大小
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // newCap = 16 * 2 = 32
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                // newThr,下一次resize大小变为32 * 2 = 64
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        // 到这里创建了一个大小为原来2倍,即32的数组。
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];

       
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    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;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

transfer扩容形成单链表环操作演示


void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

有T1、T2两个线程,分别都执行到获取e指针这步,假设T1执行,T2阻塞。

完成第一个循环时

完成第二个循环时

这时T1停顿,T2开始进行扩容操作,T2的e指针指向的是最初的元素也就是key=zhang的元素。

开始执行循环中的代码e.next = newTable[i];

执行代码newTable[i] = e;后,形成环

最后执行e = next;收尾

附部分相关方法


public static boolean isNaN(float v) {
        return (v != v);
    }
    
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;
    }

posted @ 2017-03-10 00:25  清泉白石  阅读(286)  评论(0编辑  收藏  举报