大话多线程下集合类如何生存,那些事

你常用的集合类是啥?—ArrayList,HashSet,HashMap
1、单机版这肯定没啥问题,多线程环境下还好使吗?
2、有啥解决方案不?
3、为啥这种方案好使?
面对这一串三连问,有多少人能扛得住~且听我细细道来。。。

		List<String> list= new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(Thread.currentThread().getName()+"————————"+list);
            },String.valueOf(i)).start();
        }
        //30个线程同时插入数据到list
    运行结果: -Exception in thread "4" java.util.ConcurrentModificationException
    //不加锁-线程1正在对一个对象写,线程2抢夺此对象、导致数据不一致
	
	public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    //追踪源码发现,不加任何锁~

有三种解决方案
1、List list= new Vector<>();
2、List list= Collections.synchronizedList(new ArrayList<>());
3、List list= new CopyOnWriteArrayList<>()

	// new Vector<>(); 源码如下,发现有 synchronized 
	public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        //  protected Object[] elementData; 缺点:全局对象,synchronized 锁导致只能写或者读
        
        return true;
    }
    //Collections.synchronizedList(new ArrayList<>()); 追踪发现也有 synchronized 
    public List<E> subList(int fromIndex, int toIndex) {
            synchronized (mutex) {
                return new SynchronizedList<>(list.subList(fromIndex, toIndex),
                                            mutex);
            }
     }

对于1,2解决方案不在多说,synchronized 起了关键作用,那么3又是如何的呢 ?

	// 写时复制 读写分离--ReentrantLock
	public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            //线程1--copy原有数组,在最下边加一个
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            //替换原有数组
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }
    // setArray(newElements);
	final void setArray(Object[] a) {
        array = a;
    }

对于这段代码通过图片理解,
在这里插入图片描述
通过图片结合代码发现,线程1 --add时、上锁,copy 原有数组、后边加一个,没有对原有对象 Object[] 整体加锁,保证了并发读不受影响、进一步保证了读写分离。
在这里插入图片描述
二、举一反三、new HashSet<>(); 存在同样的问题
Set set=new HashSet<>();
解决方案:
1、 set=Collections.synchronizedSet(new HashSet<>());
2、 set= new CopyOnWriteArraySet<>();

	//HashSet
	public HashSet() {
        map = new HashMap<>();
    }
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
     private static final Object PRESENT = new Object();
// CopyOnWriteArraySet
  private boolean addIfAbsent(E e, Object[] snapshot) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] current = getArray();
            int len = current.length;
            if (snapshot != current) {
                // Optimize for lost race to another addXXX operation
                int common = Math.min(snapshot.length, len);
                for (int i = 0; i < common; i++)
                    if (current[i] != snapshot[i] && eq(e, current[i]))
                        return false;
                if (indexOf(e, current, common, len) >= 0)
                        return false;
            }
            Object[] newElements = Arrays.copyOf(current, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }
     

通过源码发现原理都一样,不过有个意外的发现。。HashSet 底层是hashmap,\add(E e) 添加的是key,value是一个常量–static final Object PRESENT = new Object();

三、举一反三、new HashMap<>(); 存在同样的问题
Map<String,Object> map=new HashMap<>();
解决方案:
1、map=Collections.synchronizedMap(new HashMap<String,Object>());
2、 map=new ConcurrentHashMap<>();

	public boolean add(K e) {
            V v;
            if ((v = value) == null)
                throw new UnsupportedOperationException();
            return map.putVal(e, v, true) == null;
     }

	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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值