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.109 by jsr166, Sat Nov 5 16:21:06 2016 UTC vs.
Revision 1.131 by jsr166, Wed Aug 23 22:41:49 2017 UTC

# 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/util/package-summary.html#CollectionsFramework">
54   * Java Collections Framework</a>.
55   *
56   * @author  Josh Bloch and Doug Lea
# Line 68 | Line 68 | public class ArrayDeque<E> extends Abstr
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.
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  
# Line 88 | Line 90 | public class ArrayDeque<E> extends Abstr
90  
91      /**
92       * The index at which the next element would be added to the tail
93 <     * of the deque (via addLast(E), add(E), or push(E)).
93 >     * of the deque (via addLast(E), add(E), or push(E));
94 >     * elements[tail] is always null.
95       */
96      transient int tail;
97  
# Line 114 | Line 117 | public class ArrayDeque<E> extends Abstr
117          if (jump < needed
118              || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
119              newCapacity = newCapacity(needed, jump);
120 <        elements = Arrays.copyOf(elements, newCapacity);
120 >        final Object[] es = elements = Arrays.copyOf(elements, newCapacity);
121          // Exceptionally, here tail == head needs to be disambiguated
122 <        if (tail < head || (tail == head && elements[head] != null)) {
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 187 | 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[Math.max(1, numElements + 1)];
193 >        elements =
194 >            new Object[(numElements < 1) ? 1 :
195 >                       (numElements == Integer.MAX_VALUE) ? Integer.MAX_VALUE :
196 >                       numElements + 1];
197      }
198  
199      /**
# Line 201 | 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 <        elements = new Object[c.size() + 1];
210 >        this(c.size());
211          addAll(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 215 | 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 224 | 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       * Subtracts j from i, mod modulus.
244 <     * Index i must be logically ahead of j.
245 <     * Returns the "circular distance" from j to i.
246 <     * Precondition and postcondition: 0 <= i < modulus, 0 <= j < modulus.
244 >     * Index i must be logically ahead of index j.
245 >     * Precondition: 0 <= i < modulus, 0 <= j < modulus.
246 >     * @return the "circular distance" from j to i; corner case i == j
247 >     * is disambiguated to "empty", returning 0.
248       */
249      static final int sub(int i, int j, int modulus) {
250          if ((i -= j) < 0) i += modulus;
# Line 305 | Line 313 | public class ArrayDeque<E> extends Abstr
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
309 <     * 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 314 | 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;
325 <        if ((needed = s + c.size() - elements.length + 1) > 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 >        c.forEach(this::addLast);
328          // checkInvariants();
329          return size() > s;
330      }
# Line 469 | Line 476 | public class ArrayDeque<E> extends Abstr
476              final Object[] es = elements;
477              for (int i = tail, end = head, to = (i >= end) ? end : 0;
478                   ; i = es.length, to = end) {
479 <                while (--i >= to)
479 >                for (i--; i > to - 1; i--)
480                      if (o.equals(es[i])) {
481                          delete(i);
482                          return true;
# Line 512 | Line 519 | public class ArrayDeque<E> extends Abstr
519      /**
520       * Retrieves and removes the head of the queue represented by this deque.
521       *
522 <     * This method differs from {@link #poll poll} only in that it throws an
523 <     * exception if this deque is empty.
522 >     * This method differs from {@link #poll() poll()} only in that it
523 >     * throws an exception if this deque is empty.
524       *
525       * <p>This method is equivalent to {@link #removeFirst}.
526       *
# Line 608 | Line 615 | public class ArrayDeque<E> extends Abstr
615          // checkInvariants();
616          final Object[] es = elements;
617          final int capacity = es.length;
618 <        final int h = head;
618 >        final int h, t;
619          // number of elements before to-be-deleted elt
620 <        final int front = sub(i, h, capacity);
621 <        final int back = size() - front - 1; // number of elements after
620 >        final int front = sub(i, h = head, capacity);
621 >        // number of elements after to-be-deleted elt
622 >        final int back = sub(t = tail, i, capacity) - 1;
623          if (front < back) {
624              // move front elements forwards
625              if (h <= i) {
# Line 627 | Line 635 | public class ArrayDeque<E> extends Abstr
635              return false;
636          } else {
637              // move back elements backwards
638 <            tail = dec(tail, capacity);
638 >            tail = dec(t, capacity);
639              if (i <= tail) {
640                  System.arraycopy(es, i + 1, es, i, back);
641              } else { // Wrap around
642 <                int firstLeg = capacity - (i + 1);
635 <                System.arraycopy(es, i + 1, es, i, firstLeg);
642 >                System.arraycopy(es, i + 1, es, i, capacity - (i + 1));
643                  es[capacity - 1] = es[0];
644 <                System.arraycopy(es, 1, es, 0, back - firstLeg - 1);
644 >                System.arraycopy(es, 1, es, 0, t - 1);
645              }
646              es[tail] = null;
647              // checkInvariants();
# Line 702 | Line 709 | public class ArrayDeque<E> extends Abstr
709                  throw new NoSuchElementException();
710              final Object[] es = elements;
711              E e = nonNullElementAt(es, cursor);
712 <            lastRet = cursor;
706 <            cursor = inc(cursor, es.length);
712 >            cursor = inc(lastRet = cursor, es.length);
713              remaining--;
714              return e;
715          }
# Line 751 | Line 757 | public class ArrayDeque<E> extends Abstr
757                  throw new NoSuchElementException();
758              final Object[] es = elements;
759              E e = nonNullElementAt(es, cursor);
760 <            lastRet = cursor;
755 <            cursor = dec(cursor, es.length);
760 >            cursor = dec(lastRet = cursor, es.length);
761              remaining--;
762              return e;
763          }
# Line 773 | Line 778 | public class ArrayDeque<E> extends Abstr
778                  throw new ConcurrentModificationException();
779              for (int i = cursor, end = head, to = (i >= end) ? end : 0;
780                   ; i = es.length - 1, to = end) {
781 <                for (; i >= to; i--)
781 >                // hotspot generates faster code than for: i >= to !
782 >                for (; i > to - 1; i--)
783                      action.accept(elementAt(es, i));
784                  if (to == end) {
785                      if (end != head)
786                          throw new ConcurrentModificationException();
787 <                    lastRet = head;
787 >                    lastRet = end;
788                      break;
789                  }
790              }
# Line 813 | Line 819 | public class ArrayDeque<E> extends Abstr
819  
820          /** Constructs spliterator over the given range. */
821          DeqSpliterator(int origin, int fence) {
822 +            // assert 0 <= origin && origin < elements.length;
823 +            // assert 0 <= fence && fence < elements.length;
824              this.cursor = origin;
825              this.fence = fence;
826          }
# Line 832 | Line 840 | public class ArrayDeque<E> extends Abstr
840              final int i, n;
841              return ((n = sub(getFence(), i = cursor, es.length) >> 1) <= 0)
842                  ? null
843 <                : new DeqSpliterator(i, cursor = add(i, n, es.length));
843 >                : new DeqSpliterator(i, cursor = inc(i, n, es.length));
844          }
845  
846          public void forEachRemaining(Consumer<? super E> action) {
# Line 855 | Line 863 | public class ArrayDeque<E> extends Abstr
863          }
864  
865          public boolean tryAdvance(Consumer<? super E> action) {
866 <            if (action == null)
867 <                throw new NullPointerException();
868 <            int t, i;
869 <            if ((t = fence) < 0) t = getFence();
870 <            if (t == (i = cursor))
866 >            Objects.requireNonNull(action);
867 >            final Object[] es = elements;
868 >            if (fence < 0) { fence = tail; cursor = head; } // late-binding
869 >            final int i;
870 >            if ((i = cursor) == fence)
871                  return false;
872 <            final Object[] es;
865 <            action.accept(nonNullElementAt(es = elements, i));
872 >            E e = nonNullElementAt(es, i);
873              cursor = inc(i, es.length);
874 +            action.accept(e);
875              return true;
876          }
877  
# Line 879 | Line 887 | public class ArrayDeque<E> extends Abstr
887          }
888      }
889  
890 +    /**
891 +     * @throws NullPointerException {@inheritDoc}
892 +     */
893      public void forEach(Consumer<? super E> action) {
894          Objects.requireNonNull(action);
895          final Object[] es = elements;
# Line 949 | Line 960 | public class ArrayDeque<E> extends Abstr
960               ; i = 0, to = end) {
961              for (; i < to; i++)
962                  if (filter.test(elementAt(es, i)))
963 <                    return bulkRemoveModified(filter, i, to);
963 >                    return bulkRemoveModified(filter, i);
964              if (to == end) {
965                  if (end != tail) throw new ConcurrentModificationException();
966                  break;
# Line 958 | Line 969 | public class ArrayDeque<E> extends Abstr
969          return false;
970      }
971  
972 +    // A tiny bit set implementation
973 +
974 +    private static long[] nBits(int n) {
975 +        return new long[((n - 1) >> 6) + 1];
976 +    }
977 +    private static void setBit(long[] bits, int i) {
978 +        bits[i >> 6] |= 1L << i;
979 +    }
980 +    private static boolean isClear(long[] bits, int i) {
981 +        return (bits[i >> 6] & (1L << i)) == 0;
982 +    }
983 +
984      /**
985       * Helper for bulkRemove, in case of at least one deletion.
986 <     * @param i valid index of first element to be deleted
986 >     * Tolerate predicates that reentrantly access the collection for
987 >     * read (but writers still get CME), so traverse once to find
988 >     * elements to delete, a second pass to physically expunge.
989 >     *
990 >     * @param beg valid index of first element to be deleted
991       */
992      private boolean bulkRemoveModified(
993 <        Predicate<? super E> filter, int i, int to) {
993 >        Predicate<? super E> filter, final int beg) {
994          final Object[] es = elements;
995          final int capacity = es.length;
969        // a two-finger algorithm, with hare i reading, tortoise j writing
970        int j = i++;
996          final int end = tail;
997 <        try {
998 <            for (;; j = 0) {    // j rejoins i on second leg
999 <                E e;
1000 <                // In this loop, i and j are on the same leg, with i > j
1001 <                for (; i < to; i++)
1002 <                    if (!filter.test(e = elementAt(es, i)))
1003 <                        es[j++] = e;
1004 <                if (to == end) break;
1005 <                // In this loop, j is on the first leg, i on the second
1006 <                for (i = 0, to = end; i < to && j < capacity; i++)
1007 <                    if (!filter.test(e = elementAt(es, i)))
1008 <                        es[j++] = e;
1009 <                if (i >= to) {
1010 <                    if (j == capacity) j = 0; // "corner" case
1011 <                    break;
1012 <                }
997 >        final long[] deathRow = nBits(sub(end, beg, capacity));
998 >        deathRow[0] = 1L;   // set bit 0
999 >        for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
1000 >             ; i = 0, to = end, k -= capacity) {
1001 >            for (; i < to; i++)
1002 >                if (filter.test(elementAt(es, i)))
1003 >                    setBit(deathRow, i - k);
1004 >            if (to == end) break;
1005 >        }
1006 >        // a two-finger traversal, with hare i reading, tortoise w writing
1007 >        int w = beg;
1008 >        for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
1009 >             ; w = 0) { // w rejoins i on second leg
1010 >            // In this loop, i and w are on the same leg, with i > w
1011 >            for (; i < to; i++)
1012 >                if (isClear(deathRow, i - k))
1013 >                    es[w++] = es[i];
1014 >            if (to == end) break;
1015 >            // In this loop, w is on the first leg, i on the second
1016 >            for (i = 0, to = end, k -= capacity; i < to && w < capacity; i++)
1017 >                if (isClear(deathRow, i - k))
1018 >                    es[w++] = es[i];
1019 >            if (i >= to) {
1020 >                if (w == capacity) w = 0; // "corner" case
1021 >                break;
1022              }
989            return true;
990        } catch (Throwable ex) {
991            // copy remaining elements
992            for (; i != end; i = inc(i, capacity), j = inc(j, capacity))
993                es[j] = es[i];
994            throw ex;
995        } finally {
996            if (end != tail) throw new ConcurrentModificationException();
997            circularClear(es, tail = j, end);
998            // checkInvariants();
1023          }
1024 +        if (end != tail) throw new ConcurrentModificationException();
1025 +        circularClear(es, tail = w, end);
1026 +        // checkInvariants();
1027 +        return true;
1028      }
1029  
1030      /**
# Line 1050 | Line 1078 | public class ArrayDeque<E> extends Abstr
1078  
1079      /**
1080       * Nulls out slots starting at array index i, upto index end.
1081 +     * Condition i == end means "empty" - nothing to do.
1082       */
1083      private static void circularClear(Object[] es, int i, int end) {
1084 +        // assert 0 <= i && i < es.length;
1085 +        // assert 0 <= end && end < es.length;
1086          for (int to = (i <= end) ? end : es.length;
1087               ; i = 0, to = end) {
1088 <            Arrays.fill(es, i, to, null);
1088 >            for (; i < to; i++) es[i] = null;
1089              if (to == end) break;
1090          }
1091      }
# Line 1079 | Line 1110 | public class ArrayDeque<E> extends Abstr
1110      private <T> T[] toArray(Class<T[]> klazz) {
1111          final Object[] es = elements;
1112          final T[] a;
1113 <        final int size = size(), head = this.head, end;
1114 <        final int len = Math.min(size, es.length - head);
1115 <        if ((end = head + size) >= 0) {
1113 >        final int head = this.head, tail = this.tail, end;
1114 >        if ((end = tail + ((head <= tail) ? 0 : es.length)) >= 0) {
1115 >            // Uses null extension feature of copyOfRange
1116              a = Arrays.copyOfRange(es, head, end, klazz);
1117          } else {
1118              // integer overflow!
1119 <            a = Arrays.copyOfRange(es, 0, size, klazz);
1120 <            System.arraycopy(es, head, a, 0, len);
1119 >            a = Arrays.copyOfRange(es, 0, end - head, klazz);
1120 >            System.arraycopy(es, head, a, 0, es.length - head);
1121          }
1122 <        if (tail < head)
1123 <            System.arraycopy(es, 0, a, len, tail);
1122 >        if (end != tail)
1123 >            System.arraycopy(es, 0, a, es.length - head, tail);
1124          return a;
1125      }
1126  
# Line 1214 | Line 1245 | public class ArrayDeque<E> extends Abstr
1245  
1246      /** debugging */
1247      void checkInvariants() {
1248 +        // Use head and tail fields with empty slot at tail strategy.
1249 +        // head == tail disambiguates to "empty".
1250          try {
1251              int capacity = elements.length;
1252 <            // assert head >= 0 && head < capacity;
1253 <            // assert tail >= 0 && tail < capacity;
1252 >            // assert 0 <= head && head < capacity;
1253 >            // assert 0 <= tail && tail < capacity;
1254              // assert capacity > 0;
1255              // assert size() < capacity;
1256              // assert head == tail || elements[head] != null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines