猿问

关于线程安全List读时加锁的问题

Vector或Collections.synchronizedList为什么get方法要加锁?CopyOnWriteArrayList并没有。

我觉得读的时候不加锁应该没问题吧?读时候加锁有什么意义?能确保读到最新值?那么直接给Object[] elementData加volatile关键字保证可见性。

我也知道CopyOnWriteArrayList修改是每次重新建一个elementData,但就算不是重新建,读时不加锁有什么问题?请赐教。


//以下是CopyOnWriteArrayList的代码:

@SuppressWarnings("unchecked")

private E get(Object[] a, int index) {

    return (E) a[index];

}

/**

 * {@inheritDoc}

 *

 * @throws IndexOutOfBoundsException {@inheritDoc}

 */

public E get(int index) {

    return get(getArray(), index);

}


//以下是Vector的代码:

public synchronized E get(int index) {

    if (index >= elementCount)

        throw new ArrayIndexOutOfBoundsException(index);


    return elementData(index);

}


POPMUISE
浏览 326回答 1
1回答
随时随地看视频慕课网APP

相关分类

Java
我要回答