ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
(Generate patch)

Comparing jsr166/src/main/java/util/ArrayDeque.java (file contents):
Revision 1.65 by jsr166, Sat Feb 28 20:35:47 2015 UTC vs.
Revision 1.137 by jsr166, Sun Nov 11 17:37:30 2018 UTC

# Line 7 | Line 7 | package java.util;
7  
8   import java.io.Serializable;
9   import java.util.function.Consumer;
10 + import java.util.function.Predicate;
11 + // OPENJDK import jdk.internal.access.SharedSecrets;
12  
13   /**
14   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 48 | Line 50 | import java.util.function.Consumer;
50   * Iterator} interfaces.
51   *
52   * <p>This class is a member of the
53 < * <a href="{@docRoot}/../technotes/guides/collections/index.html">
53 > * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
54   * Java Collections Framework</a>.
55   *
56   * @author  Josh Bloch and Doug Lea
55 * @since   1.6
57   * @param <E> the type of elements held in this deque
58 + * @since   1.6
59   */
60   public class ArrayDeque<E> extends AbstractCollection<E>
61                             implements Deque<E>, Cloneable, Serializable
62   {
63 +    /*
64 +     * VMs excel at optimizing simple array loops where indices are
65 +     * incrementing or decrementing over a valid slice, e.g.
66 +     *
67 +     * for (int i = start; i < end; i++) ... elements[i]
68 +     *
69 +     * Because in a circular array, elements are in general stored in
70 +     * two disjoint such slices, we help the VM by writing unusual
71 +     * nested loops for all traversals over the elements.  Having only
72 +     * one hot inner loop body instead of two or three eases human
73 +     * maintenance and encourages VM loop inlining into the caller.
74 +     */
75 +
76      /**
77       * The array in which the elements of the deque are stored.
78 <     * The capacity of the deque is the length of this array, which is
79 <     * always a power of two. The array is never allowed to become
65 <     * full, except transiently within an addX method where it is
66 <     * resized (see doubleCapacity) immediately upon becoming full,
67 <     * thus avoiding head and tail wrapping around to equal each
68 <     * other.  We also guarantee that all array cells not holding
69 <     * deque elements are always null.
78 >     * All array cells not holding deque elements are always null.
79 >     * The array always has at least one null slot (at tail).
80       */
81 <    transient Object[] elements; // non-private to simplify nested class access
81 >    transient Object[] elements;
82  
83      /**
84       * The index of the element at the head of the deque (which is the
85       * element that would be removed by remove() or pop()); or an
86 <     * arbitrary number equal to tail if the deque is empty.
86 >     * arbitrary number 0 <= head < elements.length equal to tail if
87 >     * the deque is empty.
88       */
89      transient int head;
90  
91      /**
92       * The index at which the next element would be added to the tail
93 <     * of the deque (via addLast(E), add(E), or push(E)).
93 >     * of the deque (via addLast(E), add(E), or push(E));
94 >     * elements[tail] is always null.
95       */
96      transient int tail;
97  
98      /**
99 <     * The minimum capacity that we'll use for a newly created deque.
100 <     * Must be a power of 2.
99 >     * The maximum size of array to allocate.
100 >     * Some VMs reserve some header words in an array.
101 >     * Attempts to allocate larger arrays may result in
102 >     * OutOfMemoryError: Requested array size exceeds VM limit
103       */
104 <    private static final int MIN_INITIAL_CAPACITY = 8;
104 >    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
105  
106 <    // ******  Array allocation and resizing utilities ******
106 >    /**
107 >     * Increases the capacity of this deque by at least the given amount.
108 >     *
109 >     * @param needed the required minimum extra capacity; must be positive
110 >     */
111 >    private void grow(int needed) {
112 >        // overflow-conscious code
113 >        final int oldCapacity = elements.length;
114 >        int newCapacity;
115 >        // Double capacity if small; else grow by 50%
116 >        int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
117 >        if (jump < needed
118 >            || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
119 >            newCapacity = newCapacity(needed, jump);
120 >        final Object[] es = elements = Arrays.copyOf(elements, newCapacity);
121 >        // Exceptionally, here tail == head needs to be disambiguated
122 >        if (tail < head || (tail == head && es[head] != null)) {
123 >            // wrap around; slide first leg forward to end of array
124 >            int newSpace = newCapacity - oldCapacity;
125 >            System.arraycopy(es, head,
126 >                             es, head + newSpace,
127 >                             oldCapacity - head);
128 >            for (int i = head, to = (head += newSpace); i < to; i++)
129 >                es[i] = null;
130 >        }
131 >        // checkInvariants();
132 >    }
133 >
134 >    /** Capacity calculation for edge conditions, especially overflow. */
135 >    private int newCapacity(int needed, int jump) {
136 >        final int oldCapacity = elements.length, minCapacity;
137 >        if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
138 >            if (minCapacity < 0)
139 >                throw new IllegalStateException("Sorry, deque too big");
140 >            return Integer.MAX_VALUE;
141 >        }
142 >        if (needed > jump)
143 >            return minCapacity;
144 >        return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
145 >            ? oldCapacity + jump
146 >            : MAX_ARRAY_SIZE;
147 >    }
148  
149      /**
150 <     * Allocates empty array to hold the given number of elements.
151 <     *
152 <     * @param numElements  the number of elements to hold
153 <     */
154 <    private void allocateElements(int numElements) {
155 <        int initialCapacity = MIN_INITIAL_CAPACITY;
156 <        // Find the best power of two to hold elements.
157 <        // Tests "<=" because arrays aren't kept full.
158 <        if (numElements >= initialCapacity) {
159 <            initialCapacity = numElements;
160 <            initialCapacity |= (initialCapacity >>>  1);
106 <            initialCapacity |= (initialCapacity >>>  2);
107 <            initialCapacity |= (initialCapacity >>>  4);
108 <            initialCapacity |= (initialCapacity >>>  8);
109 <            initialCapacity |= (initialCapacity >>> 16);
110 <            initialCapacity++;
111 <
112 <            if (initialCapacity < 0)   // Too many elements, must back off
113 <                initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
114 <        }
115 <        elements = new Object[initialCapacity];
150 >     * Increases the internal storage of this collection, if necessary,
151 >     * to ensure that it can hold at least the given number of elements.
152 >     *
153 >     * @param minCapacity the desired minimum capacity
154 >     * @since TBD
155 >     */
156 >    /* public */ void ensureCapacity(int minCapacity) {
157 >        int needed;
158 >        if ((needed = (minCapacity + 1 - elements.length)) > 0)
159 >            grow(needed);
160 >        // checkInvariants();
161      }
162  
163      /**
164 <     * Doubles the capacity of this deque.  Call only when full, i.e.,
165 <     * when head and tail have wrapped around to become equal.
166 <     */
167 <    private void doubleCapacity() {
168 <        assert head == tail;
169 <        int p = head;
170 <        int n = elements.length;
171 <        int r = n - p; // number of elements to the right of p
172 <        int newCapacity = n << 1;
173 <        if (newCapacity < 0)
174 <            throw new IllegalStateException("Sorry, deque too big");
175 <        Object[] a = new Object[newCapacity];
131 <        System.arraycopy(elements, p, a, 0, r);
132 <        System.arraycopy(elements, 0, a, r, p);
133 <        elements = a;
134 <        head = 0;
135 <        tail = n;
164 >     * Minimizes the internal storage of this collection.
165 >     *
166 >     * @since TBD
167 >     */
168 >    /* public */ void trimToSize() {
169 >        int size;
170 >        if ((size = size()) + 1 < elements.length) {
171 >            elements = toArray(new Object[size + 1]);
172 >            head = 0;
173 >            tail = size;
174 >        }
175 >        // checkInvariants();
176      }
177  
178      /**
# Line 140 | Line 180 | public class ArrayDeque<E> extends Abstr
180       * sufficient to hold 16 elements.
181       */
182      public ArrayDeque() {
183 <        elements = new Object[16];
183 >        elements = new Object[16 + 1];
184      }
185  
186      /**
187       * Constructs an empty array deque with an initial capacity
188       * sufficient to hold the specified number of elements.
189       *
190 <     * @param numElements  lower bound on initial capacity of the deque
190 >     * @param numElements lower bound on initial capacity of the deque
191       */
192      public ArrayDeque(int numElements) {
193 <        allocateElements(numElements);
193 >        elements =
194 >            new Object[(numElements < 1) ? 1 :
195 >                       (numElements == Integer.MAX_VALUE) ? Integer.MAX_VALUE :
196 >                       numElements + 1];
197      }
198  
199      /**
# Line 164 | Line 207 | public class ArrayDeque<E> extends Abstr
207       * @throws NullPointerException if the specified collection is null
208       */
209      public ArrayDeque(Collection<? extends E> c) {
210 <        allocateElements(c.size());
211 <        addAll(c);
210 >        this(c.size());
211 >        copyElements(c);
212 >    }
213 >
214 >    /**
215 >     * Circularly increments i, mod modulus.
216 >     * Precondition and postcondition: 0 <= i < modulus.
217 >     */
218 >    static final int inc(int i, int modulus) {
219 >        if (++i >= modulus) i = 0;
220 >        return i;
221 >    }
222 >
223 >    /**
224 >     * Circularly decrements i, mod modulus.
225 >     * Precondition and postcondition: 0 <= i < modulus.
226 >     */
227 >    static final int dec(int i, int modulus) {
228 >        if (--i < 0) i = modulus - 1;
229 >        return i;
230 >    }
231 >
232 >    /**
233 >     * Circularly adds the given distance to index i, mod modulus.
234 >     * Precondition: 0 <= i < modulus, 0 <= distance <= modulus.
235 >     * @return index 0 <= i < modulus
236 >     */
237 >    static final int inc(int i, int distance, int modulus) {
238 >        if ((i += distance) - modulus >= 0) i -= modulus;
239 >        return i;
240 >    }
241 >
242 >    /**
243 >     * Subtracts j from i, mod modulus.
244 >     * Index i must be logically ahead of index j.
245 >     * Precondition: 0 <= i < modulus, 0 <= j < modulus.
246 >     * @return the "circular distance" from j to i; corner case i == j
247 >     * is disambiguated to "empty", returning 0.
248 >     */
249 >    static final int sub(int i, int j, int modulus) {
250 >        if ((i -= j) < 0) i += modulus;
251 >        return i;
252 >    }
253 >
254 >    /**
255 >     * Returns element at array index i.
256 >     * This is a slight abuse of generics, accepted by javac.
257 >     */
258 >    @SuppressWarnings("unchecked")
259 >    static final <E> E elementAt(Object[] es, int i) {
260 >        return (E) es[i];
261 >    }
262 >
263 >    /**
264 >     * A version of elementAt that checks for null elements.
265 >     * This check doesn't catch all possible comodifications,
266 >     * but does catch ones that corrupt traversal.
267 >     */
268 >    static final <E> E nonNullElementAt(Object[] es, int i) {
269 >        @SuppressWarnings("unchecked") E e = (E) es[i];
270 >        if (e == null)
271 >            throw new ConcurrentModificationException();
272 >        return e;
273      }
274  
275      // The main insertion and extraction methods are addFirst,
# Line 181 | Line 285 | public class ArrayDeque<E> extends Abstr
285      public void addFirst(E e) {
286          if (e == null)
287              throw new NullPointerException();
288 <        elements[head = (head - 1) & (elements.length - 1)] = e;
288 >        final Object[] es = elements;
289 >        es[head = dec(head, es.length)] = e;
290          if (head == tail)
291 <            doubleCapacity();
291 >            grow(1);
292 >        // checkInvariants();
293      }
294  
295      /**
# Line 197 | Line 303 | public class ArrayDeque<E> extends Abstr
303      public void addLast(E e) {
304          if (e == null)
305              throw new NullPointerException();
306 <        elements[tail] = e;
307 <        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
308 <            doubleCapacity();
306 >        final Object[] es = elements;
307 >        es[tail] = e;
308 >        if (head == (tail = inc(tail, es.length)))
309 >            grow(1);
310 >        // checkInvariants();
311 >    }
312 >
313 >    /**
314 >     * Adds all of the elements in the specified collection at the end
315 >     * of this deque, as if by calling {@link #addLast} on each one,
316 >     * in the order that they are returned by the collection's iterator.
317 >     *
318 >     * @param c the elements to be inserted into this deque
319 >     * @return {@code true} if this deque changed as a result of the call
320 >     * @throws NullPointerException if the specified collection or any
321 >     *         of its elements are null
322 >     */
323 >    public boolean addAll(Collection<? extends E> c) {
324 >        final int s, needed;
325 >        if ((needed = (s = size()) + c.size() + 1 - elements.length) > 0)
326 >            grow(needed);
327 >        copyElements(c);
328 >        // checkInvariants();
329 >        return size() > s;
330 >    }
331 >
332 >    private void copyElements(Collection<? extends E> c) {
333 >        c.forEach(this::addLast);
334      }
335  
336      /**
# Line 230 | Line 361 | public class ArrayDeque<E> extends Abstr
361       * @throws NoSuchElementException {@inheritDoc}
362       */
363      public E removeFirst() {
364 <        E x = pollFirst();
365 <        if (x == null)
364 >        E e = pollFirst();
365 >        if (e == null)
366              throw new NoSuchElementException();
367 <        return x;
367 >        // checkInvariants();
368 >        return e;
369      }
370  
371      /**
372       * @throws NoSuchElementException {@inheritDoc}
373       */
374      public E removeLast() {
375 <        E x = pollLast();
376 <        if (x == null)
375 >        E e = pollLast();
376 >        if (e == null)
377              throw new NoSuchElementException();
378 <        return x;
378 >        // checkInvariants();
379 >        return e;
380      }
381  
382      public E pollFirst() {
383 <        int h = head;
384 <        @SuppressWarnings("unchecked")
385 <        E result = (E) elements[h];
386 <        // Element is null if deque empty
387 <        if (result != null) {
388 <            elements[h] = null; // Must null out slot
256 <            head = (h + 1) & (elements.length - 1);
383 >        final Object[] es;
384 >        final int h;
385 >        E e = elementAt(es = elements, h = head);
386 >        if (e != null) {
387 >            es[h] = null;
388 >            head = inc(h, es.length);
389          }
390 <        return result;
390 >        // checkInvariants();
391 >        return e;
392      }
393  
394      public E pollLast() {
395 <        int t = (tail - 1) & (elements.length - 1);
396 <        @SuppressWarnings("unchecked")
397 <        E result = (E) elements[t];
398 <        if (result != null) {
399 <            elements[t] = null;
400 <            tail = t;
401 <        }
269 <        return result;
395 >        final Object[] es;
396 >        final int t;
397 >        E e = elementAt(es = elements, t = dec(tail, es.length));
398 >        if (e != null)
399 >            es[tail = t] = null;
400 >        // checkInvariants();
401 >        return e;
402      }
403  
404      /**
405       * @throws NoSuchElementException {@inheritDoc}
406       */
407      public E getFirst() {
408 <        @SuppressWarnings("unchecked")
409 <        E result = (E) elements[head];
278 <        if (result == null)
408 >        E e = elementAt(elements, head);
409 >        if (e == null)
410              throw new NoSuchElementException();
411 <        return result;
411 >        // checkInvariants();
412 >        return e;
413      }
414  
415      /**
416       * @throws NoSuchElementException {@inheritDoc}
417       */
418      public E getLast() {
419 <        @SuppressWarnings("unchecked")
420 <        E result = (E) elements[(tail - 1) & (elements.length - 1)];
421 <        if (result == null)
419 >        final Object[] es = elements;
420 >        E e = elementAt(es, dec(tail, es.length));
421 >        if (e == null)
422              throw new NoSuchElementException();
423 <        return result;
423 >        // checkInvariants();
424 >        return e;
425      }
426  
294    @SuppressWarnings("unchecked")
427      public E peekFirst() {
428 <        // elements[head] is null if deque empty
429 <        return (E) elements[head];
428 >        // checkInvariants();
429 >        return elementAt(elements, head);
430      }
431  
300    @SuppressWarnings("unchecked")
432      public E peekLast() {
433 <        return (E) elements[(tail - 1) & (elements.length - 1)];
433 >        // checkInvariants();
434 >        final Object[] es;
435 >        return elementAt(es = elements, dec(tail, es.length));
436      }
437  
438      /**
# Line 316 | Line 449 | public class ArrayDeque<E> extends Abstr
449       */
450      public boolean removeFirstOccurrence(Object o) {
451          if (o != null) {
452 <            int mask = elements.length - 1;
453 <            int i = head;
454 <            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
455 <                if (o.equals(x)) {
456 <                    delete(i);
457 <                    return true;
458 <                }
452 >            final Object[] es = elements;
453 >            for (int i = head, end = tail, to = (i <= end) ? end : es.length;
454 >                 ; i = 0, to = end) {
455 >                for (; i < to; i++)
456 >                    if (o.equals(es[i])) {
457 >                        delete(i);
458 >                        return true;
459 >                    }
460 >                if (to == end) break;
461              }
462          }
463          return false;
# Line 342 | Line 477 | public class ArrayDeque<E> extends Abstr
477       */
478      public boolean removeLastOccurrence(Object o) {
479          if (o != null) {
480 <            int mask = elements.length - 1;
481 <            int i = (tail - 1) & mask;
482 <            for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
483 <                if (o.equals(x)) {
484 <                    delete(i);
485 <                    return true;
486 <                }
480 >            final Object[] es = elements;
481 >            for (int i = tail, end = head, to = (i >= end) ? end : 0;
482 >                 ; i = es.length, to = end) {
483 >                for (i--; i > to - 1; i--)
484 >                    if (o.equals(es[i])) {
485 >                        delete(i);
486 >                        return true;
487 >                    }
488 >                if (to == end) break;
489              }
490          }
491          return false;
# Line 386 | Line 523 | public class ArrayDeque<E> extends Abstr
523      /**
524       * Retrieves and removes the head of the queue represented by this deque.
525       *
526 <     * This method differs from {@link #poll poll} only in that it throws an
527 <     * exception if this deque is empty.
526 >     * This method differs from {@link #poll() poll()} only in that it
527 >     * throws an exception if this deque is empty.
528       *
529       * <p>This method is equivalent to {@link #removeFirst}.
530       *
# Line 468 | Line 605 | public class ArrayDeque<E> extends Abstr
605          return removeFirst();
606      }
607  
471    private void checkInvariants() {
472        assert elements[tail] == null;
473        assert head == tail ? elements[head] == null :
474            (elements[head] != null &&
475             elements[(tail - 1) & (elements.length - 1)] != null);
476        assert elements[(head - 1) & (elements.length - 1)] == null;
477    }
478
608      /**
609 <     * Removes the element at the specified position in the elements array,
610 <     * adjusting head and tail as necessary.  This can result in motion of
611 <     * elements backwards or forwards in the array.
609 >     * Removes the element at the specified position in the elements array.
610 >     * This can result in forward or backwards motion of array elements.
611 >     * We optimize for least element motion.
612       *
613       * <p>This method is called delete rather than remove to emphasize
614       * that its semantics differ from those of {@link List#remove(int)}.
615       *
616 <     * @return true if elements moved backwards
616 >     * @return true if elements near tail moved backwards
617       */
618 <    private boolean delete(int i) {
619 <        checkInvariants();
620 <        final Object[] elements = this.elements;
621 <        final int mask = elements.length - 1;
622 <        final int h = head;
623 <        final int t = tail;
624 <        final int front = (i - h) & mask;
625 <        final int back  = (t - i) & mask;
626 <
498 <        // Invariant: head <= i < tail mod circularity
499 <        if (front >= ((t - h) & mask))
500 <            throw new ConcurrentModificationException();
501 <
502 <        // Optimize for least element motion
618 >    boolean delete(int i) {
619 >        // checkInvariants();
620 >        final Object[] es = elements;
621 >        final int capacity = es.length;
622 >        final int h, t;
623 >        // number of elements before to-be-deleted elt
624 >        final int front = sub(i, h = head, capacity);
625 >        // number of elements after to-be-deleted elt
626 >        final int back = sub(t = tail, i, capacity) - 1;
627          if (front < back) {
628 +            // move front elements forwards
629              if (h <= i) {
630 <                System.arraycopy(elements, h, elements, h + 1, front);
630 >                System.arraycopy(es, h, es, h + 1, front);
631              } else { // Wrap around
632 <                System.arraycopy(elements, 0, elements, 1, i);
633 <                elements[0] = elements[mask];
634 <                System.arraycopy(elements, h, elements, h + 1, mask - h);
632 >                System.arraycopy(es, 0, es, 1, i);
633 >                es[0] = es[capacity - 1];
634 >                System.arraycopy(es, h, es, h + 1, front - (i + 1));
635              }
636 <            elements[h] = null;
637 <            head = (h + 1) & mask;
636 >            es[h] = null;
637 >            head = inc(h, capacity);
638 >            // checkInvariants();
639              return false;
640          } else {
641 <            if (i < t) { // Copy the null tail as well
642 <                System.arraycopy(elements, i + 1, elements, i, back);
643 <                tail = t - 1;
641 >            // move back elements backwards
642 >            tail = dec(t, capacity);
643 >            if (i <= tail) {
644 >                System.arraycopy(es, i + 1, es, i, back);
645              } else { // Wrap around
646 <                System.arraycopy(elements, i + 1, elements, i, mask - i);
647 <                elements[mask] = elements[0];
648 <                System.arraycopy(elements, 1, elements, 0, t);
522 <                tail = (t - 1) & mask;
646 >                System.arraycopy(es, i + 1, es, i, capacity - (i + 1));
647 >                es[capacity - 1] = es[0];
648 >                System.arraycopy(es, 1, es, 0, t - 1);
649              }
650 +            es[tail] = null;
651 +            // checkInvariants();
652              return true;
653          }
654      }
# Line 533 | Line 661 | public class ArrayDeque<E> extends Abstr
661       * @return the number of elements in this deque
662       */
663      public int size() {
664 <        return (tail - head) & (elements.length - 1);
664 >        return sub(tail, head, elements.length);
665      }
666  
667      /**
# Line 562 | Line 690 | public class ArrayDeque<E> extends Abstr
690      }
691  
692      private class DeqIterator implements Iterator<E> {
693 <        /**
694 <         * Index of element to be returned by subsequent call to next.
567 <         */
568 <        private int cursor = head;
693 >        /** Index of element to be returned by subsequent call to next. */
694 >        int cursor;
695  
696 <        /**
697 <         * Tail recorded at construction (also in remove), to stop
572 <         * iterator and also to check for comodification.
573 <         */
574 <        private int fence = tail;
696 >        /** Number of elements yet to be returned. */
697 >        int remaining = size();
698  
699          /**
700           * Index of element returned by most recent call to next.
701           * Reset to -1 if element is deleted by a call to remove.
702           */
703 <        private int lastRet = -1;
703 >        int lastRet = -1;
704  
705 <        public boolean hasNext() {
706 <            return cursor != fence;
705 >        DeqIterator() { cursor = head; }
706 >
707 >        public final boolean hasNext() {
708 >            return remaining > 0;
709          }
710  
711          public E next() {
712 <            if (cursor == fence)
712 >            if (remaining <= 0)
713                  throw new NoSuchElementException();
714 <            @SuppressWarnings("unchecked")
715 <            E result = (E) elements[cursor];
716 <            // This check doesn't catch all possible comodifications,
717 <            // but does catch the ones that corrupt traversal
718 <            if (tail != fence || result == null)
719 <                throw new ConcurrentModificationException();
720 <            lastRet = cursor;
721 <            cursor = (cursor + 1) & (elements.length - 1);
722 <            return result;
714 >            final Object[] es = elements;
715 >            E e = nonNullElementAt(es, cursor);
716 >            cursor = inc(lastRet = cursor, es.length);
717 >            remaining--;
718 >            return e;
719 >        }
720 >
721 >        void postDelete(boolean leftShifted) {
722 >            if (leftShifted)
723 >                cursor = dec(cursor, elements.length);
724          }
725  
726 <        public void remove() {
726 >        public final void remove() {
727              if (lastRet < 0)
728                  throw new IllegalStateException();
729 <            if (delete(lastRet)) { // if left-shifted, undo increment in next()
604 <                cursor = (cursor - 1) & (elements.length - 1);
605 <                fence = tail;
606 <            }
729 >            postDelete(delete(lastRet));
730              lastRet = -1;
731          }
732 +
733 +        public void forEachRemaining(Consumer<? super E> action) {
734 +            Objects.requireNonNull(action);
735 +            int r;
736 +            if ((r = remaining) <= 0)
737 +                return;
738 +            remaining = 0;
739 +            final Object[] es = elements;
740 +            if (es[cursor] == null || sub(tail, cursor, es.length) != r)
741 +                throw new ConcurrentModificationException();
742 +            for (int i = cursor, end = tail, to = (i <= end) ? end : es.length;
743 +                 ; i = 0, to = end) {
744 +                for (; i < to; i++)
745 +                    action.accept(elementAt(es, i));
746 +                if (to == end) {
747 +                    if (end != tail)
748 +                        throw new ConcurrentModificationException();
749 +                    lastRet = dec(end, es.length);
750 +                    break;
751 +                }
752 +            }
753 +        }
754 +    }
755 +
756 +    private class DescendingIterator extends DeqIterator {
757 +        DescendingIterator() { cursor = dec(tail, elements.length); }
758 +
759 +        public final E next() {
760 +            if (remaining <= 0)
761 +                throw new NoSuchElementException();
762 +            final Object[] es = elements;
763 +            E e = nonNullElementAt(es, cursor);
764 +            cursor = dec(lastRet = cursor, es.length);
765 +            remaining--;
766 +            return e;
767 +        }
768 +
769 +        void postDelete(boolean leftShifted) {
770 +            if (!leftShifted)
771 +                cursor = inc(cursor, elements.length);
772 +        }
773 +
774 +        public final void forEachRemaining(Consumer<? super E> action) {
775 +            Objects.requireNonNull(action);
776 +            int r;
777 +            if ((r = remaining) <= 0)
778 +                return;
779 +            remaining = 0;
780 +            final Object[] es = elements;
781 +            if (es[cursor] == null || sub(cursor, head, es.length) + 1 != r)
782 +                throw new ConcurrentModificationException();
783 +            for (int i = cursor, end = head, to = (i >= end) ? end : 0;
784 +                 ; i = es.length - 1, to = end) {
785 +                // hotspot generates faster code than for: i >= to !
786 +                for (; i > to - 1; i--)
787 +                    action.accept(elementAt(es, i));
788 +                if (to == end) {
789 +                    if (end != head)
790 +                        throw new ConcurrentModificationException();
791 +                    lastRet = end;
792 +                    break;
793 +                }
794 +            }
795 +        }
796      }
797  
798      /**
799 <     * This class is nearly a mirror-image of DeqIterator, using tail
800 <     * instead of head for initial cursor, and head instead of tail
801 <     * for fence.
802 <     */
803 <    private class DescendingIterator implements Iterator<E> {
804 <        private int cursor = tail;
805 <        private int fence = head;
806 <        private int lastRet = -1;
799 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
800 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
801 >     * deque.
802 >     *
803 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
804 >     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
805 >     * {@link Spliterator#NONNULL}.  Overriding implementations should document
806 >     * the reporting of additional characteristic values.
807 >     *
808 >     * @return a {@code Spliterator} over the elements in this deque
809 >     * @since 1.8
810 >     */
811 >    public Spliterator<E> spliterator() {
812 >        return new DeqSpliterator();
813 >    }
814 >
815 >    final class DeqSpliterator implements Spliterator<E> {
816 >        private int fence;      // -1 until first use
817 >        private int cursor;     // current index, modified on traverse/split
818  
819 <        public boolean hasNext() {
820 <            return cursor != fence;
819 >        /** Constructs late-binding spliterator over all elements. */
820 >        DeqSpliterator() {
821 >            this.fence = -1;
822          }
823  
824 <        public E next() {
825 <            if (cursor == fence)
826 <                throw new NoSuchElementException();
827 <            cursor = (cursor - 1) & (elements.length - 1);
828 <            @SuppressWarnings("unchecked")
829 <            E result = (E) elements[cursor];
631 <            if (head != fence || result == null)
632 <                throw new ConcurrentModificationException();
633 <            lastRet = cursor;
634 <            return result;
824 >        /** Constructs spliterator over the given range. */
825 >        DeqSpliterator(int origin, int fence) {
826 >            // assert 0 <= origin && origin < elements.length;
827 >            // assert 0 <= fence && fence < elements.length;
828 >            this.cursor = origin;
829 >            this.fence = fence;
830          }
831  
832 <        public void remove() {
833 <            if (lastRet < 0)
834 <                throw new IllegalStateException();
835 <            if (!delete(lastRet)) {
836 <                cursor = (cursor + 1) & (elements.length - 1);
837 <                fence = head;
832 >        /** Ensures late-binding initialization; then returns fence. */
833 >        private int getFence() { // force initialization
834 >            int t;
835 >            if ((t = fence) < 0) {
836 >                t = fence = tail;
837 >                cursor = head;
838 >            }
839 >            return t;
840 >        }
841 >
842 >        public DeqSpliterator trySplit() {
843 >            final Object[] es = elements;
844 >            final int i, n;
845 >            return ((n = sub(getFence(), i = cursor, es.length) >> 1) <= 0)
846 >                ? null
847 >                : new DeqSpliterator(i, cursor = inc(i, n, es.length));
848 >        }
849 >
850 >        public void forEachRemaining(Consumer<? super E> action) {
851 >            if (action == null)
852 >                throw new NullPointerException();
853 >            final int end = getFence(), cursor = this.cursor;
854 >            final Object[] es = elements;
855 >            if (cursor != end) {
856 >                this.cursor = end;
857 >                // null check at both ends of range is sufficient
858 >                if (es[cursor] == null || es[dec(end, es.length)] == null)
859 >                    throw new ConcurrentModificationException();
860 >                for (int i = cursor, to = (i <= end) ? end : es.length;
861 >                     ; i = 0, to = end) {
862 >                    for (; i < to; i++)
863 >                        action.accept(elementAt(es, i));
864 >                    if (to == end) break;
865 >                }
866 >            }
867 >        }
868 >
869 >        public boolean tryAdvance(Consumer<? super E> action) {
870 >            Objects.requireNonNull(action);
871 >            final Object[] es = elements;
872 >            if (fence < 0) { fence = tail; cursor = head; } // late-binding
873 >            final int i;
874 >            if ((i = cursor) == fence)
875 >                return false;
876 >            E e = nonNullElementAt(es, i);
877 >            cursor = inc(i, es.length);
878 >            action.accept(e);
879 >            return true;
880 >        }
881 >
882 >        public long estimateSize() {
883 >            return sub(getFence(), cursor, elements.length);
884 >        }
885 >
886 >        public int characteristics() {
887 >            return Spliterator.NONNULL
888 >                | Spliterator.ORDERED
889 >                | Spliterator.SIZED
890 >                | Spliterator.SUBSIZED;
891 >        }
892 >    }
893 >
894 >    /**
895 >     * @throws NullPointerException {@inheritDoc}
896 >     */
897 >    public void forEach(Consumer<? super E> action) {
898 >        Objects.requireNonNull(action);
899 >        final Object[] es = elements;
900 >        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
901 >             ; i = 0, to = end) {
902 >            for (; i < to; i++)
903 >                action.accept(elementAt(es, i));
904 >            if (to == end) {
905 >                if (end != tail) throw new ConcurrentModificationException();
906 >                break;
907              }
644            lastRet = -1;
908          }
909 +        // checkInvariants();
910 +    }
911 +
912 +    /**
913 +     * Replaces each element of this deque with the result of applying the
914 +     * operator to that element, as specified by {@link List#replaceAll}.
915 +     *
916 +     * @param operator the operator to apply to each element
917 +     * @since TBD
918 +     */
919 +    /* public */ void replaceAll(java.util.function.UnaryOperator<E> operator) {
920 +        Objects.requireNonNull(operator);
921 +        final Object[] es = elements;
922 +        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
923 +             ; i = 0, to = end) {
924 +            for (; i < to; i++)
925 +                es[i] = operator.apply(elementAt(es, i));
926 +            if (to == end) {
927 +                if (end != tail) throw new ConcurrentModificationException();
928 +                break;
929 +            }
930 +        }
931 +        // checkInvariants();
932 +    }
933 +
934 +    /**
935 +     * @throws NullPointerException {@inheritDoc}
936 +     */
937 +    public boolean removeIf(Predicate<? super E> filter) {
938 +        Objects.requireNonNull(filter);
939 +        return bulkRemove(filter);
940 +    }
941 +
942 +    /**
943 +     * @throws NullPointerException {@inheritDoc}
944 +     */
945 +    public boolean removeAll(Collection<?> c) {
946 +        Objects.requireNonNull(c);
947 +        return bulkRemove(e -> c.contains(e));
948 +    }
949 +
950 +    /**
951 +     * @throws NullPointerException {@inheritDoc}
952 +     */
953 +    public boolean retainAll(Collection<?> c) {
954 +        Objects.requireNonNull(c);
955 +        return bulkRemove(e -> !c.contains(e));
956 +    }
957 +
958 +    /** Implementation of bulk remove methods. */
959 +    private boolean bulkRemove(Predicate<? super E> filter) {
960 +        // checkInvariants();
961 +        final Object[] es = elements;
962 +        // Optimize for initial run of survivors
963 +        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
964 +             ; i = 0, to = end) {
965 +            for (; i < to; i++)
966 +                if (filter.test(elementAt(es, i)))
967 +                    return bulkRemoveModified(filter, i);
968 +            if (to == end) {
969 +                if (end != tail) throw new ConcurrentModificationException();
970 +                break;
971 +            }
972 +        }
973 +        return false;
974 +    }
975 +
976 +    // A tiny bit set implementation
977 +
978 +    private static long[] nBits(int n) {
979 +        return new long[((n - 1) >> 6) + 1];
980 +    }
981 +    private static void setBit(long[] bits, int i) {
982 +        bits[i >> 6] |= 1L << i;
983 +    }
984 +    private static boolean isClear(long[] bits, int i) {
985 +        return (bits[i >> 6] & (1L << i)) == 0;
986 +    }
987 +
988 +    /**
989 +     * Helper for bulkRemove, in case of at least one deletion.
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 +     *
994 +     * @param beg valid index of first element to be deleted
995 +     */
996 +    private boolean bulkRemoveModified(
997 +        Predicate<? super E> filter, final int beg) {
998 +        final Object[] es = elements;
999 +        final int capacity = es.length;
1000 +        final int end = tail;
1001 +        final long[] deathRow = nBits(sub(end, beg, capacity));
1002 +        deathRow[0] = 1L;   // set bit 0
1003 +        for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
1004 +             ; i = 0, to = end, k -= capacity) {
1005 +            for (; i < to; i++)
1006 +                if (filter.test(elementAt(es, i)))
1007 +                    setBit(deathRow, i - k);
1008 +            if (to == end) break;
1009 +        }
1010 +        // a two-finger traversal, with hare i reading, tortoise w writing
1011 +        int w = beg;
1012 +        for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
1013 +             ; w = 0) { // w rejoins i on second leg
1014 +            // In this loop, i and w are on the same leg, with i > w
1015 +            for (; i < to; i++)
1016 +                if (isClear(deathRow, i - k))
1017 +                    es[w++] = es[i];
1018 +            if (to == end) break;
1019 +            // In this loop, w is on the first leg, i on the second
1020 +            for (i = 0, to = end, k -= capacity; i < to && w < capacity; i++)
1021 +                if (isClear(deathRow, i - k))
1022 +                    es[w++] = es[i];
1023 +            if (i >= to) {
1024 +                if (w == capacity) w = 0; // "corner" case
1025 +                break;
1026 +            }
1027 +        }
1028 +        if (end != tail) throw new ConcurrentModificationException();
1029 +        circularClear(es, tail = w, end);
1030 +        // checkInvariants();
1031 +        return true;
1032      }
1033  
1034      /**
# Line 655 | Line 1041 | public class ArrayDeque<E> extends Abstr
1041       */
1042      public boolean contains(Object o) {
1043          if (o != null) {
1044 <            int mask = elements.length - 1;
1045 <            int i = head;
1046 <            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
1047 <                if (o.equals(x))
1048 <                    return true;
1044 >            final Object[] es = elements;
1045 >            for (int i = head, end = tail, to = (i <= end) ? end : es.length;
1046 >                 ; i = 0, to = end) {
1047 >                for (; i < to; i++)
1048 >                    if (o.equals(es[i]))
1049 >                        return true;
1050 >                if (to == end) break;
1051              }
1052          }
1053          return false;
# Line 687 | Line 1075 | public class ArrayDeque<E> extends Abstr
1075       * The deque will be empty after this call returns.
1076       */
1077      public void clear() {
1078 <        int h = head;
1079 <        int t = tail;
1080 <        if (h != t) { // clear all cells
1081 <            head = tail = 0;
1082 <            int i = h;
1083 <            int mask = elements.length - 1;
1084 <            do {
1085 <                elements[i] = null;
1086 <                i = (i + 1) & mask;
1087 <            } while (i != t);
1078 >        circularClear(elements, head, tail);
1079 >        head = tail = 0;
1080 >        // checkInvariants();
1081 >    }
1082 >
1083 >    /**
1084 >     * Nulls out slots starting at array index i, upto index end.
1085 >     * Condition i == end means "empty" - nothing to do.
1086 >     */
1087 >    private static void circularClear(Object[] es, int i, int end) {
1088 >        // assert 0 <= i && i < es.length;
1089 >        // assert 0 <= end && end < es.length;
1090 >        for (int to = (i <= end) ? end : es.length;
1091 >             ; i = 0, to = end) {
1092 >            for (; i < to; i++) es[i] = null;
1093 >            if (to == end) break;
1094          }
1095      }
1096  
# Line 714 | Line 1108 | public class ArrayDeque<E> extends Abstr
1108       * @return an array containing all of the elements in this deque
1109       */
1110      public Object[] toArray() {
1111 <        final int head = this.head;
1112 <        final int tail = this.tail;
1113 <        boolean wrap = (tail < head);
1114 <        int end = wrap ? tail + elements.length : tail;
1115 <        Object[] a = Arrays.copyOfRange(elements, head, end);
1116 <        if (wrap)
1117 <            System.arraycopy(elements, 0, a, elements.length - head, tail);
1111 >        return toArray(Object[].class);
1112 >    }
1113 >
1114 >    private <T> T[] toArray(Class<T[]> klazz) {
1115 >        final Object[] es = elements;
1116 >        final T[] a;
1117 >        final int head = this.head, tail = this.tail, end;
1118 >        if ((end = tail + ((head <= tail) ? 0 : es.length)) >= 0) {
1119 >            // Uses null extension feature of copyOfRange
1120 >            a = Arrays.copyOfRange(es, head, end, klazz);
1121 >        } else {
1122 >            // integer overflow!
1123 >            a = Arrays.copyOfRange(es, 0, end - head, klazz);
1124 >            System.arraycopy(es, head, a, 0, es.length - head);
1125 >        }
1126 >        if (end != tail)
1127 >            System.arraycopy(es, 0, a, es.length - head, tail);
1128          return a;
1129      }
1130  
# Line 762 | Line 1166 | public class ArrayDeque<E> extends Abstr
1166       */
1167      @SuppressWarnings("unchecked")
1168      public <T> T[] toArray(T[] a) {
1169 <        final int head = this.head;
1170 <        final int tail = this.tail;
1171 <        boolean wrap = (tail < head);
1172 <        int size = (tail - head) + (wrap ? elements.length : 0);
1173 <        int firstLeg = size - (wrap ? tail : 0);
1174 <        int len = a.length;
1175 <        if (size > len) {
1176 <            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
773 <                                         a.getClass());
774 <        } else {
775 <            System.arraycopy(elements, head, a, 0, firstLeg);
776 <            if (size < len)
777 <                a[size] = null;
1169 >        final int size;
1170 >        if ((size = size()) > a.length)
1171 >            return toArray((Class<T[]>) a.getClass());
1172 >        final Object[] es = elements;
1173 >        for (int i = head, j = 0, len = Math.min(size, es.length - i);
1174 >             ; i = 0, len = tail) {
1175 >            System.arraycopy(es, i, a, j, len);
1176 >            if ((j += len) == size) break;
1177          }
1178 <        if (wrap)
1179 <            System.arraycopy(elements, 0, a, firstLeg, tail);
1178 >        if (size < a.length)
1179 >            a[size] = null;
1180          return a;
1181      }
1182  
# Line 818 | Line 1217 | public class ArrayDeque<E> extends Abstr
1217          s.writeInt(size());
1218  
1219          // Write out elements in order.
1220 <        int mask = elements.length - 1;
1221 <        for (int i = head; i != tail; i = (i + 1) & mask)
1222 <            s.writeObject(elements[i]);
1220 >        final Object[] es = elements;
1221 >        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
1222 >             ; i = 0, to = end) {
1223 >            for (; i < to; i++)
1224 >                s.writeObject(es[i]);
1225 >            if (to == end) break;
1226 >        }
1227      }
1228  
1229      /**
# Line 836 | Line 1239 | public class ArrayDeque<E> extends Abstr
1239  
1240          // Read in size and allocate array
1241          int size = s.readInt();
1242 <        allocateElements(size);
1243 <        head = 0;
1244 <        tail = size;
1242 >        jsr166.Platform.checkArray(s, Object[].class, size + 1);
1243 >        elements = new Object[size + 1];
1244 >        this.tail = size;
1245  
1246          // Read in all elements in the proper order.
1247          for (int i = 0; i < size; i++)
1248              elements[i] = s.readObject();
1249      }
1250  
1251 <    public Spliterator<E> spliterator() {
1252 <        return new DeqSpliterator<E>(this, -1, -1);
1253 <    }
1254 <
1255 <    static final class DeqSpliterator<E> implements Spliterator<E> {
1256 <        private final ArrayDeque<E> deq;
1257 <        private int fence;  // -1 until first use
1258 <        private int index;  // current index, modified on traverse/split
1259 <
1260 <        /** Creates new spliterator covering the given array and range */
1261 <        DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
1262 <            this.deq = deq;
1263 <            this.index = origin;
1264 <            this.fence = fence;
1265 <        }
1266 <
1267 <        private int getFence() { // force initialization
1268 <            int t;
1269 <            if ((t = fence) < 0) {
867 <                t = fence = deq.tail;
868 <                index = deq.head;
869 <            }
870 <            return t;
871 <        }
872 <
873 <        public Spliterator<E> trySplit() {
874 <            int t = getFence(), h = index, n = deq.elements.length;
875 <            if (h != t && ((h + 1) & (n - 1)) != t) {
876 <                if (h > t)
877 <                    t += n;
878 <                int m = ((h + t) >>> 1) & (n - 1);
879 <                return new DeqSpliterator<>(deq, h, index = m);
880 <            }
881 <            return null;
882 <        }
883 <
884 <        public void forEachRemaining(Consumer<? super E> consumer) {
885 <            if (consumer == null)
886 <                throw new NullPointerException();
887 <            Object[] a = deq.elements;
888 <            int m = a.length - 1, f = getFence(), i = index;
889 <            index = f;
890 <            while (i != f) {
891 <                @SuppressWarnings("unchecked") E e = (E)a[i];
892 <                i = (i + 1) & m;
893 <                if (e == null)
894 <                    throw new ConcurrentModificationException();
895 <                consumer.accept(e);
896 <            }
897 <        }
898 <
899 <        public boolean tryAdvance(Consumer<? super E> consumer) {
900 <            if (consumer == null)
901 <                throw new NullPointerException();
902 <            Object[] a = deq.elements;
903 <            int m = a.length - 1, f = getFence(), i = index;
904 <            if (i != f) {
905 <                @SuppressWarnings("unchecked") E e = (E)a[i];
906 <                index = (i + 1) & m;
907 <                if (e == null)
908 <                    throw new ConcurrentModificationException();
909 <                consumer.accept(e);
910 <                return true;
911 <            }
912 <            return false;
913 <        }
914 <
915 <        public long estimateSize() {
916 <            int n = getFence() - index;
917 <            if (n < 0)
918 <                n += deq.elements.length;
919 <            return (long) n;
920 <        }
921 <
922 <        @Override
923 <        public int characteristics() {
924 <            return Spliterator.ORDERED | Spliterator.SIZED |
925 <                Spliterator.NONNULL | Spliterator.SUBSIZED;
1251 >    /** debugging */
1252 >    void checkInvariants() {
1253 >        // Use head and tail fields with empty slot at tail strategy.
1254 >        // head == tail disambiguates to "empty".
1255 >        try {
1256 >            int capacity = elements.length;
1257 >            // assert 0 <= head && head < capacity;
1258 >            // assert 0 <= tail && tail < capacity;
1259 >            // assert capacity > 0;
1260 >            // assert size() < capacity;
1261 >            // assert head == tail || elements[head] != null;
1262 >            // assert elements[tail] == null;
1263 >            // assert head == tail || elements[dec(tail, capacity)] != null;
1264 >        } catch (Throwable t) {
1265 >            System.err.printf("head=%d tail=%d capacity=%d%n",
1266 >                              head, tail, elements.length);
1267 >            System.err.printf("elements=%s%n",
1268 >                              Arrays.toString(elements));
1269 >            throw t;
1270          }
1271      }
1272  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines