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.57 by jsr166, Thu Oct 10 16:53:08 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 97 | Line 102 | public class Vector<E>
102       *
103       * @serial
104       */
105 +    @SuppressWarnings("serial") // Conditionally serializable
106      protected Object[] elementData;
107  
108      /**
# Line 119 | Line 125 | public class Vector<E>
125      protected int capacityIncrement;
126  
127      /** use serialVersionUID from JDK 1.0.2 for interoperability */
128 +    // OPENJDK @java.io.Serial
129      private static final long serialVersionUID = -2767605614048989439L;
130  
131      /**
# Line 239 | Line 246 | public class Vector<E>
246      }
247  
248      /**
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    /**
249       * Increases the capacity to ensure that it can hold at least the
250       * number of elements specified by the minimum capacity argument.
251       *
# Line 254 | Line 253 | public class Vector<E>
253       * @throws OutOfMemoryError if minCapacity is less than zero
254       */
255      private Object[] grow(int minCapacity) {
256 <        return elementData = Arrays.copyOf(elementData,
257 <                                           newCapacity(minCapacity));
256 >        int oldCapacity = elementData.length;
257 >        int newCapacity = ArraysSupport.newLength(oldCapacity,
258 >                minCapacity - oldCapacity, /* minimum growth */
259 >                capacityIncrement > 0 ? capacityIncrement : oldCapacity
260 >                                           /* preferred growth */);
261 >        return elementData = Arrays.copyOf(elementData, newCapacity);
262      }
263  
264      private Object[] grow() {
# Line 263 | Line 266 | public class Vector<E>
266      }
267  
268      /**
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    /**
269       * Sets the size of this vector. If the new size is greater than the
270       * current size, new {@code null} items are added to the end of
271       * the vector. If the new size is less than the current size, all
# Line 306 | Line 278 | public class Vector<E>
278          modCount++;
279          if (newSize > elementData.length)
280              grow(newSize);
281 <        for (int i = newSize; i < elementCount; i++)
282 <            elementData[i] = null;
281 >        final Object[] es = elementData;
282 >        for (int to = elementCount, i = newSize; i < to; i++)
283 >            es[i] = null;
284          elementCount = newSize;
285      }
286  
# Line 585 | Line 558 | public class Vector<E>
558          modCount++;
559          elementCount--;
560          elementData[elementCount] = null; /* to let gc do its work */
561 +        // checkInvariants();
562      }
563  
564      /**
# Line 675 | Line 649 | public class Vector<E>
649       * method (which is part of the {@link List} interface).
650       */
651      public synchronized void removeAllElements() {
652 <        // Let gc do its work
653 <        for (int i = 0; i < elementCount; i++)
654 <            elementData[i] = null;
681 <
652 >        final Object[] es = elementData;
653 >        for (int to = elementCount, i = elementCount = 0; i < to; i++)
654 >            es[i] = null;
655          modCount++;
683        elementCount = 0;
656      }
657  
658      /**
# Line 810 | Line 782 | public class Vector<E>
782              elementData = grow();
783          elementData[s] = e;
784          elementCount = s + 1;
785 +        // checkInvariants();
786      }
787  
788      /**
# Line 878 | Line 851 | public class Vector<E>
851                               numMoved);
852          elementData[--elementCount] = null; // Let gc do its work
853  
854 +        // checkInvariants();
855          return oldValue;
856      }
857  
# Line 933 | Line 907 | public class Vector<E>
907                  elementData = grow(s + numNew);
908              System.arraycopy(a, 0, elementData, s, numNew);
909              elementCount = s + numNew;
910 +            // checkInvariants();
911              return true;
912          }
913      }
# Line 983 | Line 958 | public class Vector<E>
958          return bulkRemove(e -> !c.contains(e));
959      }
960  
961 +    /**
962 +     * @throws NullPointerException {@inheritDoc}
963 +     */
964      @Override
965      public boolean removeIf(Predicate<? super E> filter) {
966          Objects.requireNonNull(filter);
# Line 1005 | Line 983 | public class Vector<E>
983          int expectedModCount = modCount;
984          final Object[] es = elementData;
985          final int end = elementCount;
1008        final boolean modified;
986          int i;
987          // Optimize for initial run of survivors
988          for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
# Line 1013 | Line 990 | public class Vector<E>
990          // Tolerate predicates that reentrantly access the collection for
991          // read (but writers still get CME), so traverse once to find
992          // elements to delete, a second pass to physically expunge.
993 <        if (modified = (i < end)) {
1017 <            expectedModCount++;
1018 <            modCount++;
993 >        if (i < end) {
994              final int beg = i;
995              final long[] deathRow = nBits(end - beg);
996              deathRow[0] = 1L;   // set bit 0
997              for (i = beg + 1; i < end; i++)
998                  if (filter.test(elementAt(es, i)))
999                      setBit(deathRow, i - beg);
1000 +            if (modCount != expectedModCount)
1001 +                throw new ConcurrentModificationException();
1002 +            modCount++;
1003              int w = beg;
1004              for (i = beg; i < end; i++)
1005                  if (isClear(deathRow, i - beg))
1006                      es[w++] = es[i];
1007 <            Arrays.fill(es, elementCount = w, end, null);
1007 >            for (i = elementCount = w; i < end; i++)
1008 >                es[i] = null;
1009 >            // checkInvariants();
1010 >            return true;
1011 >        } else {
1012 >            if (modCount != expectedModCount)
1013 >                throw new ConcurrentModificationException();
1014 >            // checkInvariants();
1015 >            return false;
1016          }
1031        if (modCount != expectedModCount)
1032            throw new ConcurrentModificationException();
1033        return modified;
1017      }
1018  
1019      /**
# Line 1071 | Line 1054 | public class Vector<E>
1054                               numMoved);
1055          System.arraycopy(a, 0, elementData, index, numNew);
1056          elementCount = s + numNew;
1057 +        // checkInvariants();
1058          return true;
1059      }
1060  
# Line 1152 | Line 1136 | public class Vector<E>
1136       * (If {@code toIndex==fromIndex}, this operation has no effect.)
1137       */
1138      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
1139          modCount++;
1140 <        int newElementCount = elementCount - (toIndex-fromIndex);
1141 <        while (elementCount != newElementCount)
1142 <            elementData[--elementCount] = null;
1140 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1141 >        // checkInvariants();
1142 >    }
1143 >
1144 >    /** Erases the gap from lo to hi, by sliding down following elements. */
1145 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1146 >        System.arraycopy(es, hi, es, lo, elementCount - hi);
1147 >        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1148 >            es[i] = null;
1149      }
1150  
1151      /**
1152 <     * Save the state of the {@code Vector} instance to a stream (that
1153 <     * is, serialize it).
1152 >     * Loads a {@code Vector} instance from a stream
1153 >     * (that is, deserializes it).
1154 >     * This method performs checks to ensure the consistency
1155 >     * of the fields.
1156 >     *
1157 >     * @param in the stream
1158 >     * @throws java.io.IOException if an I/O error occurs
1159 >     * @throws ClassNotFoundException if the stream contains data
1160 >     *         of a non-existing class
1161 >     */
1162 >    // OPENJDK @java.io.Serial
1163 >    private void readObject(ObjectInputStream in)
1164 >            throws IOException, ClassNotFoundException {
1165 >        ObjectInputStream.GetField gfields = in.readFields();
1166 >        int count = gfields.get("elementCount", 0);
1167 >        Object[] data = (Object[])gfields.get("elementData", null);
1168 >        if (count < 0 || data == null || count > data.length) {
1169 >            throw new StreamCorruptedException("Inconsistent vector internals");
1170 >        }
1171 >        elementCount = count;
1172 >        elementData = data.clone();
1173 >    }
1174 >
1175 >    /**
1176 >     * Saves the state of the {@code Vector} instance to a stream
1177 >     * (that is, serializes it).
1178       * This method performs synchronization to ensure the consistency
1179       * of the serialized data.
1180 +     *
1181 +     * @param s the stream
1182 +     * @throws java.io.IOException if an I/O error occurs
1183       */
1184 +    // OPENJDK @java.io.Serial
1185      private void writeObject(java.io.ObjectOutputStream s)
1186              throws java.io.IOException {
1187          final java.io.ObjectOutputStream.PutField fields = s.putFields();
# Line 1340 | Line 1353 | public class Vector<E>
1353          }
1354      }
1355  
1356 +    /**
1357 +     * @throws NullPointerException {@inheritDoc}
1358 +     */
1359      @Override
1360      public synchronized void forEach(Consumer<? super E> action) {
1361          Objects.requireNonNull(action);
# Line 1350 | Line 1366 | public class Vector<E>
1366              action.accept(elementAt(es, i));
1367          if (modCount != expectedModCount)
1368              throw new ConcurrentModificationException();
1369 +        // checkInvariants();
1370      }
1371  
1372 +    /**
1373 +     * @throws NullPointerException {@inheritDoc}
1374 +     */
1375      @Override
1376      public synchronized void replaceAll(UnaryOperator<E> operator) {
1377          Objects.requireNonNull(operator);
# Line 1362 | Line 1382 | public class Vector<E>
1382              es[i] = operator.apply(elementAt(es, i));
1383          if (modCount != expectedModCount)
1384              throw new ConcurrentModificationException();
1385 +        // TODO(8203662): remove increment of modCount from ...
1386          modCount++;
1387 +        // checkInvariants();
1388      }
1389  
1390      @SuppressWarnings("unchecked")
# Line 1370 | Line 1392 | public class Vector<E>
1392      public synchronized void sort(Comparator<? super E> c) {
1393          final int expectedModCount = modCount;
1394          Arrays.sort((E[]) elementData, 0, elementCount, c);
1395 <        if (modCount != expectedModCount) {
1395 >        if (modCount != expectedModCount)
1396              throw new ConcurrentModificationException();
1375        }
1397          modCount++;
1398 +        // checkInvariants();
1399      }
1400  
1401      /**
# Line 1391 | Line 1413 | public class Vector<E>
1413       */
1414      @Override
1415      public Spliterator<E> spliterator() {
1416 <        return new VectorSpliterator<>(this, null, 0, -1, 0);
1416 >        return new VectorSpliterator(null, 0, -1, 0);
1417      }
1418  
1419      /** Similar to ArrayList Spliterator */
1420 <    static final class VectorSpliterator<E> implements Spliterator<E> {
1399 <        private final Vector<E> list;
1420 >    final class VectorSpliterator implements Spliterator<E> {
1421          private Object[] array;
1422          private int index; // current index, modified on advance/split
1423          private int fence; // -1 until used; then one past last index
1424          private int expectedModCount; // initialized when fence set
1425  
1426 <        /** Create new spliterator covering the given range */
1427 <        VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
1426 >        /** Creates new spliterator covering the given range. */
1427 >        VectorSpliterator(Object[] array, int origin, int fence,
1428                            int expectedModCount) {
1408            this.list = list;
1429              this.array = array;
1430              this.index = origin;
1431              this.fence = fence;
# Line 1415 | Line 1435 | public class Vector<E>
1435          private int getFence() { // initialize on first use
1436              int hi;
1437              if ((hi = fence) < 0) {
1438 <                synchronized (list) {
1439 <                    array = list.elementData;
1440 <                    expectedModCount = list.modCount;
1441 <                    hi = fence = list.elementCount;
1438 >                synchronized (Vector.this) {
1439 >                    array = elementData;
1440 >                    expectedModCount = modCount;
1441 >                    hi = fence = elementCount;
1442                  }
1443              }
1444              return hi;
# Line 1427 | Line 1447 | public class Vector<E>
1447          public Spliterator<E> trySplit() {
1448              int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1449              return (lo >= mid) ? null :
1450 <                new VectorSpliterator<>(list, array, lo, index = mid,
1431 <                                        expectedModCount);
1450 >                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1451          }
1452  
1453          @SuppressWarnings("unchecked")
1454          public boolean tryAdvance(Consumer<? super E> action) {
1455 +            Objects.requireNonNull(action);
1456              int i;
1437            if (action == null)
1438                throw new NullPointerException();
1457              if (getFence() > (i = index)) {
1458                  index = i + 1;
1459                  action.accept((E)array[i]);
1460 <                if (list.modCount != expectedModCount)
1460 >                if (modCount != expectedModCount)
1461                      throw new ConcurrentModificationException();
1462                  return true;
1463              }
# Line 1448 | Line 1466 | public class Vector<E>
1466  
1467          @SuppressWarnings("unchecked")
1468          public void forEachRemaining(Consumer<? super E> action) {
1469 <            int i, hi; // hoist accesses and checks from loop
1470 <            Vector<E> lst; Object[] a;
1471 <            if (action == null)
1472 <                throw new NullPointerException();
1473 <            if ((lst = list) != null) {
1474 <                if ((hi = fence) < 0) {
1475 <                    synchronized (lst) {
1476 <                        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();
1469 >            Objects.requireNonNull(action);
1470 >            final int hi = getFence();
1471 >            final Object[] a = array;
1472 >            int i;
1473 >            for (i = index, index = hi; i < hi; i++)
1474 >                action.accept((E) a[i]);
1475 >            if (modCount != expectedModCount)
1476 >                throw new ConcurrentModificationException();
1477          }
1478  
1479          public long estimateSize() {
# Line 1480 | Line 1484 | public class Vector<E>
1484              return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1485          }
1486      }
1487 +
1488 +    void checkInvariants() {
1489 +        // assert elementCount >= 0;
1490 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1491 +    }
1492   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines