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.95 by jsr166, Sat Oct 29 19:10:27 2016 UTC vs.
Revision 1.137 by jsr166, Sun Nov 11 17:37:30 2018 UTC

# Line 8 | Line 8 | package java.util;
8   import java.io.Serializable;
9   import java.util.function.Consumer;
10   import java.util.function.Predicate;
11 < import java.util.function.UnaryOperator;
11 > // OPENJDK import jdk.internal.access.SharedSecrets;
12  
13   /**
14   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 50 | Line 50 | import java.util.function.UnaryOperator;
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
# Line 60 | Line 60 | import java.util.function.UnaryOperator;
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 <     * We guarantee that all array cells not holding deque elements
79 <     * 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;
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 0 <= head < elements.length 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 <    /** Number of elements in this collection. */
92 <    transient int size;
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));
94 >     * elements[tail] is always null.
95 >     */
96 >    transient int tail;
97  
98      /**
99       * The maximum size of array to allocate.
# Line 92 | Line 110 | public class ArrayDeque<E> extends Abstr
110       */
111      private void grow(int needed) {
112          // overflow-conscious code
95        // checkInvariants();
113          final int oldCapacity = elements.length;
114          int newCapacity;
115 <        // Double size if small; else grow by 50%
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 <        elements = Arrays.copyOf(elements, newCapacity);
121 <        if (oldCapacity - head < size) {
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(elements, head,
126 <                             elements, head + newSpace,
125 >            System.arraycopy(es, head,
126 >                             es, head + newSpace,
127                               oldCapacity - head);
128 <            Arrays.fill(elements, head, head + newSpace, null);
129 <            head += newSpace;
128 >            for (int i = head, to = (head += newSpace); i < to; i++)
129 >                es[i] = null;
130          }
131          // checkInvariants();
132      }
# Line 136 | Line 154 | public class ArrayDeque<E> extends Abstr
154       * @since TBD
155       */
156      /* public */ void ensureCapacity(int minCapacity) {
157 <        if (minCapacity > elements.length)
158 <            grow(minCapacity - elements.length);
157 >        int needed;
158 >        if ((needed = (minCapacity + 1 - elements.length)) > 0)
159 >            grow(needed);
160          // checkInvariants();
161      }
162  
# Line 147 | Line 166 | public class ArrayDeque<E> extends Abstr
166       * @since TBD
167       */
168      /* public */ void trimToSize() {
169 <        if (size < elements.length) {
170 <            elements = toArray();
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      }
# Line 159 | 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      /**
# Line 169 | Line 190 | public class ArrayDeque<E> extends Abstr
190       * @param numElements lower bound on initial capacity of the deque
191       */
192      public ArrayDeque(int numElements) {
193 <        elements = new Object[numElements];
193 >        elements =
194 >            new Object[(numElements < 1) ? 1 :
195 >                       (numElements == Integer.MAX_VALUE) ? Integer.MAX_VALUE :
196 >                       numElements + 1];
197      }
198  
199      /**
# Line 183 | 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 <        Object[] es = c.toArray();
211 <        // defend against c.toArray (incorrectly) not returning Object[]
188 <        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
189 <        if (es.getClass() != Object[].class)
190 <            es = Arrays.copyOf(es, es.length, Object[].class);
191 <        for (Object obj : es)
192 <            Objects.requireNonNull(obj);
193 <        this.elements = es;
194 <        this.size = es.length;
210 >        this(c.size());
211 >        copyElements(c);
212      }
213  
214      /**
215 <     * Increments i, mod modulus.
215 >     * Circularly increments i, mod modulus.
216       * Precondition and postcondition: 0 <= i < modulus.
217       */
218      static final int inc(int i, int modulus) {
# Line 204 | Line 221 | public class ArrayDeque<E> extends Abstr
221      }
222  
223      /**
224 <     * Decrements i, mod modulus.
224 >     * Circularly decrements i, mod modulus.
225       * Precondition and postcondition: 0 <= i < modulus.
226       */
227      static final int dec(int i, int modulus) {
# Line 213 | Line 230 | public class ArrayDeque<E> extends Abstr
230      }
231  
232      /**
233 <     * Adds i and j, mod modulus.
234 <     * Precondition and postcondition: 0 <= i < modulus, 0 <= j <= modulus.
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 add(int i, int j, int modulus) {
238 <        if ((i += j) - modulus >= 0) i -= modulus;
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 <     * Returns the array index of the last element.
244 <     * May return invalid index -1 if there are no elements.
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 <    final int tail() {
250 <        return add(head, size - 1, elements.length);
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 <    private E elementAt(int i) {
260 <        return (E) elements[i];
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.  It's a little
244 <     * surprising that javac allows this abuse of generics.
266 >     * but does catch ones that corrupt traversal.
267       */
268 <    static final <E> E nonNullElementAt(Object[] elements, int i) {
269 <        @SuppressWarnings("unchecked") E e = (E) elements[i];
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;
# Line 261 | Line 283 | public class ArrayDeque<E> extends Abstr
283       * @throws NullPointerException if the specified element is null
284       */
285      public void addFirst(E e) {
286 <        // checkInvariants();
287 <        Objects.requireNonNull(e);
288 <        Object[] es;
289 <        int capacity, h;
290 <        final int s;
269 <        if ((s = size) == (capacity = (es = elements).length)) {
286 >        if (e == null)
287 >            throw new NullPointerException();
288 >        final Object[] es = elements;
289 >        es[head = dec(head, es.length)] = e;
290 >        if (head == tail)
291              grow(1);
271            capacity = (es = elements).length;
272        }
273        if ((h = head - 1) < 0) h = capacity - 1;
274        es[head = h] = e;
275        size = s + 1;
292          // checkInvariants();
293      }
294  
# Line 285 | Line 301 | public class ArrayDeque<E> extends Abstr
301       * @throws NullPointerException if the specified element is null
302       */
303      public void addLast(E e) {
304 <        // checkInvariants();
305 <        Objects.requireNonNull(e);
306 <        Object[] es;
307 <        int capacity;
308 <        final int s;
293 <        if ((s = size) == (capacity = (es = elements).length)) {
304 >        if (e == null)
305 >            throw new NullPointerException();
306 >        final Object[] es = elements;
307 >        es[tail] = e;
308 >        if (head == (tail = inc(tail, es.length)))
309              grow(1);
295            capacity = (es = elements).length;
296        }
297        es[add(head, s, capacity)] = e;
298        size = s + 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
306 <     * iterator.
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
# Line 311 | Line 321 | public class ArrayDeque<E> extends Abstr
321       *         of its elements are null
322       */
323      public boolean addAll(Collection<? extends E> c) {
324 <        final int s = size, needed = c.size() - (elements.length - s);
325 <        if (needed > 0)
324 >        final int s, needed;
325 >        if ((needed = (s = size()) + c.size() + 1 - elements.length) > 0)
326              grow(needed);
327 <        c.forEach((e) -> addLast(e));
327 >        copyElements(c);
328          // checkInvariants();
329 <        return size > s;
329 >        return size() > s;
330 >    }
331 >
332 >    private void copyElements(Collection<? extends E> c) {
333 >        c.forEach(this::addLast);
334      }
335  
336      /**
# Line 347 | Line 361 | public class ArrayDeque<E> extends Abstr
361       * @throws NoSuchElementException {@inheritDoc}
362       */
363      public E removeFirst() {
350        // checkInvariants();
364          E e = pollFirst();
365          if (e == null)
366              throw new NoSuchElementException();
367 +        // checkInvariants();
368          return e;
369      }
370  
# Line 358 | Line 372 | public class ArrayDeque<E> extends Abstr
372       * @throws NoSuchElementException {@inheritDoc}
373       */
374      public E removeLast() {
361        // checkInvariants();
375          E e = pollLast();
376          if (e == null)
377              throw new NoSuchElementException();
378 +        // checkInvariants();
379          return e;
380      }
381  
382      public E pollFirst() {
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          // checkInvariants();
370        int s, h;
371        if ((s = size) <= 0)
372            return null;
373        final Object[] elements = this.elements;
374        @SuppressWarnings("unchecked") E e = (E) elements[h = head];
375        elements[h] = null;
376        if (++h >= elements.length) h = 0;
377        head = h;
378        size = s - 1;
391          return e;
392      }
393  
394      public E pollLast() {
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();
384        final int s, tail;
385        if ((s = size) <= 0)
386            return null;
387        final Object[] elements = this.elements;
388        @SuppressWarnings("unchecked")
389        E e = (E) elements[tail = add(head, s - 1, elements.length)];
390        elements[tail] = null;
391        size = s - 1;
401          return e;
402      }
403  
# Line 396 | Line 405 | public class ArrayDeque<E> extends Abstr
405       * @throws NoSuchElementException {@inheritDoc}
406       */
407      public E getFirst() {
408 +        E e = elementAt(elements, head);
409 +        if (e == null)
410 +            throw new NoSuchElementException();
411          // checkInvariants();
412 <        if (size <= 0) throw new NoSuchElementException();
401 <        return elementAt(head);
412 >        return e;
413      }
414  
415      /**
416       * @throws NoSuchElementException {@inheritDoc}
417       */
407    @SuppressWarnings("unchecked")
418      public E getLast() {
419 +        final Object[] es = elements;
420 +        E e = elementAt(es, dec(tail, es.length));
421 +        if (e == null)
422 +            throw new NoSuchElementException();
423          // checkInvariants();
424 <        final int s;
411 <        if ((s = size) <= 0) throw new NoSuchElementException();
412 <        final Object[] elements = this.elements;
413 <        return (E) elements[add(head, s - 1, elements.length)];
424 >        return e;
425      }
426  
427      public E peekFirst() {
428          // checkInvariants();
429 <        return (size <= 0) ? null : elementAt(head);
429 >        return elementAt(elements, head);
430      }
431  
421    @SuppressWarnings("unchecked")
432      public E peekLast() {
433          // checkInvariants();
434 <        final int s;
435 <        if ((s = size) <= 0) return null;
426 <        final Object[] elements = this.elements;
427 <        return (E) elements[add(head, s - 1, elements.length)];
434 >        final Object[] es;
435 >        return elementAt(es = elements, dec(tail, es.length));
436      }
437  
438      /**
# Line 441 | Line 449 | public class ArrayDeque<E> extends Abstr
449       */
450      public boolean removeFirstOccurrence(Object o) {
451          if (o != null) {
452 <            final Object[] elements = this.elements;
453 <            final int capacity = elements.length;
454 <            int i, end, to, todo;
447 <            todo = (end = (i = head) + size)
448 <                - (to = (capacity - end >= 0) ? end : capacity);
449 <            for (;; to = todo, i = 0, todo = 0) {
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(elements[i])) {
456 >                    if (o.equals(es[i])) {
457                          delete(i);
458                          return true;
459                      }
460 <                if (todo == 0) break;
460 >                if (to == end) break;
461              }
462          }
463          return false;
# Line 472 | Line 477 | public class ArrayDeque<E> extends Abstr
477       */
478      public boolean removeLastOccurrence(Object o) {
479          if (o != null) {
480 <            final Object[] elements = this.elements;
481 <            final int capacity = elements.length;
482 <            int i, to, end, todo;
483 <            todo = (to = ((end = (i = tail()) - size) >= -1) ? end : -1) - end;
484 <            for (;; to = (i = capacity - 1) - todo, todo = 0) {
480 <                for (; i > to; i--)
481 <                    if (o.equals(elements[i])) {
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 (todo == 0) break;
488 >                if (to == end) break;
489              }
490          }
491          return false;
# Line 520 | 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 610 | Line 613 | public class ArrayDeque<E> extends Abstr
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      boolean delete(int i) {
619          // checkInvariants();
620 <        final Object[] elements = this.elements;
621 <        final int capacity = elements.length;
622 <        final int h = head;
623 <        int front;              // number of elements before to-be-deleted elt
624 <        if ((front = i - h) < 0) front += capacity;
625 <        final int back = size - front - 1; // number of elements after
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[capacity - 1];
634 <                System.arraycopy(elements, h, elements, h + 1, front - (i + 1));
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 <            if ((head = (h + 1)) >= capacity) head = 0;
634 <            size--;
636 >            es[h] = null;
637 >            head = inc(h, capacity);
638              // checkInvariants();
639              return false;
640          } else {
641              // move back elements backwards
642 <            int tail = tail();
642 >            tail = dec(t, capacity);
643              if (i <= tail) {
644 <                System.arraycopy(elements, i + 1, elements, i, back);
644 >                System.arraycopy(es, i + 1, es, i, back);
645              } else { // Wrap around
646 <                int firstLeg = capacity - (i + 1);
647 <                System.arraycopy(elements, i + 1, elements, i, firstLeg);
648 <                elements[capacity - 1] = elements[0];
646 <                System.arraycopy(elements, 1, elements, 0, back - firstLeg - 1);
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 <            elements[tail] = null;
649 <            size--;
650 >            es[tail] = null;
651              // checkInvariants();
652              return true;
653          }
# Line 660 | Line 661 | public class ArrayDeque<E> extends Abstr
661       * @return the number of elements in this deque
662       */
663      public int size() {
664 <        return size;
664 >        return sub(tail, head, elements.length);
665      }
666  
667      /**
# Line 669 | Line 670 | public class ArrayDeque<E> extends Abstr
670       * @return {@code true} if this deque contains no elements
671       */
672      public boolean isEmpty() {
673 <        return size == 0;
673 >        return head == tail;
674      }
675  
676      /**
# Line 693 | Line 694 | public class ArrayDeque<E> extends Abstr
694          int cursor;
695  
696          /** Number of elements yet to be returned. */
697 <        int remaining = size;
697 >        int remaining = size();
698  
699          /**
700           * Index of element returned by most recent call to next.
# Line 710 | Line 711 | public class ArrayDeque<E> extends Abstr
711          public E next() {
712              if (remaining <= 0)
713                  throw new NoSuchElementException();
714 <            final Object[] elements = ArrayDeque.this.elements;
715 <            E e = nonNullElementAt(elements, cursor);
716 <            lastRet = cursor;
716 <            if (++cursor >= elements.length) cursor = 0;
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 <                if (--cursor < 0) cursor = elements.length - 1;
723 >                cursor = dec(cursor, elements.length);
724          }
725  
726          public final void remove() {
# Line 731 | Line 731 | public class ArrayDeque<E> extends Abstr
731          }
732  
733          public void forEachRemaining(Consumer<? super E> action) {
734 <            final int k;
735 <            if ((k = remaining) > 0) {
736 <                remaining = 0;
737 <                ArrayDeque.forEachRemaining(action, elements, cursor, k);
738 <                if ((lastRet = cursor + k - 1) >= elements.length)
739 <                    lastRet -= elements.length;
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 = tail(); }
757 >        DescendingIterator() { cursor = dec(tail, elements.length); }
758  
759          public final E next() {
760              if (remaining <= 0)
761                  throw new NoSuchElementException();
762 <            final Object[] elements = ArrayDeque.this.elements;
763 <            E e = nonNullElementAt(elements, cursor);
764 <            lastRet = cursor;
753 <            if (--cursor < 0) cursor = elements.length - 1;
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 <                if (++cursor >= elements.length) cursor = 0;
771 >                cursor = inc(cursor, elements.length);
772          }
773  
774          public final void forEachRemaining(Consumer<? super E> action) {
775 <            final int k;
776 <            if ((k = remaining) > 0) {
777 <                remaining = 0;
778 <                forEachRemainingDescending(action, elements, cursor, k);
779 <                if ((lastRet = cursor - (k - 1)) < 0)
780 <                    lastRet += elements.length;
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      }
# Line 785 | Line 809 | public class ArrayDeque<E> extends Abstr
809       * @since 1.8
810       */
811      public Spliterator<E> spliterator() {
812 <        return new ArrayDequeSpliterator();
812 >        return new DeqSpliterator();
813      }
814  
815 <    final class ArrayDequeSpliterator implements Spliterator<E> {
816 <        private int cursor;
817 <        private int remaining; // -1 until late-binding first use
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          /** Constructs late-binding spliterator over all elements. */
820 <        ArrayDequeSpliterator() {
821 <            this.remaining = -1;
798 <        }
799 <
800 <        /** Constructs spliterator over the given slice. */
801 <        ArrayDequeSpliterator(int cursor, int count) {
802 <            this.cursor = cursor;
803 <            this.remaining = count;
820 >        DeqSpliterator() {
821 >            this.fence = -1;
822          }
823  
824 <        /** Ensures late-binding initialization; then returns remaining. */
825 <        private int remaining() {
826 <            if (remaining < 0) {
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 >        /** 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;
810                remaining = size;
838              }
839 <            return remaining;
839 >            return t;
840          }
841  
842 <        public ArrayDequeSpliterator trySplit() {
843 <            final int mid;
844 <            if ((mid = remaining() >> 1) > 0) {
845 <                int oldCursor = cursor;
846 <                cursor = add(cursor, mid, elements.length);
847 <                remaining -= mid;
821 <                return new ArrayDequeSpliterator(oldCursor, mid);
822 <            }
823 <            return null;
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 <            final int k = remaining(); // side effect!
852 <            remaining = 0;
853 <            ArrayDeque.forEachRemaining(action, elements, cursor, k);
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 int k;
872 <            if ((k = remaining()) <= 0)
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 <            action.accept(nonNullElementAt(elements, cursor));
877 <            if (++cursor >= elements.length) cursor = 0;
878 <            remaining = k - 1;
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 remaining();
883 >            return sub(getFence(), cursor, elements.length);
884          }
885  
886          public int characteristics() {
# Line 852 | Line 891 | public class ArrayDeque<E> extends Abstr
891          }
892      }
893  
855    @SuppressWarnings("unchecked")
856    public void forEach(Consumer<? super E> action) {
857        Objects.requireNonNull(action);
858        final Object[] elements = this.elements;
859        final int capacity = elements.length;
860        int i, end, to, todo;
861        todo = (end = (i = head) + size)
862            - (to = (capacity - end >= 0) ? end : capacity);
863        for (;; to = todo, i = 0, todo = 0) {
864            for (; i < to; i++)
865                action.accept((E) elements[i]);
866            if (todo == 0) break;
867        }
868        // checkInvariants();
869    }
870
894      /**
895 <     * Calls action on remaining elements, starting at index i and
873 <     * traversing in ascending order.  A variant of forEach that also
874 <     * checks for concurrent modification, for use in iterators.
895 >     * @throws NullPointerException {@inheritDoc}
896       */
897 <    static <E> void forEachRemaining(
877 <        Consumer<? super E> action, Object[] elements, int i, int remaining) {
897 >    public void forEach(Consumer<? super E> action) {
898          Objects.requireNonNull(action);
899 <        final int capacity = elements.length;
900 <        int end, to, todo;
901 <        todo = (end = i + remaining)
882 <            - (to = (capacity - end >= 0) ? end : capacity);
883 <        for (;; to = todo, i = 0, todo = 0) {
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(nonNullElementAt(elements, i));
904 <            if (todo == 0) break;
905 <        }
906 <    }
907 <
890 <    static <E> void forEachRemainingDescending(
891 <        Consumer<? super E> action, Object[] elements, int i, int remaining) {
892 <        Objects.requireNonNull(action);
893 <        final int capacity = elements.length;
894 <        int end, to, todo;
895 <        todo = (to = ((end = i - remaining) >= -1) ? end : -1) - end;
896 <        for (;; to = (i = capacity - 1) - todo, todo = 0) {
897 <            for (; i > to; i--)
898 <                action.accept(nonNullElementAt(elements, i));
899 <            if (todo == 0) break;
903 >                action.accept(elementAt(es, i));
904 >            if (to == end) {
905 >                if (end != tail) throw new ConcurrentModificationException();
906 >                break;
907 >            }
908          }
909 +        // checkInvariants();
910      }
911  
912      /**
# Line 907 | Line 916 | public class ArrayDeque<E> extends Abstr
916       * @param operator the operator to apply to each element
917       * @since TBD
918       */
919 <    /* public */ void replaceAll(UnaryOperator<E> operator) {
919 >    /* public */ void replaceAll(java.util.function.UnaryOperator<E> operator) {
920          Objects.requireNonNull(operator);
921 <        final Object[] elements = this.elements;
922 <        final int capacity = elements.length;
923 <        int i, end, to, todo;
915 <        todo = (end = (i = head) + size)
916 <            - (to = (capacity - end >= 0) ? end : capacity);
917 <        for (;; to = todo, i = 0, todo = 0) {
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 <                elements[i] = operator.apply(elementAt(i));
926 <            if (todo == 0) break;
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      }
# Line 949 | Line 958 | public class ArrayDeque<E> extends Abstr
958      /** Implementation of bulk remove methods. */
959      private boolean bulkRemove(Predicate<? super E> filter) {
960          // checkInvariants();
961 <        final Object[] elements = this.elements;
962 <        final int capacity = elements.length;
963 <        int i = head, j = i, remaining = size, deleted = 0;
964 <        try {
965 <            for (; remaining > 0; remaining--) {
966 <                @SuppressWarnings("unchecked") E e = (E) elements[i];
967 <                if (filter.test(e))
968 <                    deleted++;
969 <                else {
970 <                    if (j != i)
971 <                        elements[j] = e;
972 <                    if (++j >= capacity) j = 0;
973 <                }
974 <                if (++i >= capacity) i = 0;
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              }
967            return deleted > 0;
968        } catch (Throwable ex) {
969            if (deleted > 0)
970                for (; remaining > 0; remaining--) {
971                    elements[j] = elements[i];
972                    if (++i >= capacity) i = 0;
973                    if (++j >= capacity) j = 0;
974                }
975            throw ex;
976        } finally {
977            size -= deleted;
978            clearSlice(elements, j, deleted);
979            // checkInvariants();
1027          }
1028 +        if (end != tail) throw new ConcurrentModificationException();
1029 +        circularClear(es, tail = w, end);
1030 +        // checkInvariants();
1031 +        return true;
1032      }
1033  
1034      /**
# Line 990 | Line 1041 | public class ArrayDeque<E> extends Abstr
1041       */
1042      public boolean contains(Object o) {
1043          if (o != null) {
1044 <            final Object[] elements = this.elements;
1045 <            final int capacity = elements.length;
1046 <            int i, end, to, todo;
996 <            todo = (end = (i = head) + size)
997 <                - (to = (capacity - end >= 0) ? end : capacity);
998 <            for (;; to = todo, i = 0, todo = 0) {
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(elements[i]))
1048 >                    if (o.equals(es[i]))
1049                          return true;
1050 <                if (todo == 0) break;
1050 >                if (to == end) break;
1051              }
1052          }
1053          return false;
# Line 1027 | Line 1075 | public class ArrayDeque<E> extends Abstr
1075       * The deque will be empty after this call returns.
1076       */
1077      public void clear() {
1078 <        clearSlice(elements, head, size);
1079 <        size = head = 0;
1078 >        circularClear(elements, head, tail);
1079 >        head = tail = 0;
1080          // checkInvariants();
1081      }
1082  
1083      /**
1084 <     * Nulls out count elements, starting at array index from.
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 clearSlice(Object[] elements, int from, int count) {
1088 <        final int capacity = elements.length, end = from + count;
1089 <        final int leg = (capacity - end >= 0) ? end : capacity;
1090 <        Arrays.fill(elements, from, leg, null);
1091 <        if (leg != end)
1092 <            Arrays.fill(elements, 0, end - capacity, null);
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  
1097      /**
# Line 1061 | Line 1112 | public class ArrayDeque<E> extends Abstr
1112      }
1113  
1114      private <T> T[] toArray(Class<T[]> klazz) {
1115 <        final Object[] elements = this.elements;
1065 <        final int capacity = elements.length;
1066 <        final int head = this.head, end = head + size;
1115 >        final Object[] es = elements;
1116          final T[] a;
1117 <        if (end >= 0) {
1118 <            a = Arrays.copyOfRange(elements, head, end, klazz);
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(elements, 0, size, klazz);
1124 <            System.arraycopy(elements, head, a, 0, capacity - head);
1123 >            a = Arrays.copyOfRange(es, 0, end - head, klazz);
1124 >            System.arraycopy(es, head, a, 0, es.length - head);
1125          }
1126 <        if (end - capacity > 0)
1127 <            System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1126 >        if (end != tail)
1127 >            System.arraycopy(es, 0, a, es.length - head, tail);
1128          return a;
1129      }
1130  
# Line 1115 | Line 1166 | public class ArrayDeque<E> extends Abstr
1166       */
1167      @SuppressWarnings("unchecked")
1168      public <T> T[] toArray(T[] a) {
1169 <        final int size = this.size;
1170 <        if (size > a.length)
1169 >        final int size;
1170 >        if ((size = size()) > a.length)
1171              return toArray((Class<T[]>) a.getClass());
1172 <        final Object[] elements = this.elements;
1173 <        final int capacity = elements.length;
1174 <        final int head = this.head, end = head + size;
1175 <        final int front = (capacity - end >= 0) ? size : capacity - head;
1176 <        System.arraycopy(elements, head, a, 0, front);
1177 <        if (front != size)
1127 <            System.arraycopy(elements, 0, a, capacity - head, end - capacity);
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 (size < a.length)
1179              a[size] = null;
1180          return a;
# Line 1164 | Line 1214 | public class ArrayDeque<E> extends Abstr
1214          s.defaultWriteObject();
1215  
1216          // Write out size
1217 <        s.writeInt(size);
1217 >        s.writeInt(size());
1218  
1219          // Write out elements in order.
1220 <        final Object[] elements = this.elements;
1221 <        final int capacity = elements.length;
1222 <        int i, end, to, todo;
1173 <        todo = (end = (i = head) + size)
1174 <            - (to = (capacity - end >= 0) ? end : capacity);
1175 <        for (;; to = todo, i = 0, todo = 0) {
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(elements[i]);
1225 <            if (todo == 0) break;
1224 >                s.writeObject(es[i]);
1225 >            if (to == end) break;
1226          }
1227      }
1228  
# Line 1191 | Line 1238 | public class ArrayDeque<E> extends Abstr
1238          s.defaultReadObject();
1239  
1240          // Read in size and allocate array
1241 <        elements = new Object[size = s.readInt()];
1241 >        int size = s.readInt();
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++)
# Line 1200 | Line 1250 | public class ArrayDeque<E> extends Abstr
1250  
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 size >= 0 && size <= capacity;
1258 <            // assert head >= 0;
1259 <            // assert capacity == 0 || head < capacity;
1260 <            // assert size == 0 || elements[head] != null;
1261 <            // assert size == 0 || elements[tail()] != null;
1262 <            // assert size == capacity || elements[dec(head, capacity)] == null;
1263 <            // assert size == capacity || elements[inc(tail(), capacity)] == null;
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 size=%d capacity=%d%n",
1266 <                              head, size, elements.length);
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;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines