JUC-集合类线程不安全问题

先来看:对一个ArrayList做一个并发写操作

List<String> list =new ArrayList<>();
        //通过多线程来证明
        for (int i = 1; i <= 90; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }

运行直接报错java.util.ConcurrentModificationException并发写操作异常

查看Arraylist中add源码:

在这里插入图片描述
1:很明显可以看到并没有对线程进行安全处理;
2:在ensureCapacityInternal方法中与HashMap采用Fast-Fail机制,每次对ArrayList做修改都会增加modCount这个值,且在迭代器初始化的时候将modCount赋值给expectedModCount,在迭代过程中,判断modCount跟expectedModCount是否相等,如果不相等就表示已经有其他线程修改了数组,马上抛出ConcurrentModificationException异常
抛出并发异常的ArrayLisit中的源码:

private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        //赋值
        int expectedModCount = modCount;
        s.defaultWriteObject();

        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }
		//判断判断modCount跟expectedModCount是否相等
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }
那如何解决呢:

1:使用Vector

可以看到Vector与ArrayList 相关之间的关系:
在这里插入图片描述
Vector可以看到和ArrayList实现和继承的是一样,不同的是Vector是线程安全的,因为其内部 有很多同步代码来保证线程安全
解决上面的并发写入的问题:查看Vector的add源码:
在这里插入图片描述
与上面ArrayList的源码相比,进行了同步,但是这样也是有一个问题:就是这样同步锁的是这个对象this,所以当一个线程进来进行写还没出去之前,其他线程是无法进入这个对象的其他synchronized方法,查看其源码,对List的基本操作都进行了同步,所以效率上来说的话是慢的,比如你进行写的时候是无法进行读,删…,且Vector就是ArrayList的前身,比较老,JDK1.0

但是其确实是能解决我们上面的问题并发写异常:

 Vector<String>list= new Vector<>();

        for (int i = 1; i <= 90; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }
  • 运行无异常

JUC也是给我们提供了Collection工具类来创建线程安全的List,

 List<String> list= Collections.synchronizedList(new ArrayList<>
        for (int i = 1; i <= 90; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }

查看其源码其实也是底层也是synchronize,只不过Vector是采用同步方法,而Collection返回的线程安全是采用同步代码块;
让我们进入源码:

 List<String> list= Collections.synchronizedList(new ArrayList<>());

查看synchronizedList方法:

public static <T> List<T> synchronizedList(List<T> list) {
        return (list instanceof RandomAccess ?
                new SynchronizedRandomAccessList<>(list) :
                new SynchronizedList<>(list));
    }

    static <T> List<T> synchronizedList(List<T> list, Object mutex) {
        return (list instanceof RandomAccess ?
                new SynchronizedRandomAccessList<>(list, mutex) :
                new SynchronizedList<>(list, mutex));
    }

可以看到可以必须传入一个List对象,mutex锁可以 选择性传入,因为不传后面是将自己的this引用作为锁
我们传入的是ArrayList对象,ArrayList对象是实现了RandomAccss接口的,所以返回的对象是:new SynchronizedRandomAccessList<>(list)
这个是这个类的源码:

static class SynchronizedRandomAccessList<E>
        extends SynchronizedList<E>
        implements RandomAccess {

        SynchronizedRandomAccessList(List<E> list) {
            super(list);
        }

        SynchronizedRandomAccessList(List<E> list, Object mutex) {
            super(list, mutex);
        }

        public List<E> subList(int fromIndex, int toIndex) {
            synchronized (mutex) {
                return new SynchronizedRandomAccessList<>(
                    list.subList(fromIndex, toIndex), mutex);
            }
        }

        private static final long serialVersionUID = 1530674583602358482L;

        /**
         * Allows instances to be deserialized in pre-1.4 JREs (which do
         * not have SynchronizedRandomAccessList).  SynchronizedList has
         * a readResolve method that inverts this transformation upon
         * deserialization.
         */
        private Object writeReplace() {
            return new SynchronizedList<>(list);
        }
    }

其实继承了SynchronizedList,实现implements RandomAccess,所以这里内容对我们意义不大,主要是实现RandomAccess接口提供了随机访问功能
可以看到构造方法是将List传给其父类SynchronizedList,接下来我们得进入其父类:在这里插入图片描述

可以看到,我们如果使用JUC工具类Collection为我们返回的线程安全List其实也是通过synchronized同步代码块来实现,因为我们没有传入mutex,接下来看看其默认的锁是啥吧?

通过其构造方法可以看到锁传入的是其父类:

SynchronizedList(List<E> list) {
            super(list);
            this.list = list;
        }
        SynchronizedList(List<E> list, Object mutex) {
            super(list, mutex);
            this.list = list;
        }

接下来进入其父类SynchronizedCollection:

在这里插入图片描述
通过构造方法可以看到mutex锁默认就是this,也就是其自身;且可以指定mutex锁的对象。
那将Collection工具类返回的SynchronizedList与Vector做对比:

  • SunchronizedList相对于Vector来说,提供了很扩张兼容性,他可以将所有的List的子类转换成线程安全的对象,比如我们如果有个需求是:增删频繁需要使用到数组,那么我们可以将LinkList传入返回SunchronizedList,不用改变底层的实现,而Vector的话底层的结构就是数组实现,如果增删频繁的话效率的损失也是很大,因为需要平凡移动数组的元素不灵活
  • SynchronizedList可以指定锁定的对象,更加灵活

同时通过Collection工具类我们也可以反推很多集合类是不安全的
在这里插入图片描述

但是Vector与SunchronizedList的缺陷刚刚也说了,就是当进入锁区域后,其他线程无法在进入其他的同步方法,也就是比如进行写的时候,无法进行读;那是否有更好的解决办法,那就是使用JUC给我们提供的写时复制List进行读写分离:CopyOnWriteArrayList

简单来说不加锁性能提升出错误,加锁数据一致性能下降
使用学时复制实现写线程的独占性,读线程的共享性

CopyOnWriteArrayList

Api文档中对其的解释:

  • A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.
  • 其中所有可变操作(add、set等)都是通过生成底层数组的新副本来实现的。
    查看其源码:
public class CopyOnWriteArrayList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    private static final long serialVersionUID = 8673264195747942595L;

    /** The lock protecting all mutators */
    final transient ReentrantLock lock = new ReentrantLock();

    /** The array, accessed only via getArray/setArray. */
    private transient volatile Object[] array;
			..........

    private E get(Object[] a, int index) {
        return (E) a[index];
    }

public E set(int index, E element) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            E oldValue = get(elements, index);

            if (oldValue != element) {
                int len = elements.length;
                Object[] newElements = Arrays.copyOf(elements, len);
                newElements[index] = element;
                setArray(newElements);
            } else {
                // Not quite a no-op; ensures volatile write semantics
                setArray(elements);
            }
            return oldValue;
        } finally {
            lock.unlock();
        }
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }


单独列出了读操作get与写操作set/add

 /** The array, accessed only via getArray/setArray. */
    private transient volatile Object[] array;

可以看到变量数组使用volatile关键字:变换的时候都会去通知别的线程i值变了。

首先写操作的话:

-1: 上锁

  • 2:对正本数组进行复制出了一个副本newElements
  • 3:将需要写入的数据添加入副本
  • 4:将副本设置为正本
  • 5:解锁

而读操作get:

private E get(Object[] a, int index) {
        return (E) a[index];
    }

可以看到 其并未做线程安全,也就是其可以异步

总结其原理

但凡发现有人要写了,就拷贝一份写,旧的那一份给其他线程进行读操作;
当写操作完成后,把所有读的线程让其读最新的副本;以次类推

最后使用其之前完成并发写入:

List<String> list =new CopyOnWriteArrayList<>();

        for (int i = 1; i <= 90; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值