您的位置:首页 > 编程语言 > Java开发

Java 7之多线程并发容器 - CopyOnWriteArrayList

2017-03-06 17:23 537 查看
CopyOnWriteArrayList相当于线程安全的ArrayList,通过增加写时复制语义来实现线程安全性。底层也是通过一个可变数组来实现的。但是和ArrayList不同的时,它具有以下特性:
 它最适合于具有以下特征的应用程序:List 大小通常保持很小,只读操作远多于可变操作,需要在遍历期间防止线程间的冲突
 支持高效率并发且是线程安全的
 因为通常需要复制整个基础数组,所以可变操作(add()、set() 和 remove() 等等)的开销很大
 迭代器支持hasNext(), next()等不可变操作,但不支持可变 remove()等操作
 使用迭代器进行遍历的速度很快,并且不会与其他线程发生冲突。在构造迭代器时,迭代器依赖于不变的数组快照
首先来看一下构造函数,如下所示:

[java]
view plain
copy

print?





private volatile transient Object[] array;  
  
final Object[] getArray() {  
    return array;  
}  
final void setArray(Object[] a) {  
    array = a;  
}  
// -----开始构造函数----------------------------  
public CopyOnWriteArrayList() {  
    setArray(new Object[0]);  
}  
public CopyOnWriteArrayList(Collection<? extends E> c) {  
    Object[] elements = c.toArray();  
    // c.toArray might (incorrectly) not return Object[] (see 6260652)  
    if (elements.getClass() != Object[].class)  
        elements = Arrays.copyOf(elements, elements.length, Object[].class);  
    setArray(elements);  
}  
// Creates a list holding a copy of the given array.  
public CopyOnWriteArrayList(E[] toCopyIn) {  
    setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));  
}  



private volatile transient Object[] array;

final Object[] getArray() {
return array;
}
final void setArray(Object[] a) {
array = a;
}
// -----开始构造函数----------------------------
public CopyOnWriteArrayList() {
setArray(new Object[0]);
}
public CopyOnWriteArrayList(Collection<? extends E> c) {
Object[] elements = c.toArray();
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elements.getClass() != Object[].class)
elements = Arrays.copyOf(elements, elements.length, Object[].class);
setArray(elements);
}
// Creates a list holding a copy of the given array.
public CopyOnWriteArrayList(E[] toCopyIn) {
setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
}
使用一个指向volatile类型的Object数组来保存容器元素。构造函数中都会根据参数值重新生成一个新的数组。

1、添加元素

[java]
view plain
copy

print?





public boolean add(E e) {  
       final ReentrantLock lock = this.lock;                       // 获取独占锁  
       lock.lock();  
       try {  
           Object[] elements = getArray();  
           int len = elements.length;  
           Object[] newElements = Arrays.copyOf(elements, len + 1);// 重新生成一个新的数组实例,并将原始数组的元素拷贝到新数组中  
           newElements[len] = e;                                   // 添加新的元素到新数组的末尾  
           setArray(newElements);                                  // 更新底层数组  
           return true;  
       } finally {  
           lock.unlock();  
       }  
   }  



public boolean add(E e) {
final ReentrantLock lock = this.lock;                       // 获取独占锁
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);// 重新生成一个新的数组实例,并将原始数组的元素拷贝到新数组中
newElements[len] = e;                                   // 添加新的元素到新数组的末尾
setArray(newElements);                                  // 更新底层数组
return true;
} finally {
lock.unlock();
}
}

有两点必须清楚:
 第一,在”添加操作“开始前,获取独占锁(lock),若此时有需要线程要获取锁,则必须等待;在操作完毕后,释放独占锁(lock),此时其它线程才能获取锁。通过独占锁,来防止多线程同时修改数据!
 第二,操作完毕时,会通过setArray()来更新volatile数组。对一个volatile变量的读,总是能看到(任意线程)对这个volatile变量最后的写入;这样,每次添加元素之后,其它线程都能看到新添加的元素。

2、获取元素

[java]
view plain
copy

print?





public E get(int index) {  
    return get(getArray(), index);  
}  
  
private E get(Object[] a, int index) {  
    return (E) a[index];  
}  



public E get(int index) {
return get(getArray(), index);
}

private E get(Object[] a, int index) {
return (E) a[index];
}
将底层volatile数组指定索引处的元素返回即可。

3、删除元素

以remove(int index)为例,来对“CopyOnWriteArrayList的删除操作”进行说明。下面是remove(int index)的代码:

[java]
view plain
copy

print?





public E remove(int index) {  
    final ReentrantLock lock = this.lock;  
    lock.lock();  
    try {  
        Object[] elements = getArray();  
        int len = elements.length;  
        E oldValue = get(elements, index); // 获取volatile数组中指定索引处的元素值  
        int numMoved = len - index - 1;  
        if (numMoved == 0) // 如果被删除的是最后一个元素,则直接通过Arrays.copyOf()进行处理,而不需要新建数组  
            setArray(Arrays.copyOf(elements, len - 1));  
        else {  
            Object[] newElements = new Object[len - 1];  
            System.arraycopy(elements, 0, newElements, 0, index);    // 拷贝删除元素前半部分数据到新数组中  
            System.arraycopy(elements, index + 1, newElements, index, numMoved);// 拷贝删除元素后半部分数据到新数组中  
            setArray(newElements); // 更新volatile数组  
        }  
        return oldValue;  
    } finally {  
        lock.unlock();  
    }  
}  



public E remove(int index) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
E oldValue = get(elements, index); // 获取volatile数组中指定索引处的元素值
int numMoved = len - index - 1;
if (numMoved == 0) // 如果被删除的是最后一个元素,则直接通过Arrays.copyOf()进行处理,而不需要新建数组
setArray(Arrays.copyOf(elements, len - 1));
else {
Object[] newElements = new Object[len - 1];
System.arraycopy(elements, 0, newElements, 0, index);    // 拷贝删除元素前半部分数据到新数组中
System.arraycopy(elements, index + 1, newElements, index, numMoved);// 拷贝删除元素后半部分数据到新数组中
setArray(newElements); // 更新volatile数组
}
return oldValue;
} finally {
lock.unlock();
}
}


4、遍历元素

[java]
view plain
copy

print?





public Iterator<E> iterator() {  
    return new COWIterator<E>(getArray(), 0);  
}  
public ListIterator<E> listIterator() {  
    return new COWIterator<E>(getArray(), 0);  
}  
public ListIterator<E> listIterator(final int index) {  
    Object[] elements = getArray();  
    int len = elements.length;  
    if (index<0 || index>len)  
        throw new IndexOutOfBoundsException("Index: "+index);  
  
    return new COWIterator<E>(elements, index);  
}  
  
private static class COWIterator<E> implements ListIterator<E> {  
    private final Object[] snapshot; // 保存数组的快照,是一个不可变的对象  
    private int cursor;  
  
    private COWIterator(Object[] elements, int initialCursor) {  
        cursor = initialCursor;  
        snapshot = elements;  
    }  
  
    public boolean hasNext() {  
        return cursor < snapshot.length;  
    }  
  
    public boolean hasPrevious() {  
        return cursor > 0;  
    }  
  
    @SuppressWarnings("unchecked")  
    public E next() {  
        if (! hasNext())  
            throw new NoSuchElementException();  
        return (E) snapshot[cursor++];  
    }  
  
    @SuppressWarnings("unchecked")  
    public E previous() {  
        if (! hasPrevious())  
            throw new NoSuchElementException();  
        return (E) snapshot[--cursor];  
    }  
  
    public int nextIndex() {  
        return cursor;  
    }  
  
    public int previousIndex() {  
        return cursor-1;  
    }  
    public void remove() {  
        throw new UnsupportedOperationException();  
    }  <
b190
/span>
    public void set(E e) {  
        throw new UnsupportedOperationException();  
    }  
    public void add(E e) {  
        throw new UnsupportedOperationException();  
    }  
}  



public Iterator<E> iterator() {
return new COWIterator<E>(getArray(), 0);
}
public ListIterator<E> listIterator() {
return new COWIterator<E>(getArray(), 0);
}
public ListIterator<E> listIterator(final int index) {
Object[] elements = getArray();
int len = elements.length;
if (index<0 || index>len)
throw new IndexOutOfBoundsException("Index: "+index);

return new COWIterator<E>(elements, index);
}

private static class COWIterator<E> implements ListIterator<E> {
private final Object[] snapshot; // 保存数组的快照,是一个不可变的对象
private int cursor;

private COWIterator(Object[] elements, int initialCursor) {
cursor = initialCursor;
snapshot = elements;
}

public boolean hasNext() {
return cursor < snapshot.length;
}

public boolean hasPrevious() {
return cursor > 0;
}

@SuppressWarnings("unchecked")
public E next() {
if (! hasNext())
throw new NoSuchElementException();
return (E) snapshot[cursor++];
}

@SuppressWarnings("unchecked")
public E previous() {
if (! hasPrevious())
throw new NoSuchElementException();
return (E) snapshot[--cursor];
}

public int nextIndex() {
return cursor;
}

public int previousIndex() {
return cursor-1;
}
public void remove() {
throw new UnsupportedOperationException();
}
public void set(E e) {
throw new UnsupportedOperationException();
}
public void add(E e) {
throw new UnsupportedOperationException();
}
}
如上容器的迭代器中会保存一个不可变的Object数组对象,那么在进行遍历这个对象时就不需要再进一步的同步。在每次修改时,都会创建并重新发布一个新的窗口副本,从而实现了可变性。如上迭代器代码中保留了一个指向volatile数组的引用,由于不会被修改,因此多个线程可以同时对它进行迭代,而不会彼此干扰或与修改容器的线程相互干扰。
与之前的ArrayList实现相比,CopyOnWriteArrayList返回迭代器不会抛出ConcurrentModificationException异常,即它不是fail-fast机制的!

转载自http://blog.csdn.net/mazhimazh/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息