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.32 by jsr166, Sat Nov 12 20:51:59 2016 UTC vs.
Revision 1.58 by jsr166, Fri Jul 24 20:57:26 2020 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 172 | Line 179 | public class Vector<E>
179       * @since   1.2
180       */
181      public Vector(Collection<? extends E> c) {
182 <        elementData = c.toArray();
183 <        elementCount = elementData.length;
184 <        // defend against c.toArray (incorrectly) not returning Object[]
185 <        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
186 <        if (elementData.getClass() != Object[].class)
187 <            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
182 >        Object[] a = c.toArray();
183 >        elementCount = a.length;
184 >        if (c.getClass() == ArrayList.class) {
185 >            elementData = a;
186 >        } else {
187 >            elementData = Arrays.copyOf(a, elementCount, Object[].class);
188 >        }
189      }
190  
191      /**
# Line 239 | Line 247 | public class Vector<E>
247      }
248  
249      /**
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    /**
250       * Increases the capacity to ensure that it can hold at least the
251       * number of elements specified by the minimum capacity argument.
252       *
# Line 254 | Line 254 | public class Vector<E>
254       * @throws OutOfMemoryError if minCapacity is less than zero
255       */
256      private Object[] grow(int minCapacity) {
257 <        return elementData = Arrays.copyOf(elementData,
258 <                                           newCapacity(minCapacity));
257 >        int oldCapacity = elementData.length;
258 >        int newCapacity = ArraysSupport.newLength(oldCapacity,
259 >                minCapacity - oldCapacity, /* minimum growth */
260 >                capacityIncrement > 0 ? capacityIncrement : oldCapacity
261 >                                           /* preferred growth */);
262 >        return elementData = Arrays.copyOf(elementData, newCapacity);
263      }
264  
265      private Object[] grow() {
# Line 263 | Line 267 | public class Vector<E>
267      }
268  
269      /**
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    /**
270       * Sets the size of this vector. If the new size is greater than the
271       * current size, new {@code null} items are added to the end of
272       * the vector. If the new size is less than the current size, all
# Line 306 | Line 279 | public class Vector<E>
279          modCount++;
280          if (newSize > elementData.length)
281              grow(newSize);
282 <        for (int i = newSize; i < elementCount; i++)
283 <            elementData[i] = null;
282 >        final Object[] es = elementData;
283 >        for (int to = elementCount, i = newSize; i < to; i++)
284 >            es[i] = null;
285          elementCount = newSize;
286      }
287  
# Line 585 | Line 559 | public class Vector<E>
559          modCount++;
560          elementCount--;
561          elementData[elementCount] = null; /* to let gc do its work */
562 +        // checkInvariants();
563      }
564  
565      /**
# Line 675 | Line 650 | public class Vector<E>
650       * method (which is part of the {@link List} interface).
651       */
652      public synchronized void removeAllElements() {
653 <        // Let gc do its work
654 <        for (int i = 0; i < elementCount; i++)
655 <            elementData[i] = null;
681 <
653 >        final Object[] es = elementData;
654 >        for (int to = elementCount, i = elementCount = 0; i < to; i++)
655 >            es[i] = null;
656          modCount++;
683        elementCount = 0;
657      }
658  
659      /**
# Line 693 | Line 666 | public class Vector<E>
666      public synchronized Object clone() {
667          try {
668              @SuppressWarnings("unchecked")
669 <                Vector<E> v = (Vector<E>) super.clone();
669 >            Vector<E> v = (Vector<E>) super.clone();
670              v.elementData = Arrays.copyOf(elementData, elementCount);
671              v.modCount = 0;
672              return v;
# Line 759 | Line 732 | public class Vector<E>
732          return (E) elementData[index];
733      }
734  
735 +    @SuppressWarnings("unchecked")
736 +    static <E> E elementAt(Object[] es, int index) {
737 +        return (E) es[index];
738 +    }
739 +
740      /**
741       * Returns the element at the specified position in this Vector.
742       *
# Line 805 | Line 783 | public class Vector<E>
783              elementData = grow();
784          elementData[s] = e;
785          elementCount = s + 1;
786 +        // checkInvariants();
787      }
788  
789      /**
# Line 873 | Line 852 | public class Vector<E>
852                               numMoved);
853          elementData[--elementCount] = null; // Let gc do its work
854  
855 +        // checkInvariants();
856          return oldValue;
857      }
858  
# Line 928 | Line 908 | public class Vector<E>
908                  elementData = grow(s + numNew);
909              System.arraycopy(a, 0, elementData, s, numNew);
910              elementCount = s + numNew;
911 +            // checkInvariants();
912              return true;
913          }
914      }
# Line 978 | Line 959 | public class Vector<E>
959          return bulkRemove(e -> !c.contains(e));
960      }
961  
962 +    /**
963 +     * @throws NullPointerException {@inheritDoc}
964 +     */
965      @Override
966      public boolean removeIf(Predicate<? super E> filter) {
967          Objects.requireNonNull(filter);
968          return bulkRemove(filter);
969      }
970  
971 <    @SuppressWarnings("unchecked")
971 >    // A tiny bit set implementation
972 >
973 >    private static long[] nBits(int n) {
974 >        return new long[((n - 1) >> 6) + 1];
975 >    }
976 >    private static void setBit(long[] bits, int i) {
977 >        bits[i >> 6] |= 1L << i;
978 >    }
979 >    private static boolean isClear(long[] bits, int i) {
980 >        return (bits[i >> 6] & (1L << i)) == 0;
981 >    }
982 >
983      private synchronized boolean bulkRemove(Predicate<? super E> filter) {
984          int expectedModCount = modCount;
985          final Object[] es = elementData;
986 <        final int size = elementCount;
987 <        final boolean modified;
993 <        int r;
986 >        final int end = elementCount;
987 >        int i;
988          // Optimize for initial run of survivors
989 <        for (r = 0; r < size && !filter.test((E) es[r]); r++)
989 >        for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
990              ;
991 <        if (modified = (r < size)) {
992 <            expectedModCount++;
991 >        // Tolerate predicates that reentrantly access the collection for
992 >        // read (but writers still get CME), so traverse once to find
993 >        // elements to delete, a second pass to physically expunge.
994 >        if (i < end) {
995 >            final int beg = i;
996 >            final long[] deathRow = nBits(end - beg);
997 >            deathRow[0] = 1L;   // set bit 0
998 >            for (i = beg + 1; i < end; i++)
999 >                if (filter.test(elementAt(es, i)))
1000 >                    setBit(deathRow, i - beg);
1001 >            if (modCount != expectedModCount)
1002 >                throw new ConcurrentModificationException();
1003              modCount++;
1004 <            int w = r++;
1005 <            try {
1006 <                for (E e; r < size; r++)
1007 <                    if (!filter.test(e = (E) es[r]))
1008 <                        es[w++] = e;
1009 <            } catch (Throwable ex) {
1010 <                // copy remaining elements
1011 <                System.arraycopy(es, r, es, w, size - r);
1012 <                w += size - r;
1013 <                throw ex;
1014 <            } finally {
1015 <                Arrays.fill(es, elementCount = w, size, null);
1016 <            }
1004 >            int w = beg;
1005 >            for (i = beg; i < end; i++)
1006 >                if (isClear(deathRow, i - beg))
1007 >                    es[w++] = es[i];
1008 >            for (i = elementCount = w; i < end; i++)
1009 >                es[i] = null;
1010 >            // checkInvariants();
1011 >            return true;
1012 >        } else {
1013 >            if (modCount != expectedModCount)
1014 >                throw new ConcurrentModificationException();
1015 >            // checkInvariants();
1016 >            return false;
1017          }
1014        if (modCount != expectedModCount)
1015            throw new ConcurrentModificationException();
1016        return modified;
1018      }
1019  
1020      /**
# Line 1054 | Line 1055 | public class Vector<E>
1055                               numMoved);
1056          System.arraycopy(a, 0, elementData, index, numNew);
1057          elementCount = s + numNew;
1058 +        // checkInvariants();
1059          return true;
1060      }
1061  
# Line 1135 | Line 1137 | public class Vector<E>
1137       * (If {@code toIndex==fromIndex}, this operation has no effect.)
1138       */
1139      protected synchronized void removeRange(int fromIndex, int toIndex) {
1138        int numMoved = elementCount - toIndex;
1139        System.arraycopy(elementData, toIndex, elementData, fromIndex,
1140                         numMoved);
1141
1142        // Let gc do its work
1140          modCount++;
1141 <        int newElementCount = elementCount - (toIndex-fromIndex);
1142 <        while (elementCount != newElementCount)
1143 <            elementData[--elementCount] = null;
1141 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1142 >        // checkInvariants();
1143 >    }
1144 >
1145 >    /** Erases the gap from lo to hi, by sliding down following elements. */
1146 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1147 >        System.arraycopy(es, hi, es, lo, elementCount - hi);
1148 >        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1149 >            es[i] = null;
1150      }
1151  
1152      /**
1153 <     * Save the state of the {@code Vector} instance to a stream (that
1154 <     * is, serialize it).
1153 >     * Loads a {@code Vector} instance from a stream
1154 >     * (that is, deserializes it).
1155 >     * This method performs checks to ensure the consistency
1156 >     * of the fields.
1157 >     *
1158 >     * @param in the stream
1159 >     * @throws java.io.IOException if an I/O error occurs
1160 >     * @throws ClassNotFoundException if the stream contains data
1161 >     *         of a non-existing class
1162 >     */
1163 >    // OPENJDK @java.io.Serial
1164 >    private void readObject(ObjectInputStream in)
1165 >            throws IOException, ClassNotFoundException {
1166 >        ObjectInputStream.GetField gfields = in.readFields();
1167 >        int count = gfields.get("elementCount", 0);
1168 >        Object[] data = (Object[])gfields.get("elementData", null);
1169 >        if (count < 0 || data == null || count > data.length) {
1170 >            throw new StreamCorruptedException("Inconsistent vector internals");
1171 >        }
1172 >        elementCount = count;
1173 >        elementData = data.clone();
1174 >    }
1175 >
1176 >    /**
1177 >     * Saves the state of the {@code Vector} instance to a stream
1178 >     * (that is, serializes it).
1179       * This method performs synchronization to ensure the consistency
1180       * of the serialized data.
1181 +     *
1182 +     * @param s the stream
1183 +     * @throws java.io.IOException if an I/O error occurs
1184       */
1185 +    // OPENJDK @java.io.Serial
1186      private void writeObject(java.io.ObjectOutputStream s)
1187              throws java.io.IOException {
1188          final java.io.ObjectOutputStream.PutField fields = s.putFields();
# Line 1252 | Line 1283 | public class Vector<E>
1283                  if (i >= size) {
1284                      return;
1285                  }
1286 <        @SuppressWarnings("unchecked")
1287 <                final E[] elementData = (E[]) Vector.this.elementData;
1257 <                if (i >= elementData.length) {
1286 >                final Object[] es = elementData;
1287 >                if (i >= es.length)
1288                      throw new ConcurrentModificationException();
1289 <                }
1290 <                while (i != size && modCount == expectedModCount) {
1261 <                    action.accept(elementData[i++]);
1262 <                }
1289 >                while (i < size && modCount == expectedModCount)
1290 >                    action.accept(elementAt(es, i++));
1291                  // update once at end of iteration to reduce heap write traffic
1292                  cursor = i;
1293                  lastRet = i - 1;
# Line 1326 | Line 1354 | public class Vector<E>
1354          }
1355      }
1356  
1357 +    /**
1358 +     * @throws NullPointerException {@inheritDoc}
1359 +     */
1360      @Override
1361      public synchronized void forEach(Consumer<? super E> action) {
1362          Objects.requireNonNull(action);
1363          final int expectedModCount = modCount;
1364 <        @SuppressWarnings("unchecked")
1365 <        final E[] elementData = (E[]) this.elementData;
1366 <        final int elementCount = this.elementCount;
1367 <        for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
1368 <            action.accept(elementData[i]);
1338 <        }
1339 <        if (modCount != expectedModCount) {
1364 >        final Object[] es = elementData;
1365 >        final int size = elementCount;
1366 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1367 >            action.accept(elementAt(es, i));
1368 >        if (modCount != expectedModCount)
1369              throw new ConcurrentModificationException();
1370 <        }
1370 >        // checkInvariants();
1371      }
1372  
1373 +    /**
1374 +     * @throws NullPointerException {@inheritDoc}
1375 +     */
1376      @Override
1345    @SuppressWarnings("unchecked")
1377      public synchronized void replaceAll(UnaryOperator<E> operator) {
1378          Objects.requireNonNull(operator);
1379          final int expectedModCount = modCount;
1380 +        final Object[] es = elementData;
1381          final int size = elementCount;
1382 <        for (int i=0; modCount == expectedModCount && i < size; i++) {
1383 <            elementData[i] = operator.apply((E) elementData[i]);
1384 <        }
1353 <        if (modCount != expectedModCount) {
1382 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1383 >            es[i] = operator.apply(elementAt(es, i));
1384 >        if (modCount != expectedModCount)
1385              throw new ConcurrentModificationException();
1386 <        }
1386 >        // TODO(8203662): remove increment of modCount from ...
1387          modCount++;
1388 +        // checkInvariants();
1389      }
1390  
1391      @SuppressWarnings("unchecked")
# Line 1361 | Line 1393 | public class Vector<E>
1393      public synchronized void sort(Comparator<? super E> c) {
1394          final int expectedModCount = modCount;
1395          Arrays.sort((E[]) elementData, 0, elementCount, c);
1396 <        if (modCount != expectedModCount) {
1396 >        if (modCount != expectedModCount)
1397              throw new ConcurrentModificationException();
1366        }
1398          modCount++;
1399 +        // checkInvariants();
1400      }
1401  
1402      /**
# Line 1382 | Line 1414 | public class Vector<E>
1414       */
1415      @Override
1416      public Spliterator<E> spliterator() {
1417 <        return new VectorSpliterator<>(this, null, 0, -1, 0);
1417 >        return new VectorSpliterator(null, 0, -1, 0);
1418      }
1419  
1420      /** Similar to ArrayList Spliterator */
1421 <    static final class VectorSpliterator<E> implements Spliterator<E> {
1390 <        private final Vector<E> list;
1421 >    final class VectorSpliterator implements Spliterator<E> {
1422          private Object[] array;
1423          private int index; // current index, modified on advance/split
1424          private int fence; // -1 until used; then one past last index
1425          private int expectedModCount; // initialized when fence set
1426  
1427 <        /** Create new spliterator covering the given  range */
1428 <        VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
1427 >        /** Creates new spliterator covering the given range. */
1428 >        VectorSpliterator(Object[] array, int origin, int fence,
1429                            int expectedModCount) {
1399            this.list = list;
1430              this.array = array;
1431              this.index = origin;
1432              this.fence = fence;
# Line 1406 | Line 1436 | public class Vector<E>
1436          private int getFence() { // initialize on first use
1437              int hi;
1438              if ((hi = fence) < 0) {
1439 <                synchronized (list) {
1440 <                    array = list.elementData;
1441 <                    expectedModCount = list.modCount;
1442 <                    hi = fence = list.elementCount;
1439 >                synchronized (Vector.this) {
1440 >                    array = elementData;
1441 >                    expectedModCount = modCount;
1442 >                    hi = fence = elementCount;
1443                  }
1444              }
1445              return hi;
# Line 1418 | Line 1448 | public class Vector<E>
1448          public Spliterator<E> trySplit() {
1449              int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1450              return (lo >= mid) ? null :
1451 <                new VectorSpliterator<>(list, array, lo, index = mid,
1422 <                                        expectedModCount);
1451 >                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1452          }
1453  
1454          @SuppressWarnings("unchecked")
1455          public boolean tryAdvance(Consumer<? super E> action) {
1456 +            Objects.requireNonNull(action);
1457              int i;
1428            if (action == null)
1429                throw new NullPointerException();
1458              if (getFence() > (i = index)) {
1459                  index = i + 1;
1460                  action.accept((E)array[i]);
1461 <                if (list.modCount != expectedModCount)
1461 >                if (modCount != expectedModCount)
1462                      throw new ConcurrentModificationException();
1463                  return true;
1464              }
# Line 1439 | Line 1467 | public class Vector<E>
1467  
1468          @SuppressWarnings("unchecked")
1469          public void forEachRemaining(Consumer<? super E> action) {
1470 <            int i, hi; // hoist accesses and checks from loop
1471 <            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;
1450 <                        a = array = lst.elementData;
1451 <                        hi = fence = lst.elementCount;
1452 <                    }
1453 <                }
1454 <                else
1455 <                    a = array;
1456 <                if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
1457 <                    while (i < hi)
1458 <                        action.accept((E) a[i++]);
1459 <                    if (lst.modCount == expectedModCount)
1460 <                        return;
1461 <                }
1462 <            }
1463 <            throw new ConcurrentModificationException();
1470 >            Objects.requireNonNull(action);
1471 >            final int hi = getFence();
1472 >            final Object[] a = array;
1473 >            int i;
1474 >            for (i = index, index = hi; i < hi; i++)
1475 >                action.accept((E) a[i]);
1476 >            if (modCount != expectedModCount)
1477 >                throw new ConcurrentModificationException();
1478          }
1479  
1480          public long estimateSize() {
# Line 1471 | Line 1485 | public class Vector<E>
1485              return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1486          }
1487      }
1488 +
1489 +    void checkInvariants() {
1490 +        // assert elementCount >= 0;
1491 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1492 +    }
1493   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines