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.34 by jsr166, Sun Nov 13 19:58:47 2016 UTC vs.
Revision 1.56 by jsr166, Fri Aug 30 18:05:39 2019 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
2 > * Copyright (c) 1994, 2019, 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;
34  
35 + import jdk.internal.util.ArraysSupport;
36 +
37   /**
38   * The {@code Vector} class implements a growable array of
39   * objects. Like an array, it contains components that can be
# Line 70 | Line 75 | import java.util.function.UnaryOperator;
75   *
76   * <p>As of the Java 2 platform v1.2, this class was retrofitted to
77   * implement the {@link List} interface, making it a member of the
78 < * <a href="{@docRoot}/../technotes/guides/collections/index.html">
78 > * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
79   * Java Collections Framework</a>.  Unlike the new collection
80   * implementations, {@code Vector} is synchronized.  If a thread-safe
81   * implementation is not needed, it is recommended to use {@link
# Line 119 | Line 124 | public class Vector<E>
124      protected int capacityIncrement;
125  
126      /** use serialVersionUID from JDK 1.0.2 for interoperability */
127 +    // OPENJDK @java.io.Serial
128      private static final long serialVersionUID = -2767605614048989439L;
129  
130      /**
# Line 239 | Line 245 | public class Vector<E>
245      }
246  
247      /**
242     * The maximum size of array to allocate (unless necessary).
243     * Some VMs reserve some header words in an array.
244     * Attempts to allocate larger arrays may result in
245     * OutOfMemoryError: Requested array size exceeds VM limit
246     */
247    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
248
249    /**
248       * Increases the capacity to ensure that it can hold at least the
249       * number of elements specified by the minimum capacity argument.
250       *
# Line 254 | Line 252 | public class Vector<E>
252       * @throws OutOfMemoryError if minCapacity is less than zero
253       */
254      private Object[] grow(int minCapacity) {
255 <        return elementData = Arrays.copyOf(elementData,
256 <                                           newCapacity(minCapacity));
255 >        int oldCapacity = elementData.length;
256 >        int newCapacity = ArraysSupport.newLength(oldCapacity,
257 >                minCapacity - oldCapacity, /* minimum growth */
258 >                capacityIncrement > 0 ? capacityIncrement : oldCapacity
259 >                                           /* preferred growth */);
260 >        return elementData = Arrays.copyOf(elementData, newCapacity);
261      }
262  
263      private Object[] grow() {
# Line 263 | Line 265 | public class Vector<E>
265      }
266  
267      /**
266     * Returns a capacity at least as large as the given minimum capacity.
267     * Will not return a capacity greater than MAX_ARRAY_SIZE unless
268     * the given minimum capacity is greater than MAX_ARRAY_SIZE.
269     *
270     * @param minCapacity the desired minimum capacity
271     * @throws OutOfMemoryError if minCapacity is less than zero
272     */
273    private int newCapacity(int minCapacity) {
274        // overflow-conscious code
275        int oldCapacity = elementData.length;
276        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
277                                         capacityIncrement : oldCapacity);
278        if (newCapacity - minCapacity <= 0) {
279            if (minCapacity < 0) // overflow
280                throw new OutOfMemoryError();
281            return minCapacity;
282        }
283        return (newCapacity - MAX_ARRAY_SIZE <= 0)
284            ? newCapacity
285            : hugeCapacity(minCapacity);
286    }
287
288    private static int hugeCapacity(int minCapacity) {
289        if (minCapacity < 0) // overflow
290            throw new OutOfMemoryError();
291        return (minCapacity > MAX_ARRAY_SIZE) ?
292            Integer.MAX_VALUE :
293            MAX_ARRAY_SIZE;
294    }
295
296    /**
268       * Sets the size of this vector. If the new size is greater than the
269       * current size, new {@code null} items are added to the end of
270       * the vector. If the new size is less than the current size, all
# Line 306 | Line 277 | public class Vector<E>
277          modCount++;
278          if (newSize > elementData.length)
279              grow(newSize);
280 <        for (int i = newSize; i < elementCount; i++)
281 <            elementData[i] = null;
280 >        final Object[] es = elementData;
281 >        for (int to = elementCount, i = newSize; i < to; i++)
282 >            es[i] = null;
283          elementCount = newSize;
284      }
285  
# Line 585 | Line 557 | public class Vector<E>
557          modCount++;
558          elementCount--;
559          elementData[elementCount] = null; /* to let gc do its work */
560 +        // checkInvariants();
561      }
562  
563      /**
# Line 675 | Line 648 | public class Vector<E>
648       * method (which is part of the {@link List} interface).
649       */
650      public synchronized void removeAllElements() {
651 <        // Let gc do its work
652 <        for (int i = 0; i < elementCount; i++)
653 <            elementData[i] = null;
681 <
651 >        final Object[] es = elementData;
652 >        for (int to = elementCount, i = elementCount = 0; i < to; i++)
653 >            es[i] = null;
654          modCount++;
683        elementCount = 0;
655      }
656  
657      /**
# Line 810 | Line 781 | public class Vector<E>
781              elementData = grow();
782          elementData[s] = e;
783          elementCount = s + 1;
784 +        // checkInvariants();
785      }
786  
787      /**
# Line 878 | Line 850 | public class Vector<E>
850                               numMoved);
851          elementData[--elementCount] = null; // Let gc do its work
852  
853 +        // checkInvariants();
854          return oldValue;
855      }
856  
# Line 933 | Line 906 | public class Vector<E>
906                  elementData = grow(s + numNew);
907              System.arraycopy(a, 0, elementData, s, numNew);
908              elementCount = s + numNew;
909 +            // checkInvariants();
910              return true;
911          }
912      }
# Line 983 | Line 957 | public class Vector<E>
957          return bulkRemove(e -> !c.contains(e));
958      }
959  
960 +    /**
961 +     * @throws NullPointerException {@inheritDoc}
962 +     */
963      @Override
964      public boolean removeIf(Predicate<? super E> filter) {
965          Objects.requireNonNull(filter);
# Line 1005 | Line 982 | public class Vector<E>
982          int expectedModCount = modCount;
983          final Object[] es = elementData;
984          final int end = elementCount;
1008        final boolean modified;
985          int i;
986          // Optimize for initial run of survivors
987          for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
# Line 1013 | Line 989 | public class Vector<E>
989          // Tolerate predicates that reentrantly access the collection for
990          // read (but writers still get CME), so traverse once to find
991          // elements to delete, a second pass to physically expunge.
992 <        if (modified = (i < end)) {
1017 <            expectedModCount++;
1018 <            modCount++;
992 >        if (i < end) {
993              final int beg = i;
994              final long[] deathRow = nBits(end - beg);
995              deathRow[0] = 1L;   // set bit 0
996              for (i = beg + 1; i < end; i++)
997                  if (filter.test(elementAt(es, i)))
998                      setBit(deathRow, i - beg);
999 +            if (modCount != expectedModCount)
1000 +                throw new ConcurrentModificationException();
1001 +            modCount++;
1002              int w = beg;
1003              for (i = beg; i < end; i++)
1004                  if (isClear(deathRow, i - beg))
1005                      es[w++] = es[i];
1006 <            Arrays.fill(es, elementCount = w, end, null);
1006 >            for (i = elementCount = w; i < end; i++)
1007 >                es[i] = null;
1008 >            // checkInvariants();
1009 >            return true;
1010 >        } else {
1011 >            if (modCount != expectedModCount)
1012 >                throw new ConcurrentModificationException();
1013 >            // checkInvariants();
1014 >            return false;
1015          }
1031        if (modCount != expectedModCount)
1032            throw new ConcurrentModificationException();
1033        return modified;
1016      }
1017  
1018      /**
# Line 1071 | Line 1053 | public class Vector<E>
1053                               numMoved);
1054          System.arraycopy(a, 0, elementData, index, numNew);
1055          elementCount = s + numNew;
1056 +        // checkInvariants();
1057          return true;
1058      }
1059  
# Line 1152 | Line 1135 | public class Vector<E>
1135       * (If {@code toIndex==fromIndex}, this operation has no effect.)
1136       */
1137      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
1138          modCount++;
1139 <        int newElementCount = elementCount - (toIndex-fromIndex);
1140 <        while (elementCount != newElementCount)
1141 <            elementData[--elementCount] = null;
1139 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1140 >        // checkInvariants();
1141 >    }
1142 >
1143 >    /** Erases the gap from lo to hi, by sliding down following elements. */
1144 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1145 >        System.arraycopy(es, hi, es, lo, elementCount - hi);
1146 >        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1147 >            es[i] = null;
1148      }
1149  
1150      /**
1151 <     * Save the state of the {@code Vector} instance to a stream (that
1152 <     * is, serialize it).
1151 >     * Loads a {@code Vector} instance from a stream
1152 >     * (that is, deserializes it).
1153 >     * This method performs checks to ensure the consistency
1154 >     * of the fields.
1155 >     *
1156 >     * @param in the stream
1157 >     * @throws java.io.IOException if an I/O error occurs
1158 >     * @throws ClassNotFoundException if the stream contains data
1159 >     *         of a non-existing class
1160 >     */
1161 >    // OPENJDK @java.io.Serial
1162 >    private void readObject(ObjectInputStream in)
1163 >            throws IOException, ClassNotFoundException {
1164 >        ObjectInputStream.GetField gfields = in.readFields();
1165 >        int count = gfields.get("elementCount", 0);
1166 >        Object[] data = (Object[])gfields.get("elementData", null);
1167 >        if (count < 0 || data == null || count > data.length) {
1168 >            throw new StreamCorruptedException("Inconsistent vector internals");
1169 >        }
1170 >        elementCount = count;
1171 >        elementData = data.clone();
1172 >    }
1173 >
1174 >    /**
1175 >     * Saves the state of the {@code Vector} instance to a stream
1176 >     * (that is, serializes it).
1177       * This method performs synchronization to ensure the consistency
1178       * of the serialized data.
1179 +     *
1180 +     * @param s the stream
1181 +     * @throws java.io.IOException if an I/O error occurs
1182       */
1183 +    // OPENJDK @java.io.Serial
1184      private void writeObject(java.io.ObjectOutputStream s)
1185              throws java.io.IOException {
1186          final java.io.ObjectOutputStream.PutField fields = s.putFields();
# Line 1340 | Line 1352 | public class Vector<E>
1352          }
1353      }
1354  
1355 +    /**
1356 +     * @throws NullPointerException {@inheritDoc}
1357 +     */
1358      @Override
1359      public synchronized void forEach(Consumer<? super E> action) {
1360          Objects.requireNonNull(action);
# Line 1350 | Line 1365 | public class Vector<E>
1365              action.accept(elementAt(es, i));
1366          if (modCount != expectedModCount)
1367              throw new ConcurrentModificationException();
1368 +        // checkInvariants();
1369      }
1370  
1371 +    /**
1372 +     * @throws NullPointerException {@inheritDoc}
1373 +     */
1374      @Override
1375      public synchronized void replaceAll(UnaryOperator<E> operator) {
1376          Objects.requireNonNull(operator);
# Line 1362 | Line 1381 | public class Vector<E>
1381              es[i] = operator.apply(elementAt(es, i));
1382          if (modCount != expectedModCount)
1383              throw new ConcurrentModificationException();
1384 +        // TODO(8203662): remove increment of modCount from ...
1385          modCount++;
1386 +        // checkInvariants();
1387      }
1388  
1389      @SuppressWarnings("unchecked")
# Line 1370 | Line 1391 | public class Vector<E>
1391      public synchronized void sort(Comparator<? super E> c) {
1392          final int expectedModCount = modCount;
1393          Arrays.sort((E[]) elementData, 0, elementCount, c);
1394 <        if (modCount != expectedModCount) {
1394 >        if (modCount != expectedModCount)
1395              throw new ConcurrentModificationException();
1375        }
1396          modCount++;
1397 +        // checkInvariants();
1398      }
1399  
1400      /**
# Line 1391 | Line 1412 | public class Vector<E>
1412       */
1413      @Override
1414      public Spliterator<E> spliterator() {
1415 <        return new VectorSpliterator<>(this, null, 0, -1, 0);
1415 >        return new VectorSpliterator(null, 0, -1, 0);
1416      }
1417  
1418      /** Similar to ArrayList Spliterator */
1419 <    static final class VectorSpliterator<E> implements Spliterator<E> {
1399 <        private final Vector<E> list;
1419 >    final class VectorSpliterator implements Spliterator<E> {
1420          private Object[] array;
1421          private int index; // current index, modified on advance/split
1422          private int fence; // -1 until used; then one past last index
1423          private int expectedModCount; // initialized when fence set
1424  
1425 <        /** Create new spliterator covering the given range */
1426 <        VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
1425 >        /** Creates new spliterator covering the given range. */
1426 >        VectorSpliterator(Object[] array, int origin, int fence,
1427                            int expectedModCount) {
1408            this.list = list;
1428              this.array = array;
1429              this.index = origin;
1430              this.fence = fence;
# Line 1415 | Line 1434 | public class Vector<E>
1434          private int getFence() { // initialize on first use
1435              int hi;
1436              if ((hi = fence) < 0) {
1437 <                synchronized (list) {
1438 <                    array = list.elementData;
1439 <                    expectedModCount = list.modCount;
1440 <                    hi = fence = list.elementCount;
1437 >                synchronized (Vector.this) {
1438 >                    array = elementData;
1439 >                    expectedModCount = modCount;
1440 >                    hi = fence = elementCount;
1441                  }
1442              }
1443              return hi;
# Line 1427 | Line 1446 | public class Vector<E>
1446          public Spliterator<E> trySplit() {
1447              int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1448              return (lo >= mid) ? null :
1449 <                new VectorSpliterator<>(list, array, lo, index = mid,
1431 <                                        expectedModCount);
1449 >                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1450          }
1451  
1452          @SuppressWarnings("unchecked")
1453          public boolean tryAdvance(Consumer<? super E> action) {
1454 +            Objects.requireNonNull(action);
1455              int i;
1437            if (action == null)
1438                throw new NullPointerException();
1456              if (getFence() > (i = index)) {
1457                  index = i + 1;
1458                  action.accept((E)array[i]);
1459 <                if (list.modCount != expectedModCount)
1459 >                if (modCount != expectedModCount)
1460                      throw new ConcurrentModificationException();
1461                  return true;
1462              }
# Line 1448 | Line 1465 | public class Vector<E>
1465  
1466          @SuppressWarnings("unchecked")
1467          public void forEachRemaining(Consumer<? super E> action) {
1468 <            int i, hi; // hoist accesses and checks from loop
1469 <            Vector<E> lst; Object[] a;
1470 <            if (action == null)
1471 <                throw new NullPointerException();
1472 <            if ((lst = list) != null) {
1473 <                if ((hi = fence) < 0) {
1474 <                    synchronized (lst) {
1475 <                        expectedModCount = lst.modCount;
1459 <                        a = array = lst.elementData;
1460 <                        hi = fence = lst.elementCount;
1461 <                    }
1462 <                }
1463 <                else
1464 <                    a = array;
1465 <                if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
1466 <                    while (i < hi)
1467 <                        action.accept((E) a[i++]);
1468 <                    if (lst.modCount == expectedModCount)
1469 <                        return;
1470 <                }
1471 <            }
1472 <            throw new ConcurrentModificationException();
1468 >            Objects.requireNonNull(action);
1469 >            final int hi = getFence();
1470 >            final Object[] a = array;
1471 >            int i;
1472 >            for (i = index, index = hi; i < hi; i++)
1473 >                action.accept((E) a[i]);
1474 >            if (modCount != expectedModCount)
1475 >                throw new ConcurrentModificationException();
1476          }
1477  
1478          public long estimateSize() {
# Line 1480 | Line 1483 | public class Vector<E>
1483              return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1484          }
1485      }
1486 +
1487 +    void checkInvariants() {
1488 +        // assert elementCount >= 0;
1489 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1490 +    }
1491   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines