1.1 ArrayList的线程安全
ArrayList类中,add方法等并没有添加 synchronized 关键字
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true;}
那么我们在添加的时候,如果并发读和写的话,会出现并发读写的异常。 java.util.ConcurrentModificationException。 异常核心出现在:
private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; Itr() {} public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
出现的原因:
- 我们使用多个线程进行添加数据。因为ArrayList是有序的集合,每次添加后会对集合进行排序,添加上当前元素的下一个元素。
每次添加元素后,设置其next元素的时候,会进行下一个元素检查:checkForComodification方法。
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException();}
也就是会校验:当前已经修改列表的次数 count 和 排序的时候传入的修改列表的 count 是否一致,如果不一致,就会抛出并发修改的异常!
- 如果没有并发修改,那么 modCount = expectedModCount
- 如果在进行下一个next元素设置的过程中又修改了集合,则会报:ConcurrentModificationException。
1.2 集合线程安全问题的解决方案
1.2.1 Vector
Vector也是List的一个实现类,是一个线程安全的。实现关系是: public class Vector extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{ public synchronized void addElement(E obj) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = obj; }}
- 通过上面的代码我们可以发现:Vector是线程安全的,使用了 synchronized 关键字进行修饰。
- 因为这个效率不高,每次都进行加锁解锁,所以我们通常用的不过。
1.2.2 Collctions方法
使用 Collection