面试官问你HashMap底层你用线程安全吊打他

254 阅读3分钟

面试中,HashMap可以说是必问的,既然这样,我们应该怎么准备怎么回答呢,看看这篇文章,估计你会懂点东西。
先看看这两张图,是其内部的存储结构
在这里插入图片描述
在这里插入图片描述
说起HashMap,我们可以先从底层实现说起,HashMap是通过hash算法,基于数组、链表和红黑树实现的,hash算法是一种思想,只要符合该思想的算法都是hash算法,其核心就是给定一个key,通过hash可以对应一个h(key),举个例子就是当我们要存储一个key为字符串的一组数据,那么我们就可以通过hash将key转化为数字,做为数组的索引,然后将value存入该索引所对应的空间内,如果我们的数组长度是16,那么当有20个key来进行hash的时候,肯定存在冲突,也就是h(key1) = h (key2),此时解决的办法就是,让该索引指向一个链表,这样就可以让不同的key对应同一个h(key),获取的时候通过该key确定到某一个索引,然后遍历链表,但是当链表数据量很大的时候,遍历是很耗时的,于是红黑树就出现了,当链表元素大于等于8个的时候,就采用红黑树去存储,时间复杂度直接从O(n)降低到了O(logn)。
说到这,HashMap的核心思想也就差不多了,这些应该大部分人都知道,现在来点亮点,你可以说HashMap线程不安全,然后给他来这个例子进行演示,创建三个线程,同时去访问put方法

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TestHashMap implements Runnable {
    static Map<String,Object> map = new HashMap();
    //static Map<String,Object> map = new ConcurrentHashMap<>();

    @Override
    public void run() {
        for (int i = 0; i < 100; i ++) {
            map.put(i + "", "hello");
        }
    }

    public static void main(String[] args){
        Thread thread1 = new Thread(new TestHashMap());
        Thread thread2 = new Thread(new TestHashMap());
        Thread thread3 = new Thread(new TestHashMap());


        thread1.start();
        thread2.start();
        thread3.start();
        Thread currentThread = Thread.currentThread();
        try {
            currentThread.sleep(2000);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println(map.size());
    }
}

按正常来说应该输出100的,但是这里并没有,而是输出了204
在这里插入图片描述
你可以给put方法上锁,用synchronized

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TestHashMap implements Runnable {
    static Map<String,Object> map = new HashMap();
    //static Map<String,Object> map = new ConcurrentHashMap<>();

    @Override
    public void run() {
        for (int i = 0; i < 100; i ++) {
            synchronized (TestHashMap.class) { // 这里!!!
                map.put(i + "", "hello");
            }
        }
    }

    public static void main(String[] args){
        Thread thread1 = new Thread(new TestHashMap());
        Thread thread2 = new Thread(new TestHashMap());
        Thread thread3 = new Thread(new TestHashMap());


        thread1.start();
        thread2.start();
        thread3.start();
        Thread currentThread = Thread.currentThread();
        try {
            currentThread.sleep(2000);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println(map.size());
    }
}

这样是可以解决线程问题,但是,你这有点暴力了吧,直接把整个put方法都给上锁了,你看看put方法中有多少代码,都给锁上,有点过分
Hash Map的put源码

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

    /**
     * Implements Map.put and related methods.
     *
     * @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;
        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;
    }

好家伙,你这一锁,都给锁上了,不好,于是来了ConcurrentHashMap,线程安全的,先看看人家是怎么锁的

    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();
        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();
            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 (f) { // 在这!!!!!!!!!!!!
                    if (tabAt(tab, i) == f) {
                        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;
                                }
                            }
                        }
                        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;
                            }
                        }
                    }
                }
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

这样一来,锁的就少了,效率当然也就高了,说实话,用着也方便,下面来展示高端操作

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TestHashMap implements Runnable {
    //static Map<String,Object> map = new HashMap();
    static Map<String,Object> map = new ConcurrentHashMap<>();

    @Override
    public void run() {
        for (int i = 0; i < 100; i ++) {
            map.put(i + "", "hello");
        }
    }

    public static void main(String[] args){
        Thread thread1 = new Thread(new TestHashMap());
        Thread thread2 = new Thread(new TestHashMap());
        Thread thread3 = new Thread(new TestHashMap());


        thread1.start();
        thread2.start();
        thread3.start();
        Thread currentThread = Thread.currentThread();
        try {
            currentThread.sleep(2000);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println(map.size());
    }
}

在这里插入图片描述
最后,如果考虑线程安全,ConcurrentHashMap香呀。