ava.util.ConcurrentModificationException 异常

<span style="line-height: 1.875; white-space: pre-wrap; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">问题场景</span>
jdk1.7:
多线程下使用Collection.sort() OK
切换到jdk1.8 的时候,出现 java.util.ConcurrentModificationException异常

解决办法:查看jdk1.7Collection的源码:
public static <T extends Comparable<? super T>> void sort(List<T> list) {
    Object[] a = list.toArray();
    Arrays.sort(a);
    ListIterator<T> i = list.listIterator();
    for (int j=0; j<a.length; j++) {
        i.next();
        i.set((T)a[j]);
    }
}


jdk1.8版本:
Collections.sort()
    public static <T extends Comparable<? super T>> void sort(List<T> list) {
        list.sort(null);
    }

List.sort()
    @SuppressWarnings({"unchecked", "rawtypes"})
    default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }



我使用的list类型为ArrayList,查看ArrayList的sort源码:

  @Override
    @SuppressWarnings("unchecked")
    public void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }



抛出异常的情况就是并发情况下,第一个集合sort之后,modcount++ 值发生变化了,第二个线程进来对比就抛异常(sort线程不安全)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值