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.33 by jsr166, Sun Nov 13 02:10:09 2016 UTC vs.
Revision 1.51 by jsr166, Tue May 22 15:51:31 2018 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
2 > * Copyright (c) 1994, 2018, Oracle and/or its affiliates. All rights reserved.
3   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5   * This code is free software; you can redistribute it and/or modify it
# Line 25 | Line 25
25  
26   package java.util;
27  
28 + import java.io.IOException;
29 + import java.io.ObjectInputStream;
30 + import java.io.StreamCorruptedException;
31   import java.util.function.Consumer;
32   import java.util.function.Predicate;
33   import java.util.function.UnaryOperator;
# Line 70 | Line 73 | import java.util.function.UnaryOperator;
73   *
74   * <p>As of the Java 2 platform v1.2, this class was retrofitted to
75   * implement the {@link List} interface, making it a member of the
76 < * <a href="{@docRoot}/../technotes/guides/collections/index.html">
76 > * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework">
77   * Java Collections Framework</a>.  Unlike the new collection
78   * implementations, {@code Vector} is synchronized.  If a thread-safe
79   * implementation is not needed, it is recommended to use {@link
# Line 306 | Line 309 | public class Vector<E>
309          modCount++;
310          if (newSize > elementData.length)
311              grow(newSize);
312 <        for (int i = newSize; i < elementCount; i++)
313 <            elementData[i] = null;
312 >        final Object[] es = elementData;
313 >        for (int to = elementCount, i = newSize; i < to; i++)
314 >            es[i] = null;
315          elementCount = newSize;
316      }
317  
# Line 585 | Line 589 | public class Vector<E>
589          modCount++;
590          elementCount--;
591          elementData[elementCount] = null; /* to let gc do its work */
592 +        // checkInvariants();
593      }
594  
595      /**
# Line 675 | Line 680 | public class Vector<E>
680       * method (which is part of the {@link List} interface).
681       */
682      public synchronized void removeAllElements() {
683 <        // Let gc do its work
684 <        for (int i = 0; i < elementCount; i++)
685 <            elementData[i] = null;
681 <
683 >        final Object[] es = elementData;
684 >        for (int to = elementCount, i = elementCount = 0; i < to; i++)
685 >            es[i] = null;
686          modCount++;
683        elementCount = 0;
687      }
688  
689      /**
# Line 693 | Line 696 | public class Vector<E>
696      public synchronized Object clone() {
697          try {
698              @SuppressWarnings("unchecked")
699 <                Vector<E> v = (Vector<E>) super.clone();
699 >            Vector<E> v = (Vector<E>) super.clone();
700              v.elementData = Arrays.copyOf(elementData, elementCount);
701              v.modCount = 0;
702              return v;
# Line 810 | Line 813 | public class Vector<E>
813              elementData = grow();
814          elementData[s] = e;
815          elementCount = s + 1;
816 +        // checkInvariants();
817      }
818  
819      /**
# Line 878 | Line 882 | public class Vector<E>
882                               numMoved);
883          elementData[--elementCount] = null; // Let gc do its work
884  
885 +        // checkInvariants();
886          return oldValue;
887      }
888  
# Line 933 | Line 938 | public class Vector<E>
938                  elementData = grow(s + numNew);
939              System.arraycopy(a, 0, elementData, s, numNew);
940              elementCount = s + numNew;
941 +            // checkInvariants();
942              return true;
943          }
944      }
# Line 983 | Line 989 | public class Vector<E>
989          return bulkRemove(e -> !c.contains(e));
990      }
991  
992 +    /**
993 +     * @throws NullPointerException {@inheritDoc}
994 +     */
995      @Override
996      public boolean removeIf(Predicate<? super E> filter) {
997          Objects.requireNonNull(filter);
# Line 1005 | Line 1014 | public class Vector<E>
1014          int expectedModCount = modCount;
1015          final Object[] es = elementData;
1016          final int end = elementCount;
1008        final boolean modified;
1017          int i;
1018          // Optimize for initial run of survivors
1019          for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
# Line 1013 | Line 1021 | public class Vector<E>
1021          // Tolerate predicates that reentrantly access the collection for
1022          // read (but writers still get CME), so traverse once to find
1023          // elements to delete, a second pass to physically expunge.
1024 <        if (modified = (i < end)) {
1017 <            expectedModCount++;
1018 <            modCount++;
1024 >        if (i < end) {
1025              final int beg = i;
1026              final long[] deathRow = nBits(end - beg);
1027              deathRow[0] = 1L;   // set bit 0
1028              for (i = beg + 1; i < end; i++)
1029                  if (filter.test(elementAt(es, i)))
1030                      setBit(deathRow, i - beg);
1031 +            if (modCount != expectedModCount)
1032 +                throw new ConcurrentModificationException();
1033 +            modCount++;
1034              int w = beg;
1035              for (i = beg; i < end; i++)
1036                  if (isClear(deathRow, i - beg))
1037                      es[w++] = es[i];
1038 <            Arrays.fill(es, elementCount = w, end, null);
1038 >            for (i = elementCount = w; i < end; i++)
1039 >                es[i] = null;
1040 >            // checkInvariants();
1041 >            return true;
1042 >        } else {
1043 >            if (modCount != expectedModCount)
1044 >                throw new ConcurrentModificationException();
1045 >            // checkInvariants();
1046 >            return false;
1047          }
1031        if (modCount != expectedModCount)
1032            throw new ConcurrentModificationException();
1033        return modified;
1048      }
1049  
1050      /**
# Line 1071 | Line 1085 | public class Vector<E>
1085                               numMoved);
1086          System.arraycopy(a, 0, elementData, index, numNew);
1087          elementCount = s + numNew;
1088 +        // checkInvariants();
1089          return true;
1090      }
1091  
# Line 1152 | Line 1167 | public class Vector<E>
1167       * (If {@code toIndex==fromIndex}, this operation has no effect.)
1168       */
1169      protected synchronized void removeRange(int fromIndex, int toIndex) {
1155        int numMoved = elementCount - toIndex;
1156        System.arraycopy(elementData, toIndex, elementData, fromIndex,
1157                         numMoved);
1158
1159        // Let gc do its work
1170          modCount++;
1171 <        int newElementCount = elementCount - (toIndex-fromIndex);
1172 <        while (elementCount != newElementCount)
1173 <            elementData[--elementCount] = null;
1171 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1172 >        // checkInvariants();
1173 >    }
1174 >
1175 >    /** Erases the gap from lo to hi, by sliding down following elements. */
1176 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1177 >        System.arraycopy(es, hi, es, lo, elementCount - hi);
1178 >        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1179 >            es[i] = null;
1180      }
1181  
1182      /**
1183 <     * Save the state of the {@code Vector} instance to a stream (that
1184 <     * is, serialize it).
1183 >     * Loads a {@code Vector} instance from a stream
1184 >     * (that is, deserializes it).
1185 >     * This method performs checks to ensure the consistency
1186 >     * of the fields.
1187 >     *
1188 >     * @param in the stream
1189 >     * @throws java.io.IOException if an I/O error occurs
1190 >     * @throws ClassNotFoundException if the stream contains data
1191 >     *         of a non-existing class
1192 >     */
1193 >    private void readObject(ObjectInputStream in)
1194 >            throws IOException, ClassNotFoundException {
1195 >        ObjectInputStream.GetField gfields = in.readFields();
1196 >        int count = gfields.get("elementCount", 0);
1197 >        Object[] data = (Object[])gfields.get("elementData", null);
1198 >        if (count < 0 || data == null || count > data.length) {
1199 >            throw new StreamCorruptedException("Inconsistent vector internals");
1200 >        }
1201 >        elementCount = count;
1202 >        elementData = data.clone();
1203 >    }
1204 >
1205 >    /**
1206 >     * Saves the state of the {@code Vector} instance to a stream
1207 >     * (that is, serializes it).
1208       * This method performs synchronization to ensure the consistency
1209       * of the serialized data.
1210 +     *
1211 +     * @param s the stream
1212 +     * @throws java.io.IOException if an I/O error occurs
1213       */
1214      private void writeObject(java.io.ObjectOutputStream s)
1215              throws java.io.IOException {
# Line 1269 | Line 1311 | public class Vector<E>
1311                  if (i >= size) {
1312                      return;
1313                  }
1314 <        @SuppressWarnings("unchecked")
1315 <                final E[] elementData = (E[]) Vector.this.elementData;
1274 <                if (i >= elementData.length) {
1314 >                final Object[] es = elementData;
1315 >                if (i >= es.length)
1316                      throw new ConcurrentModificationException();
1317 <                }
1318 <                while (i != size && modCount == expectedModCount) {
1278 <                    action.accept(elementData[i++]);
1279 <                }
1317 >                while (i < size && modCount == expectedModCount)
1318 >                    action.accept(elementAt(es, i++));
1319                  // update once at end of iteration to reduce heap write traffic
1320                  cursor = i;
1321                  lastRet = i - 1;
# Line 1343 | Line 1382 | public class Vector<E>
1382          }
1383      }
1384  
1385 +    /**
1386 +     * @throws NullPointerException {@inheritDoc}
1387 +     */
1388      @Override
1389      public synchronized void forEach(Consumer<? super E> action) {
1390          Objects.requireNonNull(action);
1391          final int expectedModCount = modCount;
1392 <        @SuppressWarnings("unchecked")
1393 <        final E[] elementData = (E[]) this.elementData;
1394 <        final int elementCount = this.elementCount;
1395 <        for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
1396 <            action.accept(elementData[i]);
1355 <        }
1356 <        if (modCount != expectedModCount) {
1392 >        final Object[] es = elementData;
1393 >        final int size = elementCount;
1394 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1395 >            action.accept(elementAt(es, i));
1396 >        if (modCount != expectedModCount)
1397              throw new ConcurrentModificationException();
1398 <        }
1398 >        // checkInvariants();
1399      }
1400  
1401 +    /**
1402 +     * @throws NullPointerException {@inheritDoc}
1403 +     */
1404      @Override
1362    @SuppressWarnings("unchecked")
1405      public synchronized void replaceAll(UnaryOperator<E> operator) {
1406          Objects.requireNonNull(operator);
1407          final int expectedModCount = modCount;
1408 +        final Object[] es = elementData;
1409          final int size = elementCount;
1410 <        for (int i=0; modCount == expectedModCount && i < size; i++) {
1411 <            elementData[i] = operator.apply((E) elementData[i]);
1412 <        }
1370 <        if (modCount != expectedModCount) {
1410 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1411 >            es[i] = operator.apply(elementAt(es, i));
1412 >        if (modCount != expectedModCount)
1413              throw new ConcurrentModificationException();
1372        }
1414          modCount++;
1415 +        // checkInvariants();
1416      }
1417  
1418      @SuppressWarnings("unchecked")
# Line 1378 | Line 1420 | public class Vector<E>
1420      public synchronized void sort(Comparator<? super E> c) {
1421          final int expectedModCount = modCount;
1422          Arrays.sort((E[]) elementData, 0, elementCount, c);
1423 <        if (modCount != expectedModCount) {
1423 >        if (modCount != expectedModCount)
1424              throw new ConcurrentModificationException();
1383        }
1425          modCount++;
1426 +        // checkInvariants();
1427      }
1428  
1429      /**
# Line 1399 | Line 1441 | public class Vector<E>
1441       */
1442      @Override
1443      public Spliterator<E> spliterator() {
1444 <        return new VectorSpliterator<>(this, null, 0, -1, 0);
1444 >        return new VectorSpliterator(null, 0, -1, 0);
1445      }
1446  
1447      /** Similar to ArrayList Spliterator */
1448 <    static final class VectorSpliterator<E> implements Spliterator<E> {
1407 <        private final Vector<E> list;
1448 >    final class VectorSpliterator implements Spliterator<E> {
1449          private Object[] array;
1450          private int index; // current index, modified on advance/split
1451          private int fence; // -1 until used; then one past last index
1452          private int expectedModCount; // initialized when fence set
1453  
1454 <        /** Create new spliterator covering the given  range */
1455 <        VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
1454 >        /** Creates new spliterator covering the given range. */
1455 >        VectorSpliterator(Object[] array, int origin, int fence,
1456                            int expectedModCount) {
1416            this.list = list;
1457              this.array = array;
1458              this.index = origin;
1459              this.fence = fence;
# Line 1423 | Line 1463 | public class Vector<E>
1463          private int getFence() { // initialize on first use
1464              int hi;
1465              if ((hi = fence) < 0) {
1466 <                synchronized (list) {
1467 <                    array = list.elementData;
1468 <                    expectedModCount = list.modCount;
1469 <                    hi = fence = list.elementCount;
1466 >                synchronized (Vector.this) {
1467 >                    array = elementData;
1468 >                    expectedModCount = modCount;
1469 >                    hi = fence = elementCount;
1470                  }
1471              }
1472              return hi;
# Line 1435 | Line 1475 | public class Vector<E>
1475          public Spliterator<E> trySplit() {
1476              int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1477              return (lo >= mid) ? null :
1478 <                new VectorSpliterator<>(list, array, lo, index = mid,
1439 <                                        expectedModCount);
1478 >                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1479          }
1480  
1481          @SuppressWarnings("unchecked")
1482          public boolean tryAdvance(Consumer<? super E> action) {
1483 +            Objects.requireNonNull(action);
1484              int i;
1445            if (action == null)
1446                throw new NullPointerException();
1485              if (getFence() > (i = index)) {
1486                  index = i + 1;
1487                  action.accept((E)array[i]);
1488 <                if (list.modCount != expectedModCount)
1488 >                if (modCount != expectedModCount)
1489                      throw new ConcurrentModificationException();
1490                  return true;
1491              }
# Line 1456 | Line 1494 | public class Vector<E>
1494  
1495          @SuppressWarnings("unchecked")
1496          public void forEachRemaining(Consumer<? super E> action) {
1497 <            int i, hi; // hoist accesses and checks from loop
1498 <            Vector<E> lst; Object[] a;
1499 <            if (action == null)
1500 <                throw new NullPointerException();
1501 <            if ((lst = list) != null) {
1502 <                if ((hi = fence) < 0) {
1503 <                    synchronized (lst) {
1504 <                        expectedModCount = lst.modCount;
1467 <                        a = array = lst.elementData;
1468 <                        hi = fence = lst.elementCount;
1469 <                    }
1470 <                }
1471 <                else
1472 <                    a = array;
1473 <                if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
1474 <                    while (i < hi)
1475 <                        action.accept((E) a[i++]);
1476 <                    if (lst.modCount == expectedModCount)
1477 <                        return;
1478 <                }
1479 <            }
1480 <            throw new ConcurrentModificationException();
1497 >            Objects.requireNonNull(action);
1498 >            final int hi = getFence();
1499 >            final Object[] a = array;
1500 >            int i;
1501 >            for (i = index, index = hi; i < hi; i++)
1502 >                action.accept((E) a[i]);
1503 >            if (modCount != expectedModCount)
1504 >                throw new ConcurrentModificationException();
1505          }
1506  
1507          public long estimateSize() {
# Line 1488 | Line 1512 | public class Vector<E>
1512              return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1513          }
1514      }
1515 +
1516 +    void checkInvariants() {
1517 +        // assert elementCount >= 0;
1518 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1519 +    }
1520   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines