在CopyOnWriteArrayList类的set方法中有一段setArray(elements)代码,实际上这段代码并未对elements做任何改动,实现的volatile语意并不对CopyOnWriteArrayList实例产生任何影响,为什么还是要保留这行语句?见以下代码红体部分:
01 | /** The array, accessed only via getArray/setArray. */ |
02 | private volatile transient Object[] array; |
05 | * Replaces the element at the specified position in this list with the |
08 | * @throws IndexOutOfBoundsException {@inheritDoc} |
10 | public E set( int index, E element) { |
11 | final ReentrantLock lock = this .lock; |
14 | Object[] elements = getArray(); |
15 | E oldValue = get(elements, index); |
17 | if (oldValue != element) { |
18 | int len = elements.length; |
19 | Object[] newElements = Arrays.copyOf(elements, len); |
20 | newElements[index] = element; |
21 | setArray(newElements); |
35 | final void setArray(Object[] a) { |
40 | * Gets the array. Non-private so as to also be accessible |
41 | * from CopyOnWriteArraySet class. |
43 | final Object[] getArray() { |
这个问题在concurrency-interest邮件列表里也有人讨论:
http://cs.oswego.edu/pipermail/concurrency-interest/2010-February/006886.html