今天执行了一段《图解多线程设计模式》中的代码,结果抛出了如下的异常:
Exception in thread "ReaderThread" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at com.chapter1.part2.part4to6.ReaderThread.run(ReaderThread.java:13)
现把源代码贴出来:
/**
* 该线程类主要负责向List集合中添加数据
*/
public class WriterThread extends Thread{
private final List<Integer> list;
public WriterThread(List<Integer> list){
super("WriterThread");
this.list=list;
}
public void run(){
for(int i=0;true;i++){
list.add(i);
}
}
}
/**
* 该线程类主要负责遍历并打印List集合中的数据
*/
public class ReaderThread extends Thread {
private final List<Integer> list;
public ReaderThread(List<Integer> list){
super("ReaderThread");
this.list=list;
}
public void run(){
while(true){
for(int n:list){
System.out.println(n);
}
}
}
}
public class Main {
public static void main(String[] args) {
List<Integer> list=new ArrayList<>();
new WriterThread(list).start();
new ReaderThread(list).start();
}
}
分析:
通过javap -c来对字节码文件进行反编译,结果如图1:
咱先不分析上面反编译的结果,先看下一段代码以及对它反编译的结果,如图2:
import java.util.List;
import java.util.Iterator;
public class ReaderThread extends Thread {
private final List<Integer> list;
public ReaderThread(List<Integer> list){
super("ReaderThread");
this.list=list;
}
public void run(){
Iterator<Integer> strs = list.iterator();
while(true){
while(strs.hasNext()){
System.out.println(strs.next());
}
}
}
}
比较图1和图2发现,图1中InterfaceMethod也是采用Iterator,即增强for循环的底层采用Iterator进行遍历集合元素的;即通过调用hasNext()来判断是否还存在元素,通过调用next()来获取元素。
问题:java.util.ConcurrentModificationException是如何产生的
既然底层采用的是Iterator,所以有必要看一下ArrayList中Iterator的源码:
/**
* An optimized version of AbstractList.Itr
*/
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;
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];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
我们分析一下它的成员变量:
cursor:表示将要访问的元素的索引(游标)
lastRet:表示上一个访问的元素的索引
expectedModCount:表示对ArrayList修改次数的期望值,并为其赋值为modCount。
说明:
modCount是AbstractList类中的一个成员变量,表示对List的修改次数。
protected transient int modCount = 0;
假设当前expectedModCount=modCount=0;
为了更加清晰的说明异常的出现,我们将对添加元素开始到获取元素这整个过程分析(这很有必要)。
首先添加元素,先看ArrayList中相关添加元素方法的源码:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
如上代码:
当添加一个元素时,modCount就会自增1,则modCount=1,注意:此时expectedModCount并未改变,依旧为0
在遍历时,首先要判断集合中是否还有元素,这步是通过调用hasNext()来实现的。其源码:
public boolean hasNext() {
return cursor != size;
}
如果将要访问的元素索引与集合大小相等,则表明集合已经遍历结束,否则还有元素未被遍历。
若还存在未被遍历的元素,则进行获取该元素。这步通过调用next()方法实现,其源码如下:
@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];
}
从上面代码可以看出,首先调用checkForComodification()方法检查一番,然后将cursor的值赋给一个局部变量i,并使游标值+1。而后将局部变量i值赋给lastRet,并返回该索引所对应数组中的元素。
那我们看一下checkForComodification()方法到底做了什么检查:
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
如上checkForComodification()方法对修改次数和修改次数期望值进行比较,如果修改次数不等于修改次数期望值,则抛出异常:java.util.ConcurrentModificationException。
继续上面的分析:
当调用next()方法时,next()方法内部先调用checkForComodification()方法。此时modCount为1,expectedModCount为0,则必会抛出java.util.ConcurrentModificationException异常。
如何解决该问题呢?
首先咱得明白,这到底是个什么问题。
本质上是如何解决非线程安全集合类问题。更严谨的说法是,解决非线程安全ArrayList问题。
方法:
- 利用Collections.synchronizedList方法进行同步
- 使用copy-on-write的java.util.concurrent.CopyOnWriteArrayList类
利用Collections.synchronizedList方法进行同步。注:其他类不改动,只改动下面的类:
/**
* 该线程类主要负责遍历并打印List集合中的数据
*/
public class ReaderThread extends Thread {
private final List<Integer> list;
public ReaderThread(List<Integer> list){
super("ReaderThread");
this.list=list;
}
public void run(){
while(true){
synchronized(list){
for(int n:list){
System.out.println(n);
}
}
}
}
}
public class Main {
public static void main(String[] args) {
final List<Integer> list=Collections.synchronizedList(new ArrayList<Integer>());
new WriterThread(list).start();
new ReaderThread(list).start();
}
}
使用copy-on-write的java.util.concurrent.CopyOnWriteArrayList类。注:其他类不改动,只改动下面的类:
public class Main {
public static void main(String[] args) {
final List<Integer> list=new CopyOnWriteArrayList<Integer>();
new WriterThread(list).start();
new ReaderThread(list).start();
}
}
关于CopyOnWriteArrayList类简单说明:
该类采用copy-on-write技术来避免读写冲突。所谓copy-on-write即“写时复制”。当对集合执行“写”操作时,内部的数组会被整体复制得到一个新集合。对新集合里添加元素后,将指向旧集合的原引用重新指向新集合。这样做的好处是我们可以对CopyOnWrite容器进行并发的读,而不需要加锁。
关于CopyOnWrite部分的细节可以查看:
http://ifeve.com/java-copy-on-write/
更多技术干货,请关注下面二维码: