Java沉思录之HashMap源码浅析

Question

  1. HashMap的使用场景
  2. HashMap的工作原理
  3. HashMap在JDK7和JDK8的实现区别
  4. HashMap与Hashtable区别
  5. HashMap是线程安全的吗?如果不安全会有什么问题,有线程安全的解决方案吗?
  6. ConcurrentHashMap工作原理

Answer

1. HashMap的使用场景

当程序需要存储一些键值对,例如数据字典,全局参数等类型变量时,可使用HashMap作为存储对象的数据结构。HashMap允许null key和null value。
HashMap使用

2. HashMap的工作原理

HashMap可根据key的hashCode快速定位到数组下标,若发生冲突,则顺着链表一个节点一个节点查找下去,时间复杂度为链表的长度,O(n),在Java8中,当链表元素超过8个后,自动将链表转为红黑树,时间复杂度变成O(logN),提高了查找效率。

首先看下HashMap中几个比较关键的成员变量。

/**
 * 默认数组长度16,长度保持2^n,可扩容,扩容后数组为原来的2倍。
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
 * 数组最大长度2^30
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 默认负载因子,0.75
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * 用于判断是否需要将链表转换为红黑树的阈值.
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * 存放元素的数组,长度保持2^n,可扩容
 */
transient Node<K,V>[] table;

/**
 * HashMap中键值对的数量.
 */
transient int size;

/**
 * threshold = capacity * load factor.超过该阈值需要进行扩容
 */
int threshold;

/**
 * 负载因子
 */
final float loadFactor;

其中最重要的两个影响性能的参数分别是:

  1. 容量(capacity):哈希表中桶的数量,初始化容量就是创建哈希表时的容量。
  2. 负载因子(load factor):负载因子是在自动增加容量之前允许哈希表填满的度量。

当哈希表中的条目数超过加载因子和当前容量的乘积时,哈希表将被重新哈希(即,重建内部数据结构),以便哈希表具有大约两倍的桶数。

桶节点,定义了hash值,key、value及下一个节点

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    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;
    }
}

再来看最常用的get、put方法:

在get、put方法中计算下标时,需要用到一个hash方法。

/*
 *先获取key的hashCode,另h = key.hashCode()
 *再h进行无符号右移16位
 *将两个结果异或得到最终的key的hash值,i = (n - 1) & hash
 *作为节点下标
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

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

/**
 * Implements Map.get and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
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;
		//若冲突了,则取链表下一个节点,通过判断key是否相等
        if ((e = first.next) != null) {
			//判断是否为红黑树节点,时间复杂度O(logn)
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
				//链表节点,时间复杂度O(n)
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

get方法比较简单,大体思路如下:

  1. 先判断数组的第一个节点,若key和hash值相等,命中返回
  2. 若冲突了,判断是否链表节点,若是则遍历链表,查找key和hash相等的节点返回,时间复杂度O(n)
  3. 若不是链表节点,判断是否是红黑树节点,根据key和hash遍历红黑树,找到相等的节点,时间复杂度O(logN)
  4. 若遍历整个哈希表未命中则返回null

再来看put方法:

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

/**
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
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;
	//根据hash值判断当前节点是否为空(没有碰撞),为空新建一个节点,并将key,value传进去
    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);
		//通过新增一个链表节点,写入数据
        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;
                }
				//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;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

put方法大致思路如下:

  1. 根据key的hash值找到节点,若未发生碰撞,将key和value写入新节点
  2. 若碰撞了,通过链表的方式存放在桶中
  3. 若链表已填满,长度超过TREEIFY_THRESHOLD(默认8),就把链表转换为红黑树
  4. 若key已存在,替换旧值
  5. 若整个桶满了,阈值threshold超过负载因子load factor * 当前容量current capacity,需进行扩容resize()

3. HashMap在JDK7和JDK8的实现区别

主要区别是JDK7 HashMap 采用数组+链表实现,而JDK8 HashMap 采用数组+链表+红黑树实现,提高了查询效率。

Java8 HashMap结构

4. HashMap与Hashtable区别

Hashtable是历史遗留类,继承Dictionary类(已被废弃)。Hashtable是线程安全的,但效率比或者使用ConcurrentHashMap低,在非线程安全场景下,又不如HashMap。所以现在已不推荐使用。

5. HashMap的线程安全性

HashMap是线程不安全的,代码中未进行并发处理,在多线程操作时可能会导致数据不一致性。可以用 Collections 的synchronizedMap 方法使HashMap 具有线程安全的能力,或者使用ConcurrentHashMap。

6. ConcurrentHashMap工作原理

ConcurrentHashMap的key和value不能为空,在Java7中也是使用数组+链表实现,在Java8中使用了数组+链表+红黑树。
首先,先看下ConcurrentHashMap几个比较重要的成员变量:

/**
 * 整个ConcurrentHashMap的最大容量 2^30
 */
private static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 默认初始化容量16
 */
private static final int DEFAULT_CAPACITY = 16;

/**
 * 默认并发数,JDK7中Segment数量,在JDK8中已没啥用了
 */
private static final int DEFAULT_CONCURRENCY_LEVEL = 16;

/*
 * JDK7中有用到,通过继承ReentrantLock进行加锁,使用分段锁技术,
 * 默认16个Segment,即默认16线程并发操作,每当一个线程占用锁访问一个  * Segment 时,不会影响到其他的Segment,从而实现全局线程安全功能。在
 * JDK8中没用了。
 */
static class Segment<K,V> extends ReentrantLock implements Serializable {
    private static final long serialVersionUID = 2249069246763182397L;
    final float loadFactor;
    Segment(float lf) { this.loadFactor = lf; }
}

ConcurrentHashMap在JDK7和JDK8中实现有很大区别:
Java7主要使用Segment分段锁技术实现线程安全

https://s2.ax1x.com/2019/07/04/ZNs4QU.png

而Java8引入了红黑树,存放数据的节点使用Node替代HashEntry,使用cas+synchronized保证线程安全性,提高了查询效率。
Java8 ConcurrentHashMap结构

再来看下get方法:

public V get(Object key) {
    Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
    int h = spread(key.hashCode());
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (e = tabAt(tab, (n - 1) & h)) != null) {
        if ((eh = e.hash) == h) {
            if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                return e.val;
        }
        else if (eh < 0)
            return (p = e.find(h, key)) != null ? p.val : null;
        while ((e = e.next) != null) {
            if (e.hash == h &&
                ((ek = e.key) == key || (ek != null && key.equals(ek))))
                return e.val;
        }
    }
    return null;
}

基本思路就是根据key的hashCode查找,若在数组节点直接命中则返回值;
若为树节点,则通过遍历树查找返回;否则遍历链表,通过key.equals()方法比较返回值。

public V put(K key, V value) {
    return putVal(key, value, false);
}

/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
    if (key == null || value == null) throw new NullPointerException();
	//hash = (h ^ (h >>> 16)) & HASH_BITS
    int hash = spread(key.hashCode());
    int binCount = 0;
    for (Node<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;
        if (tab == null || (n = tab.length) == 0)
            tab = initTable();
		//数组下标 i = (n-1) & hash,通过tabAt和casAt方法定位节点,
		//为空就创建一个新节点并存储数据
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            if (casTabAt(tab, i, null,
                         new Node<K,V>(hash, key, value, null)))
                break;                   // no lock when adding to empty bin
        }
		//若数组在调整大小,当前节点需要进行变动
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);
        else {
            V oldVal = null;
			//使用synchronized关键字锁住当前节点,防止其他线程占用
            synchronized (f) {
                if (tabAt(tab, i) == f) {
					//若是链表节点,遍历链表,通过key.equals()方法命中节点并赋值,
					//若存在旧值进行覆盖
                    if (fh >= 0) {
                        binCount = 1;
                        for (Node<K,V> e = f;; ++binCount) {
                            K ek;
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) {
                                oldVal = e.val;
                                if (!onlyIfAbsent)
                                    e.val = value;
                                break;
                            }
                            Node<K,V> pred = e;
                            if ((e = e.next) == null) {
                                pred.next = new Node<K,V>(hash, key,
                                                          value, null);
                                break;
                            }
                        }
                    }
					//若当前节点是红黑树节点,通过遍历红黑树,根据key和hash找到节点位置赋值,
					//若存在旧值进行覆盖
                    else if (f instanceof TreeBin) {
                        Node<K,V> p;
                        binCount = 2;
                        if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                       value)) != null) {
                            oldVal = p.val;
                            if (!onlyIfAbsent)
                                p.val = value;
                        }
                    }
                }
            }
			//若数量超过树的阈值默认8,进行扩容
            if (binCount != 0) {
                if (binCount >= TREEIFY_THRESHOLD)
                    treeifyBin(tab, i);
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }
    addCount(1L, binCount);
    return null;
}

put过程大概如下:

  1. 根据key和key计算出的hash值去定位节点
  2. 若未发生碰撞,直接创建新节点并存储数据
  3. 若碰撞且数组正在调整大小,通过自旋方法保证写入
  4. 若都不满足,通过synchronized关键字锁住当前节点,写入数据
  5. 如果数量大于 TREEIFY_THRESHOLD 则要转换为红黑树,再通过树的方式写入数据

参考链接

  1. HashMap? ConcurrentHashMap? 相信看完这篇没人能难住你!
  2. Java-HashMap工作原理及实现
posted @ 2019-07-03 18:35  universal  阅读(198)  评论(0编辑  收藏  举报