--- jsr166/src/main/java/util/ArrayList.java 2016/10/31 23:02:42 1.36 +++ jsr166/src/main/java/util/ArrayList.java 2016/12/05 00:08:01 1.47 @@ -423,6 +423,11 @@ public class ArrayList extends Abstra return (E) elementData[index]; } + @SuppressWarnings("unchecked") + static E elementAt(Object[] es, int index) { + return (E) es[index]; + } + /** * Returns the element at the specified position in this list. * @@ -496,6 +501,7 @@ public class ArrayList extends Abstra s - index); elementData[index] = element; size = s + 1; + // checkInvariants(); } /** @@ -519,6 +525,7 @@ public class ArrayList extends Abstra numMoved); elementData[--size] = null; // clear to let GC do its work + // checkInvariants(); return oldValue; } @@ -552,7 +559,7 @@ public class ArrayList extends Abstra return false; } - /* + /** * Private remove method that skips bounds checking and does not * return the value removed. */ @@ -571,12 +578,9 @@ public class ArrayList extends Abstra */ public void clear() { modCount++; - - // clear to let GC do its work - for (int i = 0; i < size; i++) - elementData[i] = null; - - size = 0; + final Object[] es = elementData; + for (int to = size, i = size = 0; i < to; i++) + es[i] = null; } /** @@ -604,6 +608,7 @@ public class ArrayList extends Abstra elementData = grow(s + numNew); System.arraycopy(a, 0, elementData, s, numNew); size = s + numNew; + // checkInvariants(); return true; } @@ -642,6 +647,7 @@ public class ArrayList extends Abstra numMoved); System.arraycopy(a, 0, elementData, index, numNew); size = s + numNew; + // checkInvariants(); return true; } @@ -664,16 +670,15 @@ public class ArrayList extends Abstra outOfBoundsMsg(fromIndex, toIndex)); } modCount++; - int numMoved = size - toIndex; - System.arraycopy(elementData, toIndex, elementData, fromIndex, - numMoved); - - // clear to let GC do its work - int newSize = size - (toIndex-fromIndex); - for (int i = newSize; i < size; i++) { - elementData[i] = null; - } - size = newSize; + shiftTailOverGap(elementData, fromIndex, toIndex); + // checkInvariants(); + } + + /** Erases the gap from lo to hi, by sliding down following elements. */ + private void shiftTailOverGap(Object[] es, int lo, int hi) { + System.arraycopy(es, hi, es, lo, size - hi); + for (int to = size, i = (size -= hi - lo); i < to; i++) + es[i] = null; } /** @@ -716,8 +721,7 @@ public class ArrayList extends Abstra * @see Collection#contains(Object) */ public boolean removeAll(Collection c) { - Objects.requireNonNull(c); - return batchRemove(c, false); + return batchRemove(c, false, 0, size); } /** @@ -737,49 +741,51 @@ public class ArrayList extends Abstra * @see Collection#contains(Object) */ public boolean retainAll(Collection c) { - Objects.requireNonNull(c); - return batchRemove(c, true); + return batchRemove(c, true, 0, size); } - private boolean batchRemove(Collection c, boolean complement) { - final Object[] elementData = this.elementData; - int r = 0, w = 0; - boolean modified = false; - try { - for (; r < size; r++) - if (c.contains(elementData[r]) == complement) - elementData[w++] = elementData[r]; - } finally { - // Preserve behavioral compatibility with AbstractCollection, - // even if c.contains() throws. - if (r != size) { - System.arraycopy(elementData, r, - elementData, w, - size - r); - w += size - r; - } - if (w != size) { - // clear to let GC do its work - for (int i = w; i < size; i++) - elementData[i] = null; - modCount += size - w; - size = w; - modified = true; + boolean batchRemove(Collection c, boolean complement, + final int from, final int end) { + Objects.requireNonNull(c); + final Object[] es = elementData; + final boolean modified; + int r; + // Optimize for initial run of survivors + for (r = from; r < end && c.contains(es[r]) == complement; r++) + ; + if (modified = (r < end)) { + int w = r++; + try { + for (Object e; r < end; r++) + if (c.contains(e = es[r]) == complement) + es[w++] = e; + } catch (Throwable ex) { + // Preserve behavioral compatibility with AbstractCollection, + // even if c.contains() throws. + System.arraycopy(es, r, es, w, end - r); + w += end - r; + throw ex; + } finally { + modCount += end - w; + shiftTailOverGap(es, w, end); } } + // checkInvariants(); return modified; } /** - * Save the state of the {@code ArrayList} instance to a stream (that - * is, serialize it). + * Saves the state of the {@code ArrayList} instance to a stream + * (that is, serializes it). * + * @param s the stream + * @throws java.io.IOException if an I/O error occurs * @serialData The length of the array backing the {@code ArrayList} * instance is emitted (int), followed by all of its elements * (each an {@code Object}) in the proper order. */ private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException{ + throws java.io.IOException { // Write out element count, and any hidden stuff int expectedModCount = modCount; s.defaultWriteObject(); @@ -798,8 +804,12 @@ public class ArrayList extends Abstra } /** - * Reconstitute the {@code ArrayList} instance from a stream (that is, - * deserialize it). + * Reconstitutes the {@code ArrayList} instance from a stream (that is, + * deserializes it). + * @param s the stream + * @throws ClassNotFoundException if the class of a serialized object + * could not be found + * @throws java.io.IOException if an I/O error occurs */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { @@ -911,25 +921,21 @@ public class ArrayList extends Abstra } @Override - @SuppressWarnings("unchecked") - public void forEachRemaining(Consumer consumer) { - Objects.requireNonNull(consumer); + public void forEachRemaining(Consumer action) { + Objects.requireNonNull(action); final int size = ArrayList.this.size; int i = cursor; - if (i >= size) { - return; - } - final Object[] elementData = ArrayList.this.elementData; - if (i >= elementData.length) { - throw new ConcurrentModificationException(); - } - while (i != size && modCount == expectedModCount) { - consumer.accept((E) elementData[i++]); + if (i < size) { + final Object[] es = elementData; + if (i >= es.length) + throw new ConcurrentModificationException(); + for (; i < size && modCount == expectedModCount; i++) + action.accept(elementAt(es, i)); + // update once at end to reduce heap write traffic + cursor = i; + lastRet = i - 1; + checkForComodification(); } - // update once at end of iteration to reduce heap write traffic - cursor = i; - lastRet = i - 1; - checkForComodification(); } final void checkForComodification() { @@ -1116,6 +1122,33 @@ public class ArrayList extends Abstra return true; } + public boolean removeAll(Collection c) { + return batchRemove(c, false); + } + + public boolean retainAll(Collection c) { + return batchRemove(c, true); + } + + private boolean batchRemove(Collection c, boolean complement) { + checkForComodification(); + int oldSize = root.size; + boolean modified = + root.batchRemove(c, complement, offset, offset + size); + if (modified) + updateSizeAndModCount(root.size - oldSize); + return modified; + } + + public boolean removeIf(Predicate filter) { + checkForComodification(); + int oldSize = root.size; + boolean modified = root.removeIf(filter, offset, offset + size); + if (modified) + updateSizeAndModCount(root.size - oldSize); + return modified; + } + public Iterator iterator() { return listIterator(); } @@ -1163,24 +1196,21 @@ public class ArrayList extends Abstra return (E) elementData[offset + (lastRet = i)]; } - @SuppressWarnings("unchecked") - public void forEachRemaining(Consumer consumer) { - Objects.requireNonNull(consumer); + public void forEachRemaining(Consumer action) { + Objects.requireNonNull(action); final int size = SubList.this.size; int i = cursor; - if (i >= size) { - return; - } - final Object[] elementData = root.elementData; - if (offset + i >= elementData.length) { - throw new ConcurrentModificationException(); - } - while (i != size && modCount == expectedModCount) { - consumer.accept((E) elementData[offset + (i++)]); + if (i < size) { + final Object[] es = root.elementData; + if (offset + i >= es.length) + throw new ConcurrentModificationException(); + for (; i < size && modCount == expectedModCount; i++) + action.accept(elementAt(es, offset + i)); + // update once at end to reduce heap write traffic + cursor = i; + lastRet = i - 1; + checkForComodification(); } - // update once at end of iteration to reduce heap write traffic - lastRet = cursor = i; - checkForComodification(); } public int nextIndex() { @@ -1270,9 +1300,8 @@ public class ArrayList extends Abstra public Spliterator spliterator() { checkForComodification(); - // ArrayListSpliterator is not used because late-binding logic - // is different here - return new Spliterator<>() { + // ArrayListSpliterator not used here due to late-binding + return new Spliterator() { private int index = offset; // current index, modified on advance/split private int fence = -1; // -1 until used; then one past last index private int expectedModCount; // initialized when fence set @@ -1286,12 +1315,11 @@ public class ArrayList extends Abstra return hi; } - public ArrayListSpliterator trySplit() { + public ArrayList.ArrayListSpliterator trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; - // ArrayListSpliterator could be used here as the source is already bound + // ArrayListSpliterator can be used here as the source is already bound return (lo >= mid) ? null : // divide range in half unless too small - new ArrayListSpliterator<>(root, lo, index = mid, - expectedModCount); + root.new ArrayListSpliterator(lo, index = mid, expectedModCount); } public boolean tryAdvance(Consumer action) { @@ -1333,7 +1361,7 @@ public class ArrayList extends Abstra } public long estimateSize() { - return (long) (getFence() - index); + return getFence() - index; } public int characteristics() { @@ -1347,15 +1375,12 @@ public class ArrayList extends Abstra public void forEach(Consumer action) { Objects.requireNonNull(action); final int expectedModCount = modCount; - @SuppressWarnings("unchecked") - final E[] elementData = (E[]) this.elementData; + final Object[] es = elementData; final int size = this.size; - for (int i=0; modCount == expectedModCount && i < size; i++) { - action.accept(elementData[i]); - } - if (modCount != expectedModCount) { + for (int i = 0; modCount == expectedModCount && i < size; i++) + action.accept(elementAt(es, i)); + if (modCount != expectedModCount) throw new ConcurrentModificationException(); - } } /** @@ -1373,11 +1398,11 @@ public class ArrayList extends Abstra */ @Override public Spliterator spliterator() { - return new ArrayListSpliterator<>(this, 0, -1, 0); + return new ArrayListSpliterator(0, -1, 0); } /** Index-based split-by-two, lazily initialized Spliterator */ - static final class ArrayListSpliterator implements Spliterator { + final class ArrayListSpliterator implements Spliterator { /* * If ArrayLists were immutable, or structurally immutable (no @@ -1411,15 +1436,12 @@ public class ArrayList extends Abstra * these streamlinings. */ - private final ArrayList list; private int index; // current index, modified on advance/split private int fence; // -1 until used; then one past last index private int expectedModCount; // initialized when fence set - /** Create new spliterator covering the given range */ - ArrayListSpliterator(ArrayList list, int origin, int fence, - int expectedModCount) { - this.list = list; // OK if null unless traversed + /** Create new spliterator covering the given range */ + ArrayListSpliterator(int origin, int fence, int expectedModCount) { this.index = origin; this.fence = fence; this.expectedModCount = expectedModCount; @@ -1427,23 +1449,17 @@ public class ArrayList extends Abstra private int getFence() { // initialize fence to size on first use int hi; // (a specialized variant appears in method forEach) - ArrayList lst; if ((hi = fence) < 0) { - if ((lst = list) == null) - hi = fence = 0; - else { - expectedModCount = lst.modCount; - hi = fence = lst.size; - } + expectedModCount = modCount; + hi = fence = size; } return hi; } - public ArrayListSpliterator trySplit() { + public ArrayListSpliterator trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid) ? null : // divide range in half unless too small - new ArrayListSpliterator<>(list, lo, index = mid, - expectedModCount); + new ArrayListSpliterator(lo, index = mid, expectedModCount); } public boolean tryAdvance(Consumer action) { @@ -1452,9 +1468,9 @@ public class ArrayList extends Abstra int hi = getFence(), i = index; if (i < hi) { index = i + 1; - @SuppressWarnings("unchecked") E e = (E)list.elementData[i]; + @SuppressWarnings("unchecked") E e = (E)elementData[i]; action.accept(e); - if (list.modCount != expectedModCount) + if (modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } @@ -1463,13 +1479,13 @@ public class ArrayList extends Abstra public void forEachRemaining(Consumer action) { int i, hi, mc; // hoist accesses and checks from loop - ArrayList lst; Object[] a; + Object[] a; if (action == null) throw new NullPointerException(); - if ((lst = list) != null && (a = lst.elementData) != null) { + if ((a = elementData) != null) { if ((hi = fence) < 0) { - mc = lst.modCount; - hi = lst.size; + mc = modCount; + hi = size; } else mc = expectedModCount; @@ -1478,7 +1494,7 @@ public class ArrayList extends Abstra @SuppressWarnings("unchecked") E e = (E) a[i]; action.accept(e); } - if (lst.modCount == mc) + if (modCount == mc) return; } } @@ -1486,7 +1502,7 @@ public class ArrayList extends Abstra } public long estimateSize() { - return (long) (getFence() - index); + return getFence() - index; } public int characteristics() { @@ -1494,52 +1510,75 @@ public class ArrayList extends Abstra } } - @SuppressWarnings("unchecked") + // A tiny bit set implementation + + private static long[] nBits(int n) { + return new long[((n - 1) >> 6) + 1]; + } + private static void setBit(long[] bits, int i) { + bits[i >> 6] |= 1L << i; + } + private static boolean isClear(long[] bits, int i) { + return (bits[i >> 6] & (1L << i)) == 0; + } + @Override public boolean removeIf(Predicate filter) { + return removeIf(filter, 0, size); + } + + /** + * Removes all elements satisfying the given predicate, from index + * i (inclusive) to index end (exclusive). + */ + boolean removeIf(Predicate filter, int i, final int end) { Objects.requireNonNull(filter); int expectedModCount = modCount; final Object[] es = elementData; - final int size = this.size; - final boolean modified; - int r; - for (r = 0; r < size; r++) - if (filter.test((E) es[r])) - break; - if (modified = (r < size)) { + // Optimize for initial run of survivors + for (; i < end && !filter.test(elementAt(es, i)); i++) + ; + // Tolerate predicates that reentrantly access the collection for + // read (but writers still get CME), so traverse once to find + // elements to delete, a second pass to physically expunge. + if (i < end) { + final int beg = i; + final long[] deathRow = nBits(end - beg); + deathRow[0] = 1L; // set bit 0 + for (i = beg + 1; i < end; i++) + if (filter.test(elementAt(es, i))) + setBit(deathRow, i - beg); + if (modCount != expectedModCount) + throw new ConcurrentModificationException(); expectedModCount++; modCount++; - int w = r++; - try { - for (E e; r < size; r++) - if (!filter.test(e = (E) es[r])) - es[w++] = e; - Arrays.fill(es, (this.size = w), size, null); - } catch (Throwable ex) { - // copy remaining elements - System.arraycopy(es, r, es, w, size - r); - Arrays.fill(es, (this.size = w + size - r), size, null); - throw ex; - } + int w = beg; + for (i = beg; i < end; i++) + if (isClear(deathRow, i - beg)) + es[w++] = es[i]; + shiftTailOverGap(es, w, end); + // checkInvariants(); + return true; + } else { + if (modCount != expectedModCount) + throw new ConcurrentModificationException(); + // checkInvariants(); + return false; } - if (modCount != expectedModCount) - throw new ConcurrentModificationException(); - return modified; } @Override - @SuppressWarnings("unchecked") public void replaceAll(UnaryOperator operator) { Objects.requireNonNull(operator); final int expectedModCount = modCount; + final Object[] es = elementData; final int size = this.size; - for (int i=0; modCount == expectedModCount && i < size; i++) { - elementData[i] = operator.apply((E) elementData[i]); - } - if (modCount != expectedModCount) { + for (int i = 0; modCount == expectedModCount && i < size; i++) + es[i] = operator.apply(elementAt(es, i)); + if (modCount != expectedModCount) throw new ConcurrentModificationException(); - } modCount++; + // checkInvariants(); } @Override @@ -1547,9 +1586,14 @@ public class ArrayList extends Abstra public void sort(Comparator c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData, 0, size, c); - if (modCount != expectedModCount) { + if (modCount != expectedModCount) throw new ConcurrentModificationException(); - } modCount++; + // checkInvariants(); + } + + void checkInvariants() { + // assert size >= 0; + // assert size == elementData.length || elementData[size] == null; } }