--- jsr166/src/main/java/util/Vector.java 2011/05/07 12:22:03 1.29 +++ jsr166/src/main/java/util/Vector.java 2016/11/03 20:49:07 1.30 @@ -1,12 +1,12 @@ /* - * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this + * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. + * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or @@ -25,6 +25,10 @@ package java.util; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; + /** * The {@code Vector} class implements a growable array of * objects. Like an array, it contains components that can be @@ -41,7 +45,7 @@ package java.util; * capacity of a vector before inserting a large number of * components; this reduces the amount of incremental reallocation. * - *

+ *

* The iterators returned by this class's {@link #iterator() iterator} and * {@link #listIterator(int) listIterator} methods are fail-fast: * if the vector is structurally modified at any time after the iterator is @@ -52,7 +56,9 @@ package java.util; * concurrent modification, the iterator fails quickly and cleanly, rather * than risking arbitrary, non-deterministic behavior at an undetermined * time in the future. The {@link Enumeration Enumerations} returned by - * the {@link #elements() elements} method are not fail-fast. + * the {@link #elements() elements} method are not fail-fast; if the + * Vector is structurally modified at any time after the enumeration is + * created then the results of enumerating are undefined. * *

Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the @@ -70,11 +76,13 @@ package java.util; * implementation is not needed, it is recommended to use {@link * ArrayList} in place of {@code Vector}. * + * @param Type of component elements + * * @author Lee Boynton * @author Jonathan Payne * @see Collection * @see LinkedList - * @since JDK1.0 + * @since 1.0 */ public class Vector extends AbstractList @@ -166,7 +174,8 @@ public class Vector public Vector(Collection c) { elementData = c.toArray(); elementCount = elementData.length; - // c.toArray might (incorrectly) not return Object[] (see 6260652) + // defend against c.toArray (incorrectly) not returning Object[] + // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, elementCount, Object[].class); } @@ -222,29 +231,66 @@ public class Vector * @param minCapacity the desired minimum capacity */ public synchronized void ensureCapacity(int minCapacity) { - modCount++; - ensureCapacityHelper(minCapacity); + if (minCapacity > 0) { + modCount++; + if (minCapacity > elementData.length) + grow(minCapacity); + } + } + + /** + * The maximum size of array to allocate (unless necessary). + * Some VMs reserve some header words in an array. + * Attempts to allocate larger arrays may result in + * OutOfMemoryError: Requested array size exceeds VM limit + */ + private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; + + /** + * Increases the capacity to ensure that it can hold at least the + * number of elements specified by the minimum capacity argument. + * + * @param minCapacity the desired minimum capacity + * @throws OutOfMemoryError if minCapacity is less than zero + */ + private Object[] grow(int minCapacity) { + return elementData = Arrays.copyOf(elementData, + newCapacity(minCapacity)); + } + + private Object[] grow() { + return grow(elementCount + 1); } /** - * This implements the unsynchronized semantics of ensureCapacity. - * Synchronized methods in this class can internally call this - * method for ensuring capacity without incurring the cost of an - * extra synchronization. + * Returns a capacity at least as large as the given minimum capacity. + * Will not return a capacity greater than MAX_ARRAY_SIZE unless + * the given minimum capacity is greater than MAX_ARRAY_SIZE. * - * @see #ensureCapacity(int) + * @param minCapacity the desired minimum capacity + * @throws OutOfMemoryError if minCapacity is less than zero */ - private void ensureCapacityHelper(int minCapacity) { + private int newCapacity(int minCapacity) { + // overflow-conscious code int oldCapacity = elementData.length; - if (minCapacity > oldCapacity) { - Object[] oldData = elementData; - int newCapacity = (capacityIncrement > 0) ? - (oldCapacity + capacityIncrement) : (oldCapacity * 2); - if (newCapacity < minCapacity) { - newCapacity = minCapacity; - } - elementData = Arrays.copyOf(elementData, newCapacity); - } + int newCapacity = oldCapacity + ((capacityIncrement > 0) ? + capacityIncrement : oldCapacity); + if (newCapacity - minCapacity <= 0) { + if (minCapacity < 0) // overflow + throw new OutOfMemoryError(); + return minCapacity; + } + return (newCapacity - MAX_ARRAY_SIZE <= 0) + ? newCapacity + : hugeCapacity(minCapacity); + } + + private static int hugeCapacity(int minCapacity) { + if (minCapacity < 0) // overflow + throw new OutOfMemoryError(); + return (minCapacity > MAX_ARRAY_SIZE) ? + Integer.MAX_VALUE : + MAX_ARRAY_SIZE; } /** @@ -258,13 +304,10 @@ public class Vector */ public synchronized void setSize(int newSize) { modCount++; - if (newSize > elementCount) { - ensureCapacityHelper(newSize); - } else { - for (int i = newSize ; i < elementCount ; i++) { - elementData[i] = null; - } - } + if (newSize > elementData.length) + grow(newSize); + for (int i = newSize; i < elementCount; i++) + elementData[i] = null; elementCount = newSize; } @@ -303,7 +346,9 @@ public class Vector * Returns an enumeration of the components of this vector. The * returned {@code Enumeration} object will generate all items in * this vector. The first item generated is the item at index {@code 0}, - * then the item at index {@code 1}, and so on. + * then the item at index {@code 1}, and so on. If the vector is + * structurally modified while enumerating over the elements then the + * results of enumerating are undefined. * * @return an enumeration of the components of this vector * @see Iterator @@ -331,7 +376,7 @@ public class Vector * Returns {@code true} if this vector contains the specified element. * More formally, returns {@code true} if and only if this vector * contains at least one element {@code e} such that - * (o==null ? e==null : o.equals(e)). + * {@code Objects.equals(o, e)}. * * @param o element whose presence in this vector is to be tested * @return {@code true} if this vector contains the specified element @@ -344,7 +389,7 @@ public class Vector * Returns the index of the first occurrence of the specified element * in this vector, or -1 if this vector does not contain the element. * More formally, returns the lowest index {@code i} such that - * (o==null ? get(i)==null : o.equals(get(i))), + * {@code Objects.equals(o, get(i))}, * or -1 if there is no such index. * * @param o element to search for @@ -360,7 +405,7 @@ public class Vector * this vector, searching forwards from {@code index}, or returns -1 if * the element is not found. * More formally, returns the lowest index {@code i} such that - * (i >= index && (o==null ? get(i)==null : o.equals(get(i)))), + * {@code (i >= index && Objects.equals(o, get(i)))}, * or -1 if there is no such index. * * @param o element to search for @@ -388,7 +433,7 @@ public class Vector * Returns the index of the last occurrence of the specified element * in this vector, or -1 if this vector does not contain the element. * More formally, returns the highest index {@code i} such that - * (o==null ? get(i)==null : o.equals(get(i))), + * {@code Objects.equals(o, get(i))}, * or -1 if there is no such index. * * @param o element to search for @@ -404,7 +449,7 @@ public class Vector * this vector, searching backwards from {@code index}, or returns -1 if * the element is not found. * More formally, returns the highest index {@code i} such that - * (i <= index && (o==null ? get(i)==null : o.equals(get(i)))), + * {@code (i <= index && Objects.equals(o, get(i)))}, * or -1 if there is no such index. * * @param o element to search for @@ -526,7 +571,6 @@ public class Vector * ({@code index < 0 || index >= size()}) */ public synchronized void removeElementAt(int index) { - modCount++; if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); @@ -538,6 +582,7 @@ public class Vector if (j > 0) { System.arraycopy(elementData, index + 1, elementData, index, j); } + modCount++; elementCount--; elementData[elementCount] = null; /* to let gc do its work */ } @@ -566,15 +611,20 @@ public class Vector * ({@code index < 0 || index > size()}) */ public synchronized void insertElementAt(E obj, int index) { - modCount++; if (index > elementCount) { throw new ArrayIndexOutOfBoundsException(index + " > " + elementCount); } - ensureCapacityHelper(elementCount + 1); - System.arraycopy(elementData, index, elementData, index + 1, elementCount - index); + modCount++; + final int s = elementCount; + Object[] elementData = this.elementData; + if (s == elementData.length) + elementData = grow(); + System.arraycopy(elementData, index, + elementData, index + 1, + s - index); elementData[index] = obj; - elementCount++; + elementCount = s + 1; } /** @@ -590,8 +640,7 @@ public class Vector */ public synchronized void addElement(E obj) { modCount++; - ensureCapacityHelper(elementCount + 1); - elementData[elementCount++] = obj; + add(obj, elementData, elementCount); } /** @@ -626,11 +675,11 @@ public class Vector * method (which is part of the {@link List} interface). */ public synchronized void removeAllElements() { - modCount++; // Let gc do its work for (int i = 0; i < elementCount; i++) elementData[i] = null; + modCount++; elementCount = 0; } @@ -650,7 +699,7 @@ public class Vector return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable - throw new InternalError(); + throw new InternalError(e); } } @@ -678,12 +727,15 @@ public class Vector * of the Vector only if the caller knows that the Vector * does not contain any null elements.) * + * @param type of array elements. The same type as {@code } or a + * supertype of {@code }. * @param a the array into which the elements of the Vector are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the Vector - * @throws ArrayStoreException if the runtime type of a is not a supertype - * of the runtime type of every element in this Vector + * @throws ArrayStoreException if the runtime type of a, {@code }, is not + * a supertype of the runtime type, {@code }, of every element in this + * Vector * @throws NullPointerException if the given array is null * @since 1.2 */ @@ -744,6 +796,18 @@ public class Vector } /** + * This helper method split out from add(E) to keep method + * bytecode size under 35 (the -XX:MaxInlineSize default value), + * which helps when add(E) is called in a C1-compiled loop. + */ + private void add(E e, Object[] elementData, int s) { + if (s == elementData.length) + elementData = grow(); + elementData[s] = e; + elementCount = s + 1; + } + + /** * Appends the specified element to the end of this Vector. * * @param e element to be appended to this Vector @@ -752,8 +816,7 @@ public class Vector */ public synchronized boolean add(E e) { modCount++; - ensureCapacityHelper(elementCount + 1); - elementData[elementCount++] = e; + add(e, elementData, elementCount); return true; } @@ -761,7 +824,7 @@ public class Vector * Removes the first occurrence of the specified element in this Vector * If the Vector does not contain the element, it is unchanged. More * formally, removes the element with the lowest index i such that - * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such + * {@code Objects.equals(o, get(i))} (if such * an element exists). * * @param o element to be removed from this Vector, if present @@ -852,14 +915,21 @@ public class Vector * @throws NullPointerException if the specified collection is null * @since 1.2 */ - public synchronized boolean addAll(Collection c) { - modCount++; + public boolean addAll(Collection c) { Object[] a = c.toArray(); + modCount++; int numNew = a.length; - ensureCapacityHelper(elementCount + numNew); - System.arraycopy(a, 0, elementData, elementCount, numNew); - elementCount += numNew; - return numNew != 0; + if (numNew == 0) + return false; + synchronized (this) { + Object[] elementData = this.elementData; + final int s = elementCount; + if (numNew > elementData.length - s) + elementData = grow(s + numNew); + System.arraycopy(a, 0, elementData, s, numNew); + elementCount = s + numNew; + return true; + } } /** @@ -870,10 +940,13 @@ public class Vector * @return true if this Vector changed as a result of the call * @throws ClassCastException if the types of one or more elements * in this vector are incompatible with the specified - * collection (optional) + * collection + * (optional) * @throws NullPointerException if this vector contains one or more null * elements and the specified collection does not support null - * elements (optional), or if the specified collection is null + * elements + * (optional), + * or if the specified collection is null * @since 1.2 */ public synchronized boolean removeAll(Collection c) { @@ -890,10 +963,13 @@ public class Vector * @return true if this Vector changed as a result of the call * @throws ClassCastException if the types of one or more elements * in this vector are incompatible with the specified - * collection (optional) + * collection + * (optional) * @throws NullPointerException if this vector contains one or more null * elements and the specified collection does not support null - * elements (optional), or if the specified collection is null + * elements + * (optional), + * or if the specified collection is null * @since 1.2 */ public synchronized boolean retainAll(Collection c) { @@ -918,22 +994,27 @@ public class Vector * @since 1.2 */ public synchronized boolean addAll(int index, Collection c) { - modCount++; if (index < 0 || index > elementCount) throw new ArrayIndexOutOfBoundsException(index); Object[] a = c.toArray(); + modCount++; int numNew = a.length; - ensureCapacityHelper(elementCount + numNew); + if (numNew == 0) + return false; + Object[] elementData = this.elementData; + final int s = elementCount; + if (numNew > elementData.length - s) + elementData = grow(s + numNew); - int numMoved = elementCount - index; + int numMoved = s - index; if (numMoved > 0) - System.arraycopy(elementData, index, elementData, index + numNew, + System.arraycopy(elementData, index, + elementData, index + numNew, numMoved); - System.arraycopy(a, 0, elementData, index, numNew); - elementCount += numNew; - return numNew != 0; + elementCount = s + numNew; + return true; } /** @@ -941,8 +1022,8 @@ public class Vector * true if and only if the specified Object is also a List, both Lists * have the same size, and all corresponding pairs of elements in the two * Lists are equal. (Two elements {@code e1} and - * {@code e2} are equal if {@code (e1==null ? e2==null : - * e1.equals(e2))}.) In other words, two Lists are defined to be + * {@code e2} are equal if {@code Objects.equals(e1, e2)}.) + * In other words, two Lists are defined to be * equal if they contain the same elements in the same order. * * @param o the Object to be compared for equality with this Vector @@ -1014,12 +1095,12 @@ public class Vector * (If {@code toIndex==fromIndex}, this operation has no effect.) */ protected synchronized void removeRange(int fromIndex, int toIndex) { - modCount++; int numMoved = elementCount - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // Let gc do its work + modCount++; int newElementCount = elementCount - (toIndex-fromIndex); while (elementCount != newElementCount) elementData[--elementCount] = null; @@ -1027,13 +1108,21 @@ public class Vector /** * Save the state of the {@code Vector} instance to a stream (that - * is, serialize it). This method is present merely for synchronization. - * It just calls the default writeObject method. - */ - private synchronized void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException - { - s.defaultWriteObject(); + * is, serialize it). + * This method performs synchronization to ensure the consistency + * of the serialized data. + */ + private void writeObject(java.io.ObjectOutputStream s) + throws java.io.IOException { + final java.io.ObjectOutputStream.PutField fields = s.putFields(); + final Object[] data; + synchronized (this) { + fields.put("capacityIncrement", capacityIncrement); + fields.put("elementCount", elementCount); + data = elementData.clone(); + } + fields.put("elementData", data); + s.writeFields(); } /** @@ -1114,6 +1203,30 @@ public class Vector lastRet = -1; } + @Override + public void forEachRemaining(Consumer action) { + Objects.requireNonNull(action); + synchronized (Vector.this) { + final int size = elementCount; + int i = cursor; + if (i >= size) { + return; + } + @SuppressWarnings("unchecked") + final E[] elementData = (E[]) Vector.this.elementData; + if (i >= elementData.length) { + throw new ConcurrentModificationException(); + } + while (i != size && modCount == expectedModCount) { + action.accept(elementData[i++]); + } + // update once at end of iteration to reduce heap write traffic + cursor = i; + lastRet = i - 1; + checkForComodification(); + } + } + final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); @@ -1172,4 +1285,194 @@ public class Vector lastRet = -1; } } + + @Override + public synchronized void forEach(Consumer action) { + Objects.requireNonNull(action); + final int expectedModCount = modCount; + @SuppressWarnings("unchecked") + final E[] elementData = (E[]) this.elementData; + final int elementCount = this.elementCount; + for (int i=0; modCount == expectedModCount && i < elementCount; i++) { + action.accept(elementData[i]); + } + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + } + + @Override + @SuppressWarnings("unchecked") + public synchronized boolean removeIf(Predicate filter) { + Objects.requireNonNull(filter); + // figure out which elements are to be removed + // any exception thrown from the filter predicate at this stage + // will leave the collection unmodified + int removeCount = 0; + final int size = elementCount; + final BitSet removeSet = new BitSet(size); + final int expectedModCount = modCount; + for (int i=0; modCount == expectedModCount && i < size; i++) { + @SuppressWarnings("unchecked") + final E element = (E) elementData[i]; + if (filter.test(element)) { + removeSet.set(i); + removeCount++; + } + } + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + + // shift surviving elements left over the spaces left by removed elements + final boolean anyToRemove = removeCount > 0; + if (anyToRemove) { + final int newSize = size - removeCount; + for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) { + i = removeSet.nextClearBit(i); + elementData[j] = elementData[i]; + } + for (int k=newSize; k < size; k++) { + elementData[k] = null; // Let gc do its work + } + elementCount = newSize; + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + modCount++; + } + + return anyToRemove; + } + + @Override + @SuppressWarnings("unchecked") + public synchronized void replaceAll(UnaryOperator operator) { + Objects.requireNonNull(operator); + final int expectedModCount = modCount; + final int size = elementCount; + for (int i=0; modCount == expectedModCount && i < size; i++) { + elementData[i] = operator.apply((E) elementData[i]); + } + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + modCount++; + } + + @SuppressWarnings("unchecked") + @Override + public synchronized void sort(Comparator c) { + final int expectedModCount = modCount; + Arrays.sort((E[]) elementData, 0, elementCount, c); + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + modCount++; + } + + /** + * Creates a late-binding + * and fail-fast {@link Spliterator} over the elements in this + * list. + * + *

The {@code Spliterator} reports {@link Spliterator#SIZED}, + * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}. + * Overriding implementations should document the reporting of additional + * characteristic values. + * + * @return a {@code Spliterator} over the elements in this list + * @since 1.8 + */ + @Override + public Spliterator spliterator() { + return new VectorSpliterator<>(this, null, 0, -1, 0); + } + + /** Similar to ArrayList Spliterator */ + static final class VectorSpliterator implements Spliterator { + private final Vector list; + private Object[] array; + private int index; // current index, modified on advance/split + private int fence; // -1 until used; then one past last index + private int expectedModCount; // initialized when fence set + + /** Create new spliterator covering the given range */ + VectorSpliterator(Vector list, Object[] array, int origin, int fence, + int expectedModCount) { + this.list = list; + this.array = array; + this.index = origin; + this.fence = fence; + this.expectedModCount = expectedModCount; + } + + private int getFence() { // initialize on first use + int hi; + if ((hi = fence) < 0) { + synchronized(list) { + array = list.elementData; + expectedModCount = list.modCount; + hi = fence = list.elementCount; + } + } + return hi; + } + + public Spliterator trySplit() { + int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; + return (lo >= mid) ? null : + new VectorSpliterator<>(list, array, lo, index = mid, + expectedModCount); + } + + @SuppressWarnings("unchecked") + public boolean tryAdvance(Consumer action) { + int i; + if (action == null) + throw new NullPointerException(); + if (getFence() > (i = index)) { + index = i + 1; + action.accept((E)array[i]); + if (list.modCount != expectedModCount) + throw new ConcurrentModificationException(); + return true; + } + return false; + } + + @SuppressWarnings("unchecked") + public void forEachRemaining(Consumer action) { + int i, hi; // hoist accesses and checks from loop + Vector lst; Object[] a; + if (action == null) + throw new NullPointerException(); + if ((lst = list) != null) { + if ((hi = fence) < 0) { + synchronized(lst) { + expectedModCount = lst.modCount; + a = array = lst.elementData; + hi = fence = lst.elementCount; + } + } + else + a = array; + if (a != null && (i = index) >= 0 && (index = hi) <= a.length) { + while (i < hi) + action.accept((E) a[i++]); + if (lst.modCount == expectedModCount) + return; + } + } + throw new ConcurrentModificationException(); + } + + public long estimateSize() { + return getFence() - index; + } + + public int characteristics() { + return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED; + } + } }