[concurrency-interest] Question about comment 'Not quite a no-op; ensures volatile write semantics' in CopyOnWriteArrayList

Christian Vest Hansen karmazilla at gmail.com
Mon Feb 15 15:34:05 EST 2010


This is my theory:

set() wants to guarantee safe publication. So if some unsynchronized
writes have been made to element prior to the call to set(), then we
ensure that those are ordered before any subsequent get()s.

addAllAbsent() probably does not want to make this guarantee if no
elements are absent.

On Mon, Feb 15, 2010 at 8:33 PM, Peter Oleski <oleski at web.de> wrote:
> Hello
>
> The source code of the CopyOnWriteArrayList has in the set method in line 399
> a very interesting comment which is:
> "// Not quite a no-op; ensures volatile write semantics"
> This comment is part of an else case which sets the array although nothing got changed.
> The central data structure is volatile and defined as:
>
> private volatile transient Object[] array;
>
> Why is it necessary to set the array when nothing has changed?
>
> The Method addAllAbsent in line 717 only calls setArray if something got changed.
> Can somebody explain this or is there an explanation already somewhere available which I didnt't find?
> I would really like to understand this.
>
>
> Greetings
> Peter Oleski
>
> As a quick reference this is the source of the whole set method.
>
>   /**
>     * Replaces the element at the specified position in this list with the
>     * specified element.
>     *
>     * @throws IndexOutOfBoundsException {@inheritDoc}
>     */
>    public E set(int index, E element) {
>        final ReentrantLock lock = this.lock;
>        lock.lock();
>        try {
>            Object[] elements = getArray();
>            E oldValue = get(elements, index);
>
>            if (oldValue != element) {
>                int len = elements.length;
>                Object[] newElements = Arrays.copyOf(elements, len);
>                newElements[index] = element;
>                setArray(newElements);
>            } else {
>                // Not quite a no-op; ensures volatile write semantics
>                setArray(elements);
>            }
>            return oldValue;
>        } finally {
>            lock.unlock();
>        }
>    }
> ___________________________________________________________
> GRATIS für alle WEB.DE-Nutzer: Die maxdome Movie-FLAT!
> Jetzt freischalten unter http://movieflat.web.de
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>



-- 
Venlig hilsen / Kind regards,
Christian Vest Hansen.



More information about the Concurrency-interest mailing list