本文共 5694 字,大约阅读时间需要 18 分钟。
一、引子:List 删除
public static void main(String args[]) { List<String> lst = new ArrayList<String>(); lst.add("first"); lst.add("second"); lst.add("third"); lst.add("four"); lst.add("five"); lst.add("six"); lst.add("seven"); lst.add("eight"); //方法1:foreach /* for (String s : lst) { System.out.println("s = " + s); lst.remove(s); }*/ //方法2:普通for /* for (int i = 0 ; i < lst.size(); i++) { System.out.println("s = " + lst.get(i)); lst.remove(lst.get(i)); } System.out.println("lst.size = " + lst.size());*/ //方法3:iterator for(Iterator it = lst.iterator(); it.hasNext();) { System.out.println("curString = " + it.next()); it.remove(); } System.out.println("lst.size = " + lst.size()); } |
方法1:foreach方法
报错:Exception in thread "main" java.util.ConcurrentModificationException
原因:
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } |
Foreach原理其实也是iterator。按道理说不会报错,但是确实会报错。报错的不是remove,是在foreach第二次的时候,因为每次foreach都要取值,取值时会进行一次校验,代码如上,此时的modCount为9,而expectedModCount为8,不等,所以抛出异常。
方法2:不会抛出异常,单不会全部删除,只会删除一部分,不是我们要的结果,如下:
方法3: 正常用法
现在对上述的结果进行一次解释。
private class Itr implements Iterator { int cursor = 0; int lastRet = -1; int expectedModCount = modCount; } |
Itr类依靠3个int变量(还有一个隐含的AbstractList的引用)来实现遍历,cursor是下一次next()调用时元素的位置,第一次调用next()将返回索引为0的元素。lastRet记录上一次游标所在位置,因此它总是比cursor少1。
变量cursor和集合的元素个数决定hasNext(): public boolean hasNext() { return cursor != size(); } |
方法next()返回的是索引为cursor的元素,然后修改cursor和lastRet的值:
public Object next() { checkForComodification(); try { Object next = get(cursor); lastRet = cursor++; return next; } catch(IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } |
expectedModCount表示期待的modCount值,用来判断在遍历过程中集合是否被修改过。AbstractList包含一个modCount变量,它的初始值是0,当集合每被修改一次时(调用add,remove等方法),modCount加1。因此,modCount如果不变,表示集合内容未被修改。
Itr初始化时用expectedModCount记录集合的modCount变量,此后在必要的地方它会检测modCount的值: final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } |
如果modCount与一开始记录在expectedModeCount中的值不等,说明集合内容被修改过,此时会抛出ConcurrentModificationException。
这个ConcurrentModificationException是RuntimeException,不要在客户端捕获它。如果发生此异常,说明程序代码的编写有问题,应该仔细检查代码而不是在catch中忽略它。 但是调用Iterator自身的remove()方法删除当前元素是完全没有问题的,因为在这个方法中会自动同步expectedModCount和modCount的值: public void remove() { ... AbstractList.this.remove(lastRet); ... // 在调用了集合的remove()方法之后重新设置了expectedModCount: expectedModCount = modCount; ... } |
要确保遍历过程顺利完成,必须保证遍历过程中不更改集合的内容(Iterator的remove()方法除外),因此,确保遍历可靠的原则是只在一个线程中使用这个集合,或者在多线程中对遍历代码进行同步。
而普通的remove方法没有对expectedModCount进行处理,而forreach在每次取元素时,相当于内部有事iterator.next()去取值,
而,next代码如下:
public E next() { checkForComodification(); try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } |
它会进行checkForComodification检查,显然此时的modCount != expectedModCount,所以抛出异常也就不足为奇了。
二、CopOnWriteArrayList
/** * 线程一去遍历集合,get元素 */ class Thread1 implements Runnable { private List<String> lst; Thread1(List<String> lst) { this.lst = lst; } public void run() { methodFor(); // methodIterator(); } //迭代器遍历的方式 private void methodIterator() { Iterator iterator = lst.iterator(); while (iterator.hasNext()) { String cur = (String) iterator.next(); //java.util.ConcurrentModificationException try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } System.out.println("remove :" + cur); } } //for-eache的方式 private void methodFor() { for (String cur : lst) { //java.util.ConcurrentModificationException try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("cur:" + cur.toString()); } } } |
/** * 用CopyOnWriteArrayList的方式 ,读取和remove的操作互不影响 */ class Thread3 implements Runnable { private CopyOnWriteArrayList<String> lst; Thread3(CopyOnWriteArrayList<String> lst) { this.lst = lst; } public void run() { removeCopyOnWrite(); } private void removeCopyOnWrite() { for (String cur : lst) { System.out.println("remove :" + cur); lst.remove(cur); } } } |
public static void main(String args[]) { CopOnWriteArrayListTest copOnWriteArrayListTest = new CopOnWriteArrayListTest(); // List<String> lst = new ArrayList<String>(); CopyOnWriteArrayList<String> lst = new CopyOnWriteArrayList<String>(); lst.add("zhangsan"); lst.add("lisi"); lst.add("wangwu"); lst.add("zhaoliu"); Thread thread1 = new Thread(copOnWriteArrayListTest.new Thread1(lst)); Thread thread2 = new Thread(copOnWriteArrayListTest.new Thread2(lst)); Thread thread3 = new Thread(copOnWriteArrayListTest.new Thread3(lst)); thread1.start(); // thread2.start(); thread3.start(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } System.out.println(lst.isEmpty()); for(String cur: lst) { System.out.println("main cur:" +cur); } |
结果:
remove :zhangsan remove :lisi remove :wangwu remove :zhaoliu cur:zhangsan cur:lisi true cur:wangwu cur:zhaoliu |
两个线程:一个线程循环遍历get,一个线程循环remove,看打印结果:get和remove互不影响,但最终的结果判断lst是否为空却是为空的。这就是CopyOnWriteArrayList的效果。
CopyOnWriteArrayList用于替代同步List,在某些情况下它提供了更好的并发性能,并且在迭代期间不需要对容器进行加锁或复制。
“写入时复制(Copy-On-Write)”容器的线程安全性在于,只要正确地发布一个事实不可变的对象,那么在访问该对象时就不再需要进一步的同步。在每次修改时,都会创建并重新发布一个新的容器副本,从而实现可变性。“写入时复制”容器的迭代器保留一个指向底层基础数组的引用,这个数组当前位于迭代器的起始位置,由于它不能被修改,因此在对其进行同步时只需确保数组内容的可见性。因此,多个线程可以同时对这个容器进行迭代,而不会彼此干扰或者与修改容器的线程相互干扰。“写入时复制”容器返回的迭代器不会抛出ConcurrentModifactionException,并且返回的元素与迭代器创建时的元素完全一致,而不必考虑之后修改操作所带来的影响。
显然,每当修改容器时都会复制底层数组,这需要一定开销,特别是当容器的规模比较大时。仅当迭代操作远远多于修改操作时,才应该使用“写入时复制”容器。
转载地址:http://dwrrb.baihongyu.com/