• 第五章:(3)HashMap 集合线程不安全&解决方案


    一、HashMap 是不安全的

      1、故障现象

    public class NotSafeMapDemo {
    
        public static void main(String[] args) {
            Map<String, String> map = new HashMap<>();
    
            for (int i = 0; i < 30; i++) {
                String key = String.valueOf(i);
                new Thread(() -> {
                    //向集合添加内容
                    map.put(key, UUID.randomUUID().toString().substring(0, 8));
                    //从集合获取内容
                    System.out.println(map);
                }, String.valueOf(i)).start();
            }
        }
    }

      运行结果:

      

      2、分析原因

      HashMap 的 put 的方法是没有使用同步锁的,也就意味着在多线程情况下会出现问题:

      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;   //在这里会对 modCount 进行++操作
            if (++size > threshold)
                resize();
            afterNodeInsertion(evict);
            return null;
        }    

      以 KeySet 的的遍历为例:

        final class KeySet extends AbstractSet<K> {
            public final int size()                 { return size; }
            public final void clear()               { HashMap.this.clear(); }
            public final Iterator<K> iterator()     { return new KeyIterator(); }
            public final boolean contains(Object o) { return containsKey(o); }
            public final boolean remove(Object key) {
                return removeNode(hash(key), key, null, false, true) != null;
            }
            public final Spliterator<K> spliterator() {
                return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
            }
            public final void forEach(Consumer<? super K> action) {
                Node<K,V>[] tab;
                if (action == null)
                    throw new NullPointerException();
                if (size > 0 && (tab = table) != null) {
                    int mc = modCount;
                    for (int i = 0; i < tab.length; ++i) {
                        for (Node<K,V> e = tab[i]; e != null; e = e.next)
                            action.accept(e.key);
                    }
                    if (modCount != mc)
                        throw new ConcurrentModificationException();
                }
            }
        }

        这里会先记录一下原先的 modCount 值,如果此时有一个线程对 Map 进行 put,modCount值就会 ++,就满足了 if 的条件,然后就抛出异常。

    二、方案一

      1、使用 HashTable

      Hashtable容器使用 synchronized 来保证线程安全,但在线程竞争激烈的情况下Hashtable的效率非常低下。

      因为当一个线程访问 Hashtable 的同步方法时,其他线程访问 Hashtable 的同步方法时,可能会进入阻塞或轮询状态。如线程1使用put进行添加元素,线程2不但不能使用put方法添加元素,并且也不能使用get方法来获取元素,所以竞争越激烈效率越低。

        /**
         * Maps the specified <code>key</code> to the specified
         * <code>value</code> in this hashtable. Neither the key nor the
         * value can be <code>null</code>. <p>
         *
         * The value can be retrieved by calling the <code>get</code> method
         * with a key that is equal to the original key.
         *
         * @param      key     the hashtable key
         * @param      value   the value
         * @return     the previous value of the specified key in this hashtable,
         *             or <code>null</code> if it did not have one
         * @exception  NullPointerException  if the key or value is
         *               <code>null</code>
         * @see     Object#equals(Object)
         * @see     #get(Object)
         */
        public synchronized V put(K key, V value) {
            // Make sure the value is not null
            if (value == null) {
                throw new NullPointerException();
            }
    
            // Makes sure the key is not already in the hashtable.
            Entry<?,?> tab[] = table;
            int hash = key.hashCode();
            int index = (hash & 0x7FFFFFFF) % tab.length;
            @SuppressWarnings("unchecked")
            Entry<K,V> entry = (Entry<K,V>)tab[index];
            for(; entry != null ; entry = entry.next) {
                if ((entry.hash == hash) && entry.key.equals(key)) {
                    V old = entry.value;
                    entry.value = value;
                    return old;
                }
            }
    
            addEntry(hash, key, value, index);
            return null;
        }

      2、代码实现

    public class SafeMapDemo {
    
        public static void main(String[] args) {
            Map<String,String> map = new Hashtable<>();
    
            for (int i = 0; i <30; i++) {
                String key = String.valueOf(i);
                new Thread(()->{
                    //向集合添加内容
                    map.put(key, UUID.randomUUID().toString().substring(0,8));
                    //从集合获取内容
                    System.out.println(map);
                },String.valueOf(i)).start();
            }
        }
    }

    三、方案二

      1、使用 Collections 工具类

      Collections 工具类也提供了线程安全的 Map 集合。

      2、代码实现

    public class SafeMapDemo {
    
        public static void main(String[] args) {
            Map<String,String> map = Collections.synchronizedMap(new HashMap<>());
    
            for (int i = 0; i <30; i++) {
                String key = String.valueOf(i);
                new Thread(()->{
                    //向集合添加内容
                    map.put(key, UUID.randomUUID().toString().substring(0,8));
                    //从集合获取内容
                    System.out.println(map);
                },String.valueOf(i)).start();
            }
        }
    }

    四、方案三

      1、使用 ConcurrentHashMap

      ConcurrentHashMap 是一个并发散列映射表,它允许完全并发的读取,并且支持给定数量的并发更新。

      2、代码实现

    public class SafeMapDemo {
    
        public static void main(String[] args) {
    
            Map<String,String> map = new ConcurrentHashMap<>();
            for (int i = 0; i <30; i++) {
                String key = String.valueOf(i);
                new Thread(()->{
                    //向集合添加内容
                    map.put(key, UUID.randomUUID().toString().substring(0,8));
                    //从集合获取内容
                    System.out.println(map);
                },String.valueOf(i)).start();
            }
        }
    }

      3、原理分析

      参考博客:https://www.jianshu.com/p/d0b37b927c48

    五、小结

      1、线程安全与线程不安全集合

        集合类型中存在线程安全域线程不安全的两种,常见例如:

        ArrayList —— Vector

        HashMap —— HashTable

        但是以上都是通过 synchronized 关键字实现,效率较低。

      2、Collections 工具类构建的线程安全集合

        这种方式也是通过 synchronized 的方式来构建一个线程安全的集合,效率不高。

      3、使用 java.util.concurrent 并发包下

        CopyOnWriteArrayList、CopyOnWriteArraySet 类型,通过动态数组与线程安全个方面保证线程安全;

        ConcurrentHashMap 使用分段锁来保证 Map 的多线程安全。

  • 相关阅读:
    perl学习笔记之:正则表达式
    POJ 3436 ACM Computer Factory (拆点+输出解)
    POJ 3436 ACM Computer Factory (拆点+输出解)
    POJ 1637 Sightseeing tour ★混合图欧拉回路
    POJ 1637 Sightseeing tour ★混合图欧拉回路
    POJ 1149 PIGS ★(经典网络流构图)
    POJ 1149 PIGS ★(经典网络流构图)
    HDU 4571 Travel in time ★(2013 ACM/ICPC长沙邀请赛)
    HDU 4571 Travel in time ★(2013 ACM/ICPC长沙邀请赛)
    UPC 2224 Boring Counting ★(山东省第四届ACM程序设计竞赛 tag:线段树)
  • 原文地址:https://www.cnblogs.com/niujifei/p/15828452.html
Copyright © 2020-2023  润新知