Java源码学习(JDK 11)——java.util.concurrent.CopyOnWriteArrayList

Posted jl916

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java源码学习(JDK 11)——java.util.concurrent.CopyOnWriteArrayList相关的知识,希望对你有一定的参考价值。

定义

package java.util.concurrent;

public class CopyOnWriteArrayList<E>
   implements List<E>, RandomAccess, Cloneable, java.io.Serializable { /*/ }
  • JUC 中的 CopyOnWriteArrayList,线程安全的 ArrayList
  • 通过对底层数组复制保障线程安全

属性

/**
 * The lock protecting all mutators.  (We have a mild preference
 * for builtin monitors over ReentrantLock when either will do.)
 */
final transient Object lock = new Object();

/** The array, accessed only via getArray/setArray. */
private transient volatile Object[] array;

  • lock 作为被加锁的对象
  • arrayvolatile 修饰,保证修改后被所有线程可见

方法

  • add 添加元素
public boolean add(E e) {
	// 加锁 + 复制 
    synchronized (lock) {
        Object[] es = getArray();
        int len = es.length;
        es = Arrays.copyOf(es, len + 1);
        es[len] = e;
        setArray(es);
        return true;
    }
}

public void add(int index, E element) {
    synchronized (lock) {
        Object[] es = getArray();
        int len = es.length;
        if (index > len || index < 0)
            throw new IndexOutOfBoundsException(outOfBounds(index, len));
        Object[] newElements;
        int numMoved = len - index;
        if (numMoved == 0)
            newElements = Arrays.copyOf(es, len + 1);
        else {
            newElements = new Object[len + 1];
            System.arraycopy(es, 0, newElements, 0, index);
            System.arraycopy(es, index, newElements, index + 1, numMoved);
        }
        newElements[index] = element;
        setArray(newElements);
    }
}

// getArray/setArray
final Object[] getArray() {
    return array;
}

final void setArray(Object[] a) {
    array = a;
}
  • addAll 添加所有元素
public boolean addAll(int index, Collection<? extends E> c) {
	Object[] cs = c.toArray();
    synchronized (lock) {
        Object[] es = getArray();
        int len = es.length;
        if (index > len || index < 0)
            throw new IndexOutOfBoundsException(outOfBounds(index, len));
        if (cs.length == 0)
            return false;
        int numMoved = len - index;
        Object[] newElements;

        // 数组复制
        if (numMoved == 0)
            newElements = Arrays.copyOf(es, len + cs.length);
        else {
            newElements = new Object[len + cs.length];
            System.arraycopy(es, 0, newElements, 0, index);
            System.arraycopy(es, index,
                             newElements, index + cs.length,
                             numMoved);
        }
        System.arraycopy(cs, 0, newElements, index, cs.length);
        setArray(newElements);
        return true;
    }
}

public boolean addAll(Collection<? extends E> c) {
    Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ?
        ((CopyOnWriteArrayList<?>)c).getArray() : c.toArray();
    if (cs.length == 0)
        return false;
    synchronized (lock) {
        // 实现类似
    }
}
  • clear 清空
public void clear() {
    synchronized (lock) {
        setArray(new Object[0]);
    }
}
  • contains 包含
// 读取操作是不需要加锁的
public boolean contains(Object o) {
    return indexOf(o) >= 0;
}
  • remove 移除
public E remove(int index) {
    synchronized (lock) {
        Object[] es = getArray();
        int len = es.length;
        E oldValue = elementAt(es, index);
        int numMoved = len - index - 1;
        Object[] newElements;
        if (numMoved == 0)
            newElements = Arrays.copyOf(es, len - 1);
        else {
            newElements = new Object[len - 1];
            System.arraycopy(es, 0, newElements, 0, index);
            System.arraycopy(es, index + 1, newElements, index, numMoved);
        }
        setArray(newElements);
        return oldValue;
    }
}

public boolean remove(Object o) {
    Object[] snapshot = getArray();	// 保存快照
    int index = indexOfRange(o, snapshot, 0, snapshot.length);	// 寻找下标
    return index >= 0 && remove(o, snapshot, index);
}

/**
 * A version of remove(Object) using the strong hint that given
 * recent snapshot contains o at the given index.
 */
private boolean remove(Object o, Object[] snapshot, int index) {
    synchronized (lock) {	// 加锁
        Object[] current = getArray();
        int len = current.length;
        // 更新下标
        if (snapshot != current) findIndex: {
        	// 新下标在旧下标之前
            int prefix = Math.min(index, len);
            for (int i = 0; i < prefix; i++) {
                if (current[i] != snapshot[i] && Objects.equals(o, current[i])) {
                    index = i;
                    break findIndex;
                }
            }
            if (index >= len)
                return false;
            // 新旧下标一致
            if (current[index] == o)
                break findIndex;
            // 新下标在旧下标之后
            index = indexOfRange(o, current, index, len);
            if (index < 0)
                return false;
        }
        Object[] newElements = new Object[len - 1];
        System.arraycopy(current, 0, newElements, 0, index);
        System.arraycopy(current, index + 1,
                         newElements, index,
                         len - index - 1);
        setArray(newElements);
        return true;
    }
}
  • indexOf 下标
public int indexOf(Object o) {
    Object[] es = getArray();
    return indexOfRange(o, es, 0, es.length);
}

public int indexOf(E e, int index) {
    Object[] es = getArray();
    return indexOfRange(e, es, index, es.length);
}

private static int indexOfRange(Object o, Object[] es, int from, int to) {
    if (o == null) {
        for (int i = from; i < to; i++)
            if (es[i] == null)
                return i;
    } else {
        for (int i = from; i < to; i++)
            if (o.equals(es[i]))
                return i;
    }
    return -1;
}
  • iterator 迭代器
public Iterator<E> iterator() {
    return new COWIterator<E>(getArray(), 0);
}

// 内部类实现
static final class COWIterator<E> implements ListIterator<E> {
    /** Snapshot of the array */
    private final Object[] snapshot;	// 被 final 修饰 迭代过程中引用不会发生改变
    /** Index of element to be returned by subsequent call to next.  */
    private int cursor;

    // 数组改变(add/remove...)时 会创建新数组 使用新的内存地址
    // 而该迭代器始终引用的是原数组 即保存了原数组的一个快照
    // 因此不会对遍历结果造成影响 也就不需要加锁

    COWIterator(Object[] es, int initialCursor) {
        cursor = initialCursor;	// 直接引用该数组
        snapshot = es;
    }

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

    // 无法进行 add set remove 操作
    /**
     * Not supported. Always throws UnsupportedOperationException.
     * @throws UnsupportedOperationException always; {@code remove}
     *         is not supported by this iterator.
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

以上是关于Java源码学习(JDK 11)——java.util.concurrent.CopyOnWriteArrayList的主要内容,如果未能解决你的问题,请参考以下文章

Java源码学习(JDK 11)——java.util.concurrent.CopyOnWriteArrayList

源码阅读(34):Java中线程安全的QueueDeque结构——ArrayBlockingQueue

源码阅读(34):Java中线程安全的QueueDeque结构——ArrayBlockingQueue

过年学习-JVM | JDK11源码编译

JDK源码阅读:ArrayList源码解析

jdk11源码debug