Java沉思录之HashMap源码浅析

Question

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

Answer

1. HashMap的使用场景

当程序需要存储一些键值对,例如数据字典,全局参数等类型变量时,可使用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的线程安全性

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

猜你喜欢

转载自www.cnblogs.com/universal/p/11128264.html