[concurrency-interest] RFR [8011215] optimization of CopyOnWriteArrayList.addIfAbsent()

Ivan Gerasimov ivan.gerasimov at oracle.com
Tue Apr 2 14:53:09 EDT 2013


Hello everybody!

Please review my proposal for the CopyOnWriteArrayList.addIfAbsent() method optimization.

http://washi.ru.oracle.com/~igerasim/webrevs/8011215/webrev/index.html

Here is the original function body:
------------------------------------------------
     Object[] elements = getArray();
     int len = elements.length;
     Object[] newElements = new Object[len + 1]; <-- allocate new array in advance
     for (int i = 0; i < len; ++i) {
         if (eq(e, elements[i]))                 <-- check whether e is null on every iteration
             return false; // exit, throwing away copy
         else
             newElements[i] = elements[i];       <-- copy elements one by one
     }
     newElements[len] = e;
     setArray(newElements);
------------------------------------------------
The proposed change is to reuse CopyOnWriteArrayList.indexOf() function to check if e is already in the array.
If the check passed, new array is allocated withArrays.copyOf(). It uses native System.arraycopy(), which is probably faster than copying elements in the loop.

Sincerely yours,
Ivan



More information about the Concurrency-interest mailing list