java List 线程安全

我们常用的ArrayList,LinkedList都不是线程安全的的List,为什么这么说:

    /**
     * A counter for changes to the list.
     */
    protected transient int modCount;
这是他们的父类  AbstractList 中的属性,含义就是用来标记当前修改次数,用于在遍历数据时保证数据的一致性;

<span style="white-space:pre">	</span>public E next() {
            if (expectedModCount == modCount) {
                try {
                    E result = get(pos + 1);
                    lastPosition = ++pos;
                    return result;
                } catch (IndexOutOfBoundsException e) {
                    throw new NoSuchElementException();
                }
            }
            throw new ConcurrentModificationException();
        }
那如何保证List的线程安全呢,调用Collections.synchronizedList(new ArrayList());

    /**
     * Returns a wrapper on the specified List which synchronizes all access to
     * the List.
     *
     * @param list
     *            the List to wrap in a synchronized list.
     * @return a synchronized List.
     */
    public static <T> List<T> synchronizedList(List<T> list) {
        if (list == null) {
            throw new NullPointerException("list == null");
        }
        if (list instanceof RandomAccess) {
            return new SynchronizedRandomAccessList<T>(list);
        }
        return new SynchronizedList<T>(list);
    }
他的实现原理其实就是添加了 synchronized 同步串以保证线程安全。
        @Override public boolean add(E object) {
            synchronized (mutex) {
                return c.add(object);
            }
        }




  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值