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.99 by jsr166, Sun Oct 30 16:32:40 2016 UTC vs.
Revision 1.135 by jsr166, Mon Oct 1 00:10:52 2018 UTC

# Line 9 | Line 9 | import java.io.Serializable;
9   import java.util.function.Consumer;
10   import java.util.function.Predicate;
11   import java.util.function.UnaryOperator;
12 + import jdk.internal.misc.SharedSecrets;
13  
14   /**
15   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 50 | Line 51 | import java.util.function.UnaryOperator;
51   * Iterator} interfaces.
52   *
53   * <p>This class is a member of the
54 < * <a href="{@docRoot}/../technotes/guides/collections/index.html">
54 > * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
55   * Java Collections Framework</a>.
56   *
57   * @author  Josh Bloch and Doug Lea
# Line 60 | Line 61 | import java.util.function.UnaryOperator;
61   public class ArrayDeque<E> extends AbstractCollection<E>
62                             implements Deque<E>, Cloneable, Serializable
63   {
64 +    /*
65 +     * VMs excel at optimizing simple array loops where indices are
66 +     * incrementing or decrementing over a valid slice, e.g.
67 +     *
68 +     * for (int i = start; i < end; i++) ... elements[i]
69 +     *
70 +     * Because in a circular array, elements are in general stored in
71 +     * two disjoint such slices, we help the VM by writing unusual
72 +     * nested loops for all traversals over the elements.  Having only
73 +     * one hot inner loop body instead of two or three eases human
74 +     * maintenance and encourages VM loop inlining into the caller.
75 +     */
76 +
77      /**
78       * The array in which the elements of the deque are stored.
79 <     * We guarantee that all array cells not holding deque elements
80 <     * are always null.
79 >     * All array cells not holding deque elements are always null.
80 >     * The array always has at least one null slot (at tail).
81       */
82      transient Object[] elements;
83  
84      /**
85       * The index of the element at the head of the deque (which is the
86       * element that would be removed by remove() or pop()); or an
87 <     * arbitrary number 0 <= head < elements.length if the deque is empty.
87 >     * arbitrary number 0 <= head < elements.length equal to tail if
88 >     * the deque is empty.
89       */
90      transient int head;
91  
92 <    /** Number of elements in this collection. */
93 <    transient int size;
92 >    /**
93 >     * The index at which the next element would be added to the tail
94 >     * of the deque (via addLast(E), add(E), or push(E));
95 >     * elements[tail] is always null.
96 >     */
97 >    transient int tail;
98  
99      /**
100       * The maximum size of array to allocate.
# Line 92 | Line 111 | public class ArrayDeque<E> extends Abstr
111       */
112      private void grow(int needed) {
113          // overflow-conscious code
95        // checkInvariants();
114          final int oldCapacity = elements.length;
115          int newCapacity;
116 <        // Double size if small; else grow by 50%
116 >        // Double capacity if small; else grow by 50%
117          int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
118          if (jump < needed
119              || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
120              newCapacity = newCapacity(needed, jump);
121 <        elements = Arrays.copyOf(elements, newCapacity);
122 <        if (oldCapacity - head < size) {
121 >        final Object[] es = elements = Arrays.copyOf(elements, newCapacity);
122 >        // Exceptionally, here tail == head needs to be disambiguated
123 >        if (tail < head || (tail == head && es[head] != null)) {
124              // wrap around; slide first leg forward to end of array
125              int newSpace = newCapacity - oldCapacity;
126 <            System.arraycopy(elements, head,
127 <                             elements, head + newSpace,
126 >            System.arraycopy(es, head,
127 >                             es, head + newSpace,
128                               oldCapacity - head);
129 <            Arrays.fill(elements, head, head + newSpace, null);
130 <            head += newSpace;
129 >            for (int i = head, to = (head += newSpace); i < to; i++)
130 >                es[i] = null;
131          }
132          // checkInvariants();
133      }
# Line 136 | Line 155 | public class ArrayDeque<E> extends Abstr
155       * @since TBD
156       */
157      /* public */ void ensureCapacity(int minCapacity) {
158 <        if (minCapacity > elements.length)
159 <            grow(minCapacity - elements.length);
158 >        int needed;
159 >        if ((needed = (minCapacity + 1 - elements.length)) > 0)
160 >            grow(needed);
161          // checkInvariants();
162      }
163  
# Line 147 | Line 167 | public class ArrayDeque<E> extends Abstr
167       * @since TBD
168       */
169      /* public */ void trimToSize() {
170 <        if (size < elements.length) {
171 <            elements = toArray();
170 >        int size;
171 >        if ((size = size()) + 1 < elements.length) {
172 >            elements = toArray(new Object[size + 1]);
173              head = 0;
174 +            tail = size;
175          }
176          // checkInvariants();
177      }
# Line 159 | Line 181 | public class ArrayDeque<E> extends Abstr
181       * sufficient to hold 16 elements.
182       */
183      public ArrayDeque() {
184 <        elements = new Object[16];
184 >        elements = new Object[16 + 1];
185      }
186  
187      /**
# Line 169 | Line 191 | public class ArrayDeque<E> extends Abstr
191       * @param numElements lower bound on initial capacity of the deque
192       */
193      public ArrayDeque(int numElements) {
194 <        elements = new Object[numElements];
194 >        elements =
195 >            new Object[(numElements < 1) ? 1 :
196 >                       (numElements == Integer.MAX_VALUE) ? Integer.MAX_VALUE :
197 >                       numElements + 1];
198      }
199  
200      /**
# Line 183 | Line 208 | public class ArrayDeque<E> extends Abstr
208       * @throws NullPointerException if the specified collection is null
209       */
210      public ArrayDeque(Collection<? extends E> c) {
211 <        Object[] es = c.toArray();
212 <        // 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;
211 >        this(c.size());
212 >        copyElements(c);
213      }
214  
215      /**
216 <     * Increments i, mod modulus.
216 >     * Circularly increments i, mod modulus.
217       * Precondition and postcondition: 0 <= i < modulus.
218       */
219      static final int inc(int i, int modulus) {
# Line 204 | Line 222 | public class ArrayDeque<E> extends Abstr
222      }
223  
224      /**
225 <     * Decrements i, mod modulus.
225 >     * Circularly decrements i, mod modulus.
226       * Precondition and postcondition: 0 <= i < modulus.
227       */
228      static final int dec(int i, int modulus) {
# Line 213 | Line 231 | public class ArrayDeque<E> extends Abstr
231      }
232  
233      /**
234 <     * Adds i and j, mod modulus.
235 <     * Precondition and postcondition: 0 <= i < modulus, 0 <= j <= modulus.
234 >     * Circularly adds the given distance to index i, mod modulus.
235 >     * Precondition: 0 <= i < modulus, 0 <= distance <= modulus.
236 >     * @return index 0 <= i < modulus
237       */
238 <    static final int add(int i, int j, int modulus) {
239 <        if ((i += j) - modulus >= 0) i -= modulus;
238 >    static final int inc(int i, int distance, int modulus) {
239 >        if ((i += distance) - modulus >= 0) i -= modulus;
240          return i;
241      }
242  
243      /**
244 <     * Returns the array index of the last element.
245 <     * May return invalid index -1 if there are no elements.
244 >     * Subtracts j from i, mod modulus.
245 >     * Index i must be logically ahead of index j.
246 >     * Precondition: 0 <= i < modulus, 0 <= j < modulus.
247 >     * @return the "circular distance" from j to i; corner case i == j
248 >     * is disambiguated to "empty", returning 0.
249       */
250 <    final int tail() {
251 <        return add(head, size - 1, elements.length);
250 >    static final int sub(int i, int j, int modulus) {
251 >        if ((i -= j) < 0) i += modulus;
252 >        return i;
253      }
254  
255      /**
256       * Returns element at array index i.
257 +     * This is a slight abuse of generics, accepted by javac.
258       */
259      @SuppressWarnings("unchecked")
260 <    private E elementAt(int i) {
261 <        return (E) elements[i];
260 >    static final <E> E elementAt(Object[] es, int i) {
261 >        return (E) es[i];
262      }
263  
264      /**
265       * A version of elementAt that checks for null elements.
266       * This check doesn't catch all possible comodifications,
267 <     * but does catch ones that corrupt traversal.  It's a little
244 <     * surprising that javac allows this abuse of generics.
267 >     * but does catch ones that corrupt traversal.
268       */
269      static final <E> E nonNullElementAt(Object[] es, int i) {
270          @SuppressWarnings("unchecked") E e = (E) es[i];
# Line 261 | Line 284 | public class ArrayDeque<E> extends Abstr
284       * @throws NullPointerException if the specified element is null
285       */
286      public void addFirst(E e) {
287 <        // checkInvariants();
288 <        Objects.requireNonNull(e);
289 <        Object[] es;
290 <        int capacity, h;
291 <        final int s;
269 <        if ((s = size) == (capacity = (es = elements).length)) {
287 >        if (e == null)
288 >            throw new NullPointerException();
289 >        final Object[] es = elements;
290 >        es[head = dec(head, es.length)] = e;
291 >        if (head == tail)
292              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;
293          // checkInvariants();
294      }
295  
# Line 285 | Line 302 | public class ArrayDeque<E> extends Abstr
302       * @throws NullPointerException if the specified element is null
303       */
304      public void addLast(E e) {
305 <        // checkInvariants();
306 <        Objects.requireNonNull(e);
307 <        Object[] es;
308 <        int capacity;
309 <        final int s;
293 <        if ((s = size) == (capacity = (es = elements).length)) {
305 >        if (e == null)
306 >            throw new NullPointerException();
307 >        final Object[] es = elements;
308 >        es[tail] = e;
309 >        if (head == (tail = inc(tail, es.length)))
310              grow(1);
295            capacity = (es = elements).length;
296        }
297        es[add(head, s, capacity)] = e;
298        size = s + 1;
311          // checkInvariants();
312      }
313  
314      /**
315       * Adds all of the elements in the specified collection at the end
316       * of this deque, as if by calling {@link #addLast} on each one,
317 <     * in the order that they are returned by the collection's
306 <     * iterator.
317 >     * in the order that they are returned by the collection's iterator.
318       *
319       * @param c the elements to be inserted into this deque
320       * @return {@code true} if this deque changed as a result of the call
# Line 311 | Line 322 | public class ArrayDeque<E> extends Abstr
322       *         of its elements are null
323       */
324      public boolean addAll(Collection<? extends E> c) {
325 <        final int s = size, needed = c.size() - (elements.length - s);
326 <        if (needed > 0)
325 >        final int s, needed;
326 >        if ((needed = (s = size()) + c.size() + 1 - elements.length) > 0)
327              grow(needed);
328 <        c.forEach((e) -> addLast(e));
328 >        copyElements(c);
329          // checkInvariants();
330 <        return size > s;
330 >        return size() > s;
331 >    }
332 >
333 >    private void copyElements(Collection<? extends E> c) {
334 >        c.forEach(this::addLast);
335      }
336  
337      /**
# Line 347 | Line 362 | public class ArrayDeque<E> extends Abstr
362       * @throws NoSuchElementException {@inheritDoc}
363       */
364      public E removeFirst() {
350        // checkInvariants();
365          E e = pollFirst();
366          if (e == null)
367              throw new NoSuchElementException();
368 +        // checkInvariants();
369          return e;
370      }
371  
# Line 358 | Line 373 | public class ArrayDeque<E> extends Abstr
373       * @throws NoSuchElementException {@inheritDoc}
374       */
375      public E removeLast() {
361        // checkInvariants();
376          E e = pollLast();
377          if (e == null)
378              throw new NoSuchElementException();
379 +        // checkInvariants();
380          return e;
381      }
382  
383      public E pollFirst() {
384 +        final Object[] es;
385 +        final int h;
386 +        E e = elementAt(es = elements, h = head);
387 +        if (e != null) {
388 +            es[h] = null;
389 +            head = inc(h, es.length);
390 +        }
391          // checkInvariants();
370        int s, h;
371        if ((s = size) <= 0)
372            return null;
373        final Object[] es = elements;
374        @SuppressWarnings("unchecked") E e = (E) es[h = head];
375        es[h] = null;
376        if (++h >= es.length) h = 0;
377        head = h;
378        size = s - 1;
392          return e;
393      }
394  
395      public E pollLast() {
396 +        final Object[] es;
397 +        final int t;
398 +        E e = elementAt(es = elements, t = dec(tail, es.length));
399 +        if (e != null)
400 +            es[tail = t] = null;
401          // checkInvariants();
384        final int s, tail;
385        if ((s = size) <= 0)
386            return null;
387        final Object[] es = elements;
388        @SuppressWarnings("unchecked")
389        E e = (E) es[tail = add(head, s - 1, es.length)];
390        es[tail] = null;
391        size = s - 1;
402          return e;
403      }
404  
# Line 396 | Line 406 | public class ArrayDeque<E> extends Abstr
406       * @throws NoSuchElementException {@inheritDoc}
407       */
408      public E getFirst() {
409 +        E e = elementAt(elements, head);
410 +        if (e == null)
411 +            throw new NoSuchElementException();
412          // checkInvariants();
413 <        if (size <= 0) throw new NoSuchElementException();
401 <        return elementAt(head);
413 >        return e;
414      }
415  
416      /**
417       * @throws NoSuchElementException {@inheritDoc}
418       */
407    @SuppressWarnings("unchecked")
419      public E getLast() {
409        // checkInvariants();
410        final int s;
411        if ((s = size) <= 0) throw new NoSuchElementException();
420          final Object[] es = elements;
421 <        return (E) es[add(head, s - 1, es.length)];
421 >        E e = elementAt(es, dec(tail, es.length));
422 >        if (e == null)
423 >            throw new NoSuchElementException();
424 >        // checkInvariants();
425 >        return e;
426      }
427  
428      public E peekFirst() {
429          // checkInvariants();
430 <        return (size <= 0) ? null : elementAt(head);
430 >        return elementAt(elements, head);
431      }
432  
421    @SuppressWarnings("unchecked")
433      public E peekLast() {
434          // checkInvariants();
435 <        final int s;
436 <        if ((s = size) <= 0) return null;
426 <        final Object[] es = elements;
427 <        return (E) es[add(head, s - 1, es.length)];
435 >        final Object[] es;
436 >        return elementAt(es = elements, dec(tail, es.length));
437      }
438  
439      /**
# Line 442 | Line 451 | public class ArrayDeque<E> extends Abstr
451      public boolean removeFirstOccurrence(Object o) {
452          if (o != null) {
453              final Object[] es = elements;
454 <            int i, end, to, todo;
455 <            todo = (end = (i = head) + size)
447 <                - (to = (es.length - end >= 0) ? end : es.length);
448 <            for (;; to = todo, i = 0, todo = 0) {
454 >            for (int i = head, end = tail, to = (i <= end) ? end : es.length;
455 >                 ; i = 0, to = end) {
456                  for (; i < to; i++)
457                      if (o.equals(es[i])) {
458                          delete(i);
459                          return true;
460                      }
461 <                if (todo == 0) break;
461 >                if (to == end) break;
462              }
463          }
464          return false;
# Line 472 | Line 479 | public class ArrayDeque<E> extends Abstr
479      public boolean removeLastOccurrence(Object o) {
480          if (o != null) {
481              final Object[] es = elements;
482 <            int i, to, end, todo;
483 <            todo = (to = ((end = (i = tail()) - size) >= -1) ? end : -1) - end;
484 <            for (;; to = (i = es.length - 1) - todo, todo = 0) {
478 <                for (; i > to; i--)
482 >            for (int i = tail, end = head, to = (i >= end) ? end : 0;
483 >                 ; i = es.length, to = end) {
484 >                for (i--; i > to - 1; i--)
485                      if (o.equals(es[i])) {
486                          delete(i);
487                          return true;
488                      }
489 <                if (todo == 0) break;
489 >                if (to == end) break;
490              }
491          }
492          return false;
# Line 518 | Line 524 | public class ArrayDeque<E> extends Abstr
524      /**
525       * Retrieves and removes the head of the queue represented by this deque.
526       *
527 <     * This method differs from {@link #poll poll} only in that it throws an
528 <     * exception if this deque is empty.
527 >     * This method differs from {@link #poll() poll()} only in that it
528 >     * throws an exception if this deque is empty.
529       *
530       * <p>This method is equivalent to {@link #removeFirst}.
531       *
# Line 608 | Line 614 | public class ArrayDeque<E> extends Abstr
614       * <p>This method is called delete rather than remove to emphasize
615       * that its semantics differ from those of {@link List#remove(int)}.
616       *
617 <     * @return true if elements moved backwards
617 >     * @return true if elements near tail moved backwards
618       */
619      boolean delete(int i) {
620          // checkInvariants();
621          final Object[] es = elements;
622          final int capacity = es.length;
623 <        final int h = head;
624 <        int front;              // number of elements before to-be-deleted elt
625 <        if ((front = i - h) < 0) front += capacity;
626 <        final int back = size - front - 1; // number of elements after
623 >        final int h, t;
624 >        // number of elements before to-be-deleted elt
625 >        final int front = sub(i, h = head, capacity);
626 >        // number of elements after to-be-deleted elt
627 >        final int back = sub(t = tail, i, capacity) - 1;
628          if (front < back) {
629              // move front elements forwards
630              if (h <= i) {
# Line 628 | Line 635 | public class ArrayDeque<E> extends Abstr
635                  System.arraycopy(es, h, es, h + 1, front - (i + 1));
636              }
637              es[h] = null;
638 <            if ((head = (h + 1)) >= capacity) head = 0;
632 <            size--;
638 >            head = inc(h, capacity);
639              // checkInvariants();
640              return false;
641          } else {
642              // move back elements backwards
643 <            int tail = tail();
643 >            tail = dec(t, capacity);
644              if (i <= tail) {
645                  System.arraycopy(es, i + 1, es, i, back);
646              } else { // Wrap around
647 <                int firstLeg = capacity - (i + 1);
642 <                System.arraycopy(es, i + 1, es, i, firstLeg);
647 >                System.arraycopy(es, i + 1, es, i, capacity - (i + 1));
648                  es[capacity - 1] = es[0];
649 <                System.arraycopy(es, 1, es, 0, back - firstLeg - 1);
649 >                System.arraycopy(es, 1, es, 0, t - 1);
650              }
651              es[tail] = null;
647            size--;
652              // checkInvariants();
653              return true;
654          }
# Line 658 | Line 662 | public class ArrayDeque<E> extends Abstr
662       * @return the number of elements in this deque
663       */
664      public int size() {
665 <        return size;
665 >        return sub(tail, head, elements.length);
666      }
667  
668      /**
# Line 667 | Line 671 | public class ArrayDeque<E> extends Abstr
671       * @return {@code true} if this deque contains no elements
672       */
673      public boolean isEmpty() {
674 <        return size == 0;
674 >        return head == tail;
675      }
676  
677      /**
# Line 691 | Line 695 | public class ArrayDeque<E> extends Abstr
695          int cursor;
696  
697          /** Number of elements yet to be returned. */
698 <        int remaining = size;
698 >        int remaining = size();
699  
700          /**
701           * Index of element returned by most recent call to next.
# Line 710 | Line 714 | public class ArrayDeque<E> extends Abstr
714                  throw new NoSuchElementException();
715              final Object[] es = elements;
716              E e = nonNullElementAt(es, cursor);
717 <            lastRet = cursor;
714 <            if (++cursor >= es.length) cursor = 0;
717 >            cursor = inc(lastRet = cursor, es.length);
718              remaining--;
719              return e;
720          }
721  
722          void postDelete(boolean leftShifted) {
723              if (leftShifted)
724 <                if (--cursor < 0) cursor = elements.length - 1;
724 >                cursor = dec(cursor, elements.length);
725          }
726  
727          public final void remove() {
# Line 730 | Line 733 | public class ArrayDeque<E> extends Abstr
733  
734          public void forEachRemaining(Consumer<? super E> action) {
735              Objects.requireNonNull(action);
736 <            final int k;
737 <            if ((k = remaining) > 0) {
738 <                remaining = 0;
739 <                ArrayDeque.forEachRemaining(action, elements, cursor, k);
740 <                if ((lastRet = cursor + k - 1) >= elements.length)
741 <                    lastRet -= elements.length;
736 >            int r;
737 >            if ((r = remaining) <= 0)
738 >                return;
739 >            remaining = 0;
740 >            final Object[] es = elements;
741 >            if (es[cursor] == null || sub(tail, cursor, es.length) != r)
742 >                throw new ConcurrentModificationException();
743 >            for (int i = cursor, end = tail, to = (i <= end) ? end : es.length;
744 >                 ; i = 0, to = end) {
745 >                for (; i < to; i++)
746 >                    action.accept(elementAt(es, i));
747 >                if (to == end) {
748 >                    if (end != tail)
749 >                        throw new ConcurrentModificationException();
750 >                    lastRet = dec(end, es.length);
751 >                    break;
752 >                }
753              }
754          }
755      }
756  
757      private class DescendingIterator extends DeqIterator {
758 <        DescendingIterator() { cursor = tail(); }
758 >        DescendingIterator() { cursor = dec(tail, elements.length); }
759  
760          public final E next() {
761              if (remaining <= 0)
762                  throw new NoSuchElementException();
763              final Object[] es = elements;
764              E e = nonNullElementAt(es, cursor);
765 <            lastRet = cursor;
752 <            if (--cursor < 0) cursor = es.length - 1;
765 >            cursor = dec(lastRet = cursor, es.length);
766              remaining--;
767              return e;
768          }
769  
770          void postDelete(boolean leftShifted) {
771              if (!leftShifted)
772 <                if (++cursor >= elements.length) cursor = 0;
772 >                cursor = inc(cursor, elements.length);
773          }
774  
775          public final void forEachRemaining(Consumer<? super E> action) {
776              Objects.requireNonNull(action);
777 <            final int k;
778 <            if ((k = remaining) > 0) {
779 <                remaining = 0;
780 <                final Object[] es = elements;
781 <                int i, end, to, todo;
782 <                todo = (to = ((end = (i = cursor) - k) >= -1) ? end : -1) - end;
783 <                for (;; to = (i = es.length - 1) - todo, todo = 0) {
784 <                    for (; i > to; i--)
785 <                        action.accept(nonNullElementAt(es, i));
786 <                    if (todo == 0) break;
777 >            int r;
778 >            if ((r = remaining) <= 0)
779 >                return;
780 >            remaining = 0;
781 >            final Object[] es = elements;
782 >            if (es[cursor] == null || sub(cursor, head, es.length) + 1 != r)
783 >                throw new ConcurrentModificationException();
784 >            for (int i = cursor, end = head, to = (i >= end) ? end : 0;
785 >                 ; i = es.length - 1, to = end) {
786 >                // hotspot generates faster code than for: i >= to !
787 >                for (; i > to - 1; i--)
788 >                    action.accept(elementAt(es, i));
789 >                if (to == end) {
790 >                    if (end != head)
791 >                        throw new ConcurrentModificationException();
792 >                    lastRet = end;
793 >                    break;
794                  }
775                if ((lastRet = cursor - (k - 1)) < 0)
776                    lastRet += es.length;
795              }
796          }
797      }
# Line 792 | Line 810 | public class ArrayDeque<E> extends Abstr
810       * @since 1.8
811       */
812      public Spliterator<E> spliterator() {
813 <        return new ArrayDequeSpliterator();
813 >        return new DeqSpliterator();
814      }
815  
816 <    final class ArrayDequeSpliterator implements Spliterator<E> {
817 <        private int cursor;
818 <        private int remaining; // -1 until late-binding first use
816 >    final class DeqSpliterator implements Spliterator<E> {
817 >        private int fence;      // -1 until first use
818 >        private int cursor;     // current index, modified on traverse/split
819  
820          /** Constructs late-binding spliterator over all elements. */
821 <        ArrayDequeSpliterator() {
822 <            this.remaining = -1;
821 >        DeqSpliterator() {
822 >            this.fence = -1;
823          }
824  
825 <        /** Constructs spliterator over the given slice. */
826 <        ArrayDequeSpliterator(int cursor, int count) {
827 <            this.cursor = cursor;
828 <            this.remaining = count;
829 <        }
830 <
831 <        /** Ensures late-binding initialization; then returns remaining. */
832 <        private int remaining() {
833 <            if (remaining < 0) {
825 >        /** Constructs spliterator over the given range. */
826 >        DeqSpliterator(int origin, int fence) {
827 >            // assert 0 <= origin && origin < elements.length;
828 >            // assert 0 <= fence && fence < elements.length;
829 >            this.cursor = origin;
830 >            this.fence = fence;
831 >        }
832 >
833 >        /** Ensures late-binding initialization; then returns fence. */
834 >        private int getFence() { // force initialization
835 >            int t;
836 >            if ((t = fence) < 0) {
837 >                t = fence = tail;
838                  cursor = head;
817                remaining = size;
839              }
840 <            return remaining;
840 >            return t;
841          }
842  
843 <        public ArrayDequeSpliterator trySplit() {
844 <            final int mid;
845 <            if ((mid = remaining() >> 1) > 0) {
846 <                int oldCursor = cursor;
847 <                cursor = add(cursor, mid, elements.length);
848 <                remaining -= mid;
828 <                return new ArrayDequeSpliterator(oldCursor, mid);
829 <            }
830 <            return null;
843 >        public DeqSpliterator trySplit() {
844 >            final Object[] es = elements;
845 >            final int i, n;
846 >            return ((n = sub(getFence(), i = cursor, es.length) >> 1) <= 0)
847 >                ? null
848 >                : new DeqSpliterator(i, cursor = inc(i, n, es.length));
849          }
850  
851          public void forEachRemaining(Consumer<? super E> action) {
852 <            Objects.requireNonNull(action);
853 <            final int k = remaining(); // side effect!
854 <            remaining = 0;
855 <            ArrayDeque.forEachRemaining(action, elements, cursor, k);
852 >            if (action == null)
853 >                throw new NullPointerException();
854 >            final int end = getFence(), cursor = this.cursor;
855 >            final Object[] es = elements;
856 >            if (cursor != end) {
857 >                this.cursor = end;
858 >                // null check at both ends of range is sufficient
859 >                if (es[cursor] == null || es[dec(end, es.length)] == null)
860 >                    throw new ConcurrentModificationException();
861 >                for (int i = cursor, to = (i <= end) ? end : es.length;
862 >                     ; i = 0, to = end) {
863 >                    for (; i < to; i++)
864 >                        action.accept(elementAt(es, i));
865 >                    if (to == end) break;
866 >                }
867 >            }
868          }
869  
870          public boolean tryAdvance(Consumer<? super E> action) {
871              Objects.requireNonNull(action);
872 <            final int k;
873 <            if ((k = remaining()) <= 0)
872 >            final Object[] es = elements;
873 >            if (fence < 0) { fence = tail; cursor = head; } // late-binding
874 >            final int i;
875 >            if ((i = cursor) == fence)
876                  return false;
877 <            action.accept(nonNullElementAt(elements, cursor));
878 <            if (++cursor >= elements.length) cursor = 0;
879 <            remaining = k - 1;
877 >            E e = nonNullElementAt(es, i);
878 >            cursor = inc(i, es.length);
879 >            action.accept(e);
880              return true;
881          }
882  
883          public long estimateSize() {
884 <            return remaining();
884 >            return sub(getFence(), cursor, elements.length);
885          }
886  
887          public int characteristics() {
# Line 860 | Line 892 | public class ArrayDeque<E> extends Abstr
892          }
893      }
894  
895 <    @SuppressWarnings("unchecked")
895 >    /**
896 >     * @throws NullPointerException {@inheritDoc}
897 >     */
898      public void forEach(Consumer<? super E> action) {
899          Objects.requireNonNull(action);
900          final Object[] es = elements;
901 <        int i, end, to, todo;
902 <        todo = (end = (i = head) + size)
869 <            - (to = (es.length - end >= 0) ? end : es.length);
870 <        for (;; to = todo, i = 0, todo = 0) {
901 >        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
902 >             ; i = 0, to = end) {
903              for (; i < to; i++)
904 <                action.accept((E) es[i]);
905 <            if (todo == 0) break;
904 >                action.accept(elementAt(es, i));
905 >            if (to == end) {
906 >                if (end != tail) throw new ConcurrentModificationException();
907 >                break;
908 >            }
909          }
910          // checkInvariants();
911      }
912  
913      /**
879     * Calls action on remaining elements, starting at index i and
880     * traversing in ascending order.  A variant of forEach that also
881     * checks for concurrent modification, for use in iterators.
882     */
883    static <E> void forEachRemaining(
884        Consumer<? super E> action, Object[] es, int i, int remaining) {
885        int end, to, todo;
886        todo = (end = i + remaining)
887            - (to = (es.length - end >= 0) ? end : es.length);
888        for (;; to = todo, i = 0, todo = 0) {
889            for (; i < to; i++)
890                action.accept(nonNullElementAt(es, i));
891            if (todo == 0) break;
892        }
893    }
894
895    /**
914       * Replaces each element of this deque with the result of applying the
915       * operator to that element, as specified by {@link List#replaceAll}.
916       *
917       * @param operator the operator to apply to each element
918       * @since TBD
919       */
902    @SuppressWarnings("unchecked")
920      /* public */ void replaceAll(UnaryOperator<E> operator) {
921          Objects.requireNonNull(operator);
922          final Object[] es = elements;
923 <        int i, end, to, todo;
924 <        todo = (end = (i = head) + size)
908 <            - (to = (es.length - end >= 0) ? end : es.length);
909 <        for (;; to = todo, i = 0, todo = 0) {
923 >        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
924 >             ; i = 0, to = end) {
925              for (; i < to; i++)
926 <                es[i] = operator.apply((E) es[i]);
927 <            if (todo == 0) break;
926 >                es[i] = operator.apply(elementAt(es, i));
927 >            if (to == end) {
928 >                if (end != tail) throw new ConcurrentModificationException();
929 >                break;
930 >            }
931          }
932          // checkInvariants();
933      }
# Line 942 | Line 960 | public class ArrayDeque<E> extends Abstr
960      private boolean bulkRemove(Predicate<? super E> filter) {
961          // checkInvariants();
962          final Object[] es = elements;
963 +        // Optimize for initial run of survivors
964 +        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
965 +             ; i = 0, to = end) {
966 +            for (; i < to; i++)
967 +                if (filter.test(elementAt(es, i)))
968 +                    return bulkRemoveModified(filter, i);
969 +            if (to == end) {
970 +                if (end != tail) throw new ConcurrentModificationException();
971 +                break;
972 +            }
973 +        }
974 +        return false;
975 +    }
976 +
977 +    // A tiny bit set implementation
978 +
979 +    private static long[] nBits(int n) {
980 +        return new long[((n - 1) >> 6) + 1];
981 +    }
982 +    private static void setBit(long[] bits, int i) {
983 +        bits[i >> 6] |= 1L << i;
984 +    }
985 +    private static boolean isClear(long[] bits, int i) {
986 +        return (bits[i >> 6] & (1L << i)) == 0;
987 +    }
988 +
989 +    /**
990 +     * Helper for bulkRemove, in case of at least one deletion.
991 +     * Tolerate predicates that reentrantly access the collection for
992 +     * read (but writers still get CME), so traverse once to find
993 +     * elements to delete, a second pass to physically expunge.
994 +     *
995 +     * @param beg valid index of first element to be deleted
996 +     */
997 +    private boolean bulkRemoveModified(
998 +        Predicate<? super E> filter, final int beg) {
999 +        final Object[] es = elements;
1000          final int capacity = es.length;
1001 <        int i = head, j = i, remaining = size, deleted = 0;
1002 <        try {
1003 <            for (; remaining > 0; remaining--) {
1004 <                @SuppressWarnings("unchecked") E e = (E) es[i];
1005 <                if (filter.test(e))
1006 <                    deleted++;
1007 <                else {
1008 <                    if (j != i)
1009 <                        es[j] = e;
1010 <                    if (++j >= capacity) j = 0;
1011 <                }
1012 <                if (++i >= capacity) i = 0;
1001 >        final int end = tail;
1002 >        final long[] deathRow = nBits(sub(end, beg, capacity));
1003 >        deathRow[0] = 1L;   // set bit 0
1004 >        for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
1005 >             ; i = 0, to = end, k -= capacity) {
1006 >            for (; i < to; i++)
1007 >                if (filter.test(elementAt(es, i)))
1008 >                    setBit(deathRow, i - k);
1009 >            if (to == end) break;
1010 >        }
1011 >        // a two-finger traversal, with hare i reading, tortoise w writing
1012 >        int w = beg;
1013 >        for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
1014 >             ; w = 0) { // w rejoins i on second leg
1015 >            // In this loop, i and w are on the same leg, with i > w
1016 >            for (; i < to; i++)
1017 >                if (isClear(deathRow, i - k))
1018 >                    es[w++] = es[i];
1019 >            if (to == end) break;
1020 >            // In this loop, w is on the first leg, i on the second
1021 >            for (i = 0, to = end, k -= capacity; i < to && w < capacity; i++)
1022 >                if (isClear(deathRow, i - k))
1023 >                    es[w++] = es[i];
1024 >            if (i >= to) {
1025 >                if (w == capacity) w = 0; // "corner" case
1026 >                break;
1027              }
959            return deleted > 0;
960        } catch (Throwable ex) {
961            if (deleted > 0)
962                for (; remaining > 0; remaining--) {
963                    es[j] = es[i];
964                    if (++i >= capacity) i = 0;
965                    if (++j >= capacity) j = 0;
966                }
967            throw ex;
968        } finally {
969            size -= deleted;
970            clearSlice(es, j, deleted);
971            // checkInvariants();
1028          }
1029 +        if (end != tail) throw new ConcurrentModificationException();
1030 +        circularClear(es, tail = w, end);
1031 +        // checkInvariants();
1032 +        return true;
1033      }
1034  
1035      /**
# Line 983 | Line 1043 | public class ArrayDeque<E> extends Abstr
1043      public boolean contains(Object o) {
1044          if (o != null) {
1045              final Object[] es = elements;
1046 <            int i, end, to, todo;
1047 <            todo = (end = (i = head) + size)
988 <                - (to = (es.length - end >= 0) ? end : es.length);
989 <            for (;; to = todo, i = 0, todo = 0) {
1046 >            for (int i = head, end = tail, to = (i <= end) ? end : es.length;
1047 >                 ; i = 0, to = end) {
1048                  for (; i < to; i++)
1049                      if (o.equals(es[i]))
1050                          return true;
1051 <                if (todo == 0) break;
1051 >                if (to == end) break;
1052              }
1053          }
1054          return false;
# Line 1018 | Line 1076 | public class ArrayDeque<E> extends Abstr
1076       * The deque will be empty after this call returns.
1077       */
1078      public void clear() {
1079 <        clearSlice(elements, head, size);
1080 <        size = head = 0;
1079 >        circularClear(elements, head, tail);
1080 >        head = tail = 0;
1081          // checkInvariants();
1082      }
1083  
1084      /**
1085 <     * Nulls out count elements, starting at array index i.
1085 >     * Nulls out slots starting at array index i, upto index end.
1086 >     * Condition i == end means "empty" - nothing to do.
1087       */
1088 <    private static void clearSlice(Object[] es, int i, int count) {
1089 <        int end, to, todo;
1090 <        todo = (end = i + count)
1091 <            - (to = (es.length - end >= 0) ? end : es.length);
1092 <        for (;; to = todo, i = 0, todo = 0) {
1093 <            Arrays.fill(es, i, to, null);
1094 <            if (todo == 0) break;
1088 >    private static void circularClear(Object[] es, int i, int end) {
1089 >        // assert 0 <= i && i < es.length;
1090 >        // assert 0 <= end && end < es.length;
1091 >        for (int to = (i <= end) ? end : es.length;
1092 >             ; i = 0, to = end) {
1093 >            for (; i < to; i++) es[i] = null;
1094 >            if (to == end) break;
1095          }
1096      }
1097  
# Line 1055 | Line 1114 | public class ArrayDeque<E> extends Abstr
1114  
1115      private <T> T[] toArray(Class<T[]> klazz) {
1116          final Object[] es = elements;
1058        final int capacity = es.length;
1059        final int head = this.head, end = head + size;
1117          final T[] a;
1118 <        if (end >= 0) {
1118 >        final int head = this.head, tail = this.tail, end;
1119 >        if ((end = tail + ((head <= tail) ? 0 : es.length)) >= 0) {
1120 >            // Uses null extension feature of copyOfRange
1121              a = Arrays.copyOfRange(es, head, end, klazz);
1122          } else {
1123              // integer overflow!
1124 <            a = Arrays.copyOfRange(es, 0, size, klazz);
1125 <            System.arraycopy(es, head, a, 0, capacity - head);
1124 >            a = Arrays.copyOfRange(es, 0, end - head, klazz);
1125 >            System.arraycopy(es, head, a, 0, es.length - head);
1126          }
1127 <        if (end - capacity > 0)
1128 <            System.arraycopy(es, 0, a, capacity - head, end - capacity);
1127 >        if (end != tail)
1128 >            System.arraycopy(es, 0, a, es.length - head, tail);
1129          return a;
1130      }
1131  
# Line 1109 | Line 1168 | public class ArrayDeque<E> extends Abstr
1168      @SuppressWarnings("unchecked")
1169      public <T> T[] toArray(T[] a) {
1170          final int size;
1171 <        if ((size = this.size) > a.length)
1171 >        if ((size = size()) > a.length)
1172              return toArray((Class<T[]>) a.getClass());
1173          final Object[] es = elements;
1174 <        final int head = this.head, end = head + size;
1175 <        final int front = (es.length - end >= 0) ? size : es.length - head;
1176 <        System.arraycopy(es, head, a, 0, front);
1177 <        if (front < size)
1178 <            System.arraycopy(es, 0, a, front, size - front);
1174 >        for (int i = head, j = 0, len = Math.min(size, es.length - i);
1175 >             ; i = 0, len = tail) {
1176 >            System.arraycopy(es, i, a, j, len);
1177 >            if ((j += len) == size) break;
1178 >        }
1179          if (size < a.length)
1180              a[size] = null;
1181          return a;
# Line 1156 | Line 1215 | public class ArrayDeque<E> extends Abstr
1215          s.defaultWriteObject();
1216  
1217          // Write out size
1218 <        s.writeInt(size);
1218 >        s.writeInt(size());
1219  
1220          // Write out elements in order.
1221          final Object[] es = elements;
1222 <        int i, end, to, todo;
1223 <        todo = (end = (i = head) + size)
1165 <            - (to = (es.length - end >= 0) ? end : es.length);
1166 <        for (;; to = todo, i = 0, todo = 0) {
1222 >        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
1223 >             ; i = 0, to = end) {
1224              for (; i < to; i++)
1225                  s.writeObject(es[i]);
1226 <            if (todo == 0) break;
1226 >            if (to == end) break;
1227          }
1228      }
1229  
# Line 1182 | Line 1239 | public class ArrayDeque<E> extends Abstr
1239          s.defaultReadObject();
1240  
1241          // Read in size and allocate array
1242 <        elements = new Object[size = s.readInt()];
1242 >        int size = s.readInt();
1243 >        SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size + 1);
1244 >        elements = new Object[size + 1];
1245 >        this.tail = size;
1246  
1247          // Read in all elements in the proper order.
1248          for (int i = 0; i < size; i++)
# Line 1191 | Line 1251 | public class ArrayDeque<E> extends Abstr
1251  
1252      /** debugging */
1253      void checkInvariants() {
1254 +        // Use head and tail fields with empty slot at tail strategy.
1255 +        // head == tail disambiguates to "empty".
1256          try {
1257              int capacity = elements.length;
1258 <            // assert size >= 0 && size <= capacity;
1259 <            // assert head >= 0;
1260 <            // assert capacity == 0 || head < capacity;
1261 <            // assert size == 0 || elements[head] != null;
1262 <            // assert size == 0 || elements[tail()] != null;
1263 <            // assert size == capacity || elements[dec(head, capacity)] == null;
1264 <            // assert size == capacity || elements[inc(tail(), capacity)] == null;
1258 >            // assert 0 <= head && head < capacity;
1259 >            // assert 0 <= tail && tail < capacity;
1260 >            // assert capacity > 0;
1261 >            // assert size() < capacity;
1262 >            // assert head == tail || elements[head] != null;
1263 >            // assert elements[tail] == null;
1264 >            // assert head == tail || elements[dec(tail, capacity)] != null;
1265          } catch (Throwable t) {
1266 <            System.err.printf("head=%d size=%d capacity=%d%n",
1267 <                              head, size, elements.length);
1266 >            System.err.printf("head=%d tail=%d capacity=%d%n",
1267 >                              head, tail, elements.length);
1268              System.err.printf("elements=%s%n",
1269                                Arrays.toString(elements));
1270              throw t;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines