ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Vector.java
(Generate patch)

Comparing jsr166/src/main/java/util/Vector.java (file contents):
Revision 1.30 by jsr166, Thu Nov 3 20:49:07 2016 UTC vs.
Revision 1.43 by jsr166, Wed Dec 21 05:15:08 2016 UTC

# Line 306 | Line 306 | public class Vector<E>
306          modCount++;
307          if (newSize > elementData.length)
308              grow(newSize);
309 <        for (int i = newSize; i < elementCount; i++)
310 <            elementData[i] = null;
311 <        elementCount = newSize;
309 >        final Object[] es = elementData;
310 >        for (int to = elementCount, i = elementCount = newSize; i < to; i++)
311 >            es[i] = null;
312      }
313  
314      /**
# Line 513 | Line 513 | public class Vector<E>
513       * Returns the last component of the vector.
514       *
515       * @return  the last component of the vector, i.e., the component at index
516 <     *          <code>size()&nbsp;-&nbsp;1</code>.
516 >     *          {@code size() - 1}
517       * @throws NoSuchElementException if this vector is empty
518       */
519      public synchronized E lastElement() {
# Line 585 | Line 585 | public class Vector<E>
585          modCount++;
586          elementCount--;
587          elementData[elementCount] = null; /* to let gc do its work */
588 +        // checkInvariants();
589      }
590  
591      /**
# Line 675 | Line 676 | public class Vector<E>
676       * method (which is part of the {@link List} interface).
677       */
678      public synchronized void removeAllElements() {
679 <        // Let gc do its work
680 <        for (int i = 0; i < elementCount; i++)
681 <            elementData[i] = null;
681 <
679 >        final Object[] es = elementData;
680 >        for (int to = elementCount, i = elementCount = 0; i < to; i++)
681 >            es[i] = null;
682          modCount++;
683        elementCount = 0;
683      }
684  
685      /**
# Line 693 | Line 692 | public class Vector<E>
692      public synchronized Object clone() {
693          try {
694              @SuppressWarnings("unchecked")
695 <                Vector<E> v = (Vector<E>) super.clone();
695 >            Vector<E> v = (Vector<E>) super.clone();
696              v.elementData = Arrays.copyOf(elementData, elementCount);
697              v.modCount = 0;
698              return v;
# Line 759 | Line 758 | public class Vector<E>
758          return (E) elementData[index];
759      }
760  
761 +    @SuppressWarnings("unchecked")
762 +    static <E> E elementAt(Object[] es, int index) {
763 +        return (E) es[index];
764 +    }
765 +
766      /**
767       * Returns the element at the specified position in this Vector.
768       *
# Line 805 | Line 809 | public class Vector<E>
809              elementData = grow();
810          elementData[s] = e;
811          elementCount = s + 1;
812 +        // checkInvariants();
813      }
814  
815      /**
# Line 855 | Line 860 | public class Vector<E>
860       * Shifts any subsequent elements to the left (subtracts one from their
861       * indices).  Returns the element that was removed from the Vector.
862       *
858     * @throws ArrayIndexOutOfBoundsException if the index is out of range
859     *         ({@code index < 0 || index >= size()})
863       * @param index the index of the element to be removed
864       * @return element that was removed
865 +     * @throws ArrayIndexOutOfBoundsException if the index is out of range
866 +     *         ({@code index < 0 || index >= size()})
867       * @since 1.2
868       */
869      public synchronized E remove(int index) {
# Line 873 | Line 878 | public class Vector<E>
878                               numMoved);
879          elementData[--elementCount] = null; // Let gc do its work
880  
881 +        // checkInvariants();
882          return oldValue;
883      }
884  
# Line 928 | Line 934 | public class Vector<E>
934                  elementData = grow(s + numNew);
935              System.arraycopy(a, 0, elementData, s, numNew);
936              elementCount = s + numNew;
937 +            // checkInvariants();
938              return true;
939          }
940      }
# Line 949 | Line 956 | public class Vector<E>
956       *         or if the specified collection is null
957       * @since 1.2
958       */
959 <    public synchronized boolean removeAll(Collection<?> c) {
960 <        return super.removeAll(c);
959 >    public boolean removeAll(Collection<?> c) {
960 >        Objects.requireNonNull(c);
961 >        return bulkRemove(e -> c.contains(e));
962      }
963  
964      /**
# Line 972 | Line 980 | public class Vector<E>
980       *         or if the specified collection is null
981       * @since 1.2
982       */
983 <    public synchronized boolean retainAll(Collection<?> c) {
984 <        return super.retainAll(c);
983 >    public boolean retainAll(Collection<?> c) {
984 >        Objects.requireNonNull(c);
985 >        return bulkRemove(e -> !c.contains(e));
986 >    }
987 >
988 >    /**
989 >     * @throws NullPointerException {@inheritDoc}
990 >     */
991 >    @Override
992 >    public boolean removeIf(Predicate<? super E> filter) {
993 >        Objects.requireNonNull(filter);
994 >        return bulkRemove(filter);
995 >    }
996 >
997 >    // A tiny bit set implementation
998 >
999 >    private static long[] nBits(int n) {
1000 >        return new long[((n - 1) >> 6) + 1];
1001 >    }
1002 >    private static void setBit(long[] bits, int i) {
1003 >        bits[i >> 6] |= 1L << i;
1004 >    }
1005 >    private static boolean isClear(long[] bits, int i) {
1006 >        return (bits[i >> 6] & (1L << i)) == 0;
1007 >    }
1008 >
1009 >    private synchronized boolean bulkRemove(Predicate<? super E> filter) {
1010 >        int expectedModCount = modCount;
1011 >        final Object[] es = elementData;
1012 >        final int end = elementCount;
1013 >        int i;
1014 >        // Optimize for initial run of survivors
1015 >        for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
1016 >            ;
1017 >        // Tolerate predicates that reentrantly access the collection for
1018 >        // read (but writers still get CME), so traverse once to find
1019 >        // elements to delete, a second pass to physically expunge.
1020 >        if (i < end) {
1021 >            final int beg = i;
1022 >            final long[] deathRow = nBits(end - beg);
1023 >            deathRow[0] = 1L;   // set bit 0
1024 >            for (i = beg + 1; i < end; i++)
1025 >                if (filter.test(elementAt(es, i)))
1026 >                    setBit(deathRow, i - beg);
1027 >            if (modCount != expectedModCount)
1028 >                throw new ConcurrentModificationException();
1029 >            expectedModCount++;
1030 >            modCount++;
1031 >            int w = beg;
1032 >            for (i = beg; i < end; i++)
1033 >                if (isClear(deathRow, i - beg))
1034 >                    es[w++] = es[i];
1035 >            for (i = elementCount = w; i < end; i++)
1036 >                es[i] = null;
1037 >            // checkInvariants();
1038 >            return true;
1039 >        } else {
1040 >            if (modCount != expectedModCount)
1041 >                throw new ConcurrentModificationException();
1042 >            // checkInvariants();
1043 >            return false;
1044 >        }
1045      }
1046  
1047      /**
# Line 1014 | Line 1082 | public class Vector<E>
1082                               numMoved);
1083          System.arraycopy(a, 0, elementData, index, numNew);
1084          elementCount = s + numNew;
1085 +        // checkInvariants();
1086          return true;
1087      }
1088  
# Line 1095 | Line 1164 | public class Vector<E>
1164       * (If {@code toIndex==fromIndex}, this operation has no effect.)
1165       */
1166      protected synchronized void removeRange(int fromIndex, int toIndex) {
1098        int numMoved = elementCount - toIndex;
1099        System.arraycopy(elementData, toIndex, elementData, fromIndex,
1100                         numMoved);
1101
1102        // Let gc do its work
1167          modCount++;
1168 <        int newElementCount = elementCount - (toIndex-fromIndex);
1169 <        while (elementCount != newElementCount)
1170 <            elementData[--elementCount] = null;
1168 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1169 >        // checkInvariants();
1170 >    }
1171 >
1172 >    /** Erases the gap from lo to hi, by sliding down following elements. */
1173 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1174 >        System.arraycopy(es, hi, es, lo, elementCount - hi);
1175 >        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1176 >            es[i] = null;
1177      }
1178  
1179      /**
1180 <     * Save the state of the {@code Vector} instance to a stream (that
1181 <     * is, serialize it).
1180 >     * Saves the state of the {@code Vector} instance to a stream
1181 >     * (that is, serializes it).
1182       * This method performs synchronization to ensure the consistency
1183       * of the serialized data.
1184 +     *
1185 +     * @param s the stream
1186 +     * @throws java.io.IOException if an I/O error occurs
1187       */
1188      private void writeObject(java.io.ObjectOutputStream s)
1189              throws java.io.IOException {
# Line 1212 | Line 1285 | public class Vector<E>
1285                  if (i >= size) {
1286                      return;
1287                  }
1288 <        @SuppressWarnings("unchecked")
1289 <                final E[] elementData = (E[]) Vector.this.elementData;
1217 <                if (i >= elementData.length) {
1288 >                final Object[] es = elementData;
1289 >                if (i >= es.length)
1290                      throw new ConcurrentModificationException();
1291 <                }
1292 <                while (i != size && modCount == expectedModCount) {
1221 <                    action.accept(elementData[i++]);
1222 <                }
1291 >                while (i < size && modCount == expectedModCount)
1292 >                    action.accept(elementAt(es, i++));
1293                  // update once at end of iteration to reduce heap write traffic
1294                  cursor = i;
1295                  lastRet = i - 1;
# Line 1286 | Line 1356 | public class Vector<E>
1356          }
1357      }
1358  
1359 +    /**
1360 +     * @throws NullPointerException {@inheritDoc}
1361 +     */
1362      @Override
1363      public synchronized void forEach(Consumer<? super E> action) {
1364          Objects.requireNonNull(action);
1365          final int expectedModCount = modCount;
1366 <        @SuppressWarnings("unchecked")
1294 <        final E[] elementData = (E[]) this.elementData;
1295 <        final int elementCount = this.elementCount;
1296 <        for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
1297 <            action.accept(elementData[i]);
1298 <        }
1299 <        if (modCount != expectedModCount) {
1300 <            throw new ConcurrentModificationException();
1301 <        }
1302 <    }
1303 <
1304 <    @Override
1305 <    @SuppressWarnings("unchecked")
1306 <    public synchronized boolean removeIf(Predicate<? super E> filter) {
1307 <        Objects.requireNonNull(filter);
1308 <        // figure out which elements are to be removed
1309 <        // any exception thrown from the filter predicate at this stage
1310 <        // will leave the collection unmodified
1311 <        int removeCount = 0;
1366 >        final Object[] es = elementData;
1367          final int size = elementCount;
1368 <        final BitSet removeSet = new BitSet(size);
1369 <        final int expectedModCount = modCount;
1370 <        for (int i=0; modCount == expectedModCount && i < size; i++) {
1316 <            @SuppressWarnings("unchecked")
1317 <            final E element = (E) elementData[i];
1318 <            if (filter.test(element)) {
1319 <                removeSet.set(i);
1320 <                removeCount++;
1321 <            }
1322 <        }
1323 <        if (modCount != expectedModCount) {
1368 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1369 >            action.accept(elementAt(es, i));
1370 >        if (modCount != expectedModCount)
1371              throw new ConcurrentModificationException();
1372 <        }
1326 <
1327 <        // shift surviving elements left over the spaces left by removed elements
1328 <        final boolean anyToRemove = removeCount > 0;
1329 <        if (anyToRemove) {
1330 <            final int newSize = size - removeCount;
1331 <            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
1332 <                i = removeSet.nextClearBit(i);
1333 <                elementData[j] = elementData[i];
1334 <            }
1335 <            for (int k=newSize; k < size; k++) {
1336 <                elementData[k] = null;  // Let gc do its work
1337 <            }
1338 <            elementCount = newSize;
1339 <            if (modCount != expectedModCount) {
1340 <                throw new ConcurrentModificationException();
1341 <            }
1342 <            modCount++;
1343 <        }
1344 <
1345 <        return anyToRemove;
1372 >        // checkInvariants();
1373      }
1374  
1375 +    /**
1376 +     * @throws NullPointerException {@inheritDoc}
1377 +     */
1378      @Override
1349    @SuppressWarnings("unchecked")
1379      public synchronized void replaceAll(UnaryOperator<E> operator) {
1380          Objects.requireNonNull(operator);
1381          final int expectedModCount = modCount;
1382 +        final Object[] es = elementData;
1383          final int size = elementCount;
1384 <        for (int i=0; modCount == expectedModCount && i < size; i++) {
1385 <            elementData[i] = operator.apply((E) elementData[i]);
1386 <        }
1357 <        if (modCount != expectedModCount) {
1384 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1385 >            es[i] = operator.apply(elementAt(es, i));
1386 >        if (modCount != expectedModCount)
1387              throw new ConcurrentModificationException();
1359        }
1388          modCount++;
1389 +        // checkInvariants();
1390      }
1391  
1392      @SuppressWarnings("unchecked")
# Line 1365 | Line 1394 | public class Vector<E>
1394      public synchronized void sort(Comparator<? super E> c) {
1395          final int expectedModCount = modCount;
1396          Arrays.sort((E[]) elementData, 0, elementCount, c);
1397 <        if (modCount != expectedModCount) {
1397 >        if (modCount != expectedModCount)
1398              throw new ConcurrentModificationException();
1370        }
1399          modCount++;
1400 +        // checkInvariants();
1401      }
1402  
1403      /**
# Line 1386 | Line 1415 | public class Vector<E>
1415       */
1416      @Override
1417      public Spliterator<E> spliterator() {
1418 <        return new VectorSpliterator<>(this, null, 0, -1, 0);
1418 >        return new VectorSpliterator(null, 0, -1, 0);
1419      }
1420  
1421      /** Similar to ArrayList Spliterator */
1422 <    static final class VectorSpliterator<E> implements Spliterator<E> {
1394 <        private final Vector<E> list;
1422 >    final class VectorSpliterator implements Spliterator<E> {
1423          private Object[] array;
1424          private int index; // current index, modified on advance/split
1425          private int fence; // -1 until used; then one past last index
1426          private int expectedModCount; // initialized when fence set
1427  
1428 <        /** Create new spliterator covering the given  range */
1429 <        VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
1428 >        /** Creates new spliterator covering the given range. */
1429 >        VectorSpliterator(Object[] array, int origin, int fence,
1430                            int expectedModCount) {
1403            this.list = list;
1431              this.array = array;
1432              this.index = origin;
1433              this.fence = fence;
# Line 1410 | Line 1437 | public class Vector<E>
1437          private int getFence() { // initialize on first use
1438              int hi;
1439              if ((hi = fence) < 0) {
1440 <                synchronized(list) {
1441 <                    array = list.elementData;
1442 <                    expectedModCount = list.modCount;
1443 <                    hi = fence = list.elementCount;
1440 >                synchronized (Vector.this) {
1441 >                    array = elementData;
1442 >                    expectedModCount = modCount;
1443 >                    hi = fence = elementCount;
1444                  }
1445              }
1446              return hi;
# Line 1422 | Line 1449 | public class Vector<E>
1449          public Spliterator<E> trySplit() {
1450              int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1451              return (lo >= mid) ? null :
1452 <                new VectorSpliterator<>(list, array, lo, index = mid,
1426 <                                        expectedModCount);
1452 >                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1453          }
1454  
1455          @SuppressWarnings("unchecked")
# Line 1434 | Line 1460 | public class Vector<E>
1460              if (getFence() > (i = index)) {
1461                  index = i + 1;
1462                  action.accept((E)array[i]);
1463 <                if (list.modCount != expectedModCount)
1463 >                if (modCount != expectedModCount)
1464                      throw new ConcurrentModificationException();
1465                  return true;
1466              }
# Line 1443 | Line 1469 | public class Vector<E>
1469  
1470          @SuppressWarnings("unchecked")
1471          public void forEachRemaining(Consumer<? super E> action) {
1446            int i, hi; // hoist accesses and checks from loop
1447            Vector<E> lst; Object[] a;
1472              if (action == null)
1473                  throw new NullPointerException();
1474 <            if ((lst = list) != null) {
1475 <                if ((hi = fence) < 0) {
1476 <                    synchronized(lst) {
1477 <                        expectedModCount = lst.modCount;
1478 <                        a = array = lst.elementData;
1479 <                        hi = fence = lst.elementCount;
1480 <                    }
1457 <                }
1458 <                else
1459 <                    a = array;
1460 <                if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
1461 <                    while (i < hi)
1462 <                        action.accept((E) a[i++]);
1463 <                    if (lst.modCount == expectedModCount)
1464 <                        return;
1465 <                }
1466 <            }
1467 <            throw new ConcurrentModificationException();
1474 >            final int hi = getFence();
1475 >            final Object[] a = array;
1476 >            int i;
1477 >            for (i = index, index = hi; i < hi; i++)
1478 >                action.accept((E) a[i]);
1479 >            if (modCount != expectedModCount)
1480 >                throw new ConcurrentModificationException();
1481          }
1482  
1483          public long estimateSize() {
# Line 1475 | Line 1488 | public class Vector<E>
1488              return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1489          }
1490      }
1491 +
1492 +    void checkInvariants() {
1493 +        // assert elementCount >= 0;
1494 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1495 +    }
1496   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines