集合类不安全之HashMap

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/longgeqiaojie304/article/details/89819450

大厂面试题:我们知道HashMap是线程不安全的,请编码写一个不安全的案例并给出解决方案?

1、HashMap线程不安全问题产生

import java.util.*;

 

public class ContainerNotSafeHashMapDemoThree {

    public static void main(String[] args) {

        Map<String, String> map = new HashMap<>();

        for (int i = 0; i < 30; i++) {

            new Thread(() -> {

                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString());

                System.out.println(map.toString());

            }, String.valueOf(i)).start();

        }

    }

}

程序执行结果如下:报java.util.ConcurrentModificationException异常

2、ConcurrentModificationException产生的原因

一个线程正在写,另一个线程过来抢占资源,会造成数据不一致,进而报并发修改异常。

 

3、HashMap线程不安全解决方案

(1)第一种解决方案

使用Collections工具类创建同步集合类

 

import java.util.Collections;

import java.util.HashMap;

import java.util.Map;

import java.util.UUID;

import java.util.concurrent.ConcurrentHashMap;

 

public class ContainerSafeHashMapDemoOne {

    public static void main(String[] args) {

        Map<String, String> map = Collections.synchronizedMap(new HashMap<>());

        for (int i = 0; i < 30; i++) {

            new Thread(() -> {

                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString());

                System.out.println(map.toString());

            }, String.valueOf(i)).start();

        }

    }

}

(2)第二种解决方案

使用并发编程类ConcurrentHashMap替换HashMap

 

import java.util.Map;

import java.util.Set;

import java.util.UUID;

import java.util.concurrent.ConcurrentHashMap;

 

public class ContainerSafeHashMapDemoTwo {

    public static void main(String[] args) {

        Map<String, String> map = new ConcurrentHashMap<>();

        for (int i = 0; i < 30; i++) {

            new Thread(() -> {

                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString());

                System.out.println(map.toString());

            }, String.valueOf(i)).start();

        }

    }

}

 

ConcurentHashMap底层使用的是分段锁

 

    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;

    }

 

 

猜你喜欢

转载自blog.csdn.net/longgeqiaojie304/article/details/89819450