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.119 by jsr166, Sun Nov 20 08:30:56 2016 UTC

# 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 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  
# 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 add(int i, int distance, int modulus) {
238 >        if ((i += distance) - modulus >= 0) distance -= 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 diambiguated to "empty", returning 0.
248       */
249      static final int sub(int i, int j, int modulus) {
250          if ((i -= j) < 0) i += modulus;
# Line 314 | 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;
326 <        if ((needed = s + c.size() - elements.length + 1) > 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 >        c.forEach(this::addLast);
329          // checkInvariants();
330          return size() > s;
331      }
# Line 469 | Line 477 | public class ArrayDeque<E> extends Abstr
477              final Object[] es = elements;
478              for (int i = tail, end = head, to = (i >= end) ? end : 0;
479                   ; i = es.length, to = end) {
480 <                while (--i >= to)
480 >                for (i--; i > to - 1; i--)
481                      if (o.equals(es[i])) {
482                          delete(i);
483                          return true;
# Line 608 | Line 616 | public class ArrayDeque<E> extends Abstr
616          // checkInvariants();
617          final Object[] es = elements;
618          final int capacity = es.length;
619 <        final int h = head;
619 >        final int h, t;
620          // number of elements before to-be-deleted elt
621 <        final int front = sub(i, h, capacity);
622 <        final int back = size() - front - 1; // number of elements after
621 >        final int front = sub(i, h = head, capacity);
622 >        // number of elements after to-be-deleted elt
623 >        final int back = sub(t = tail, i, capacity) - 1;
624          if (front < back) {
625              // move front elements forwards
626              if (h <= i) {
# Line 627 | Line 636 | public class ArrayDeque<E> extends Abstr
636              return false;
637          } else {
638              // move back elements backwards
639 <            tail = dec(tail, capacity);
639 >            tail = dec(t, capacity);
640              if (i <= tail) {
641                  System.arraycopy(es, i + 1, es, i, back);
642              } else { // Wrap around
643 <                int firstLeg = capacity - (i + 1);
635 <                System.arraycopy(es, i + 1, es, i, firstLeg);
643 >                System.arraycopy(es, i + 1, es, i, capacity - (i + 1));
644                  es[capacity - 1] = es[0];
645 <                System.arraycopy(es, 1, es, 0, back - firstLeg - 1);
645 >                System.arraycopy(es, 1, es, 0, t - 1);
646              }
647              es[tail] = null;
648              // checkInvariants();
# Line 773 | Line 781 | public class ArrayDeque<E> extends Abstr
781                  throw new ConcurrentModificationException();
782              for (int i = cursor, end = head, to = (i >= end) ? end : 0;
783                   ; i = es.length - 1, to = end) {
784 <                for (; i >= to; i--)
784 >                // hotspot generates faster code than for: i >= to !
785 >                for (; i > to - 1; i--)
786                      action.accept(elementAt(es, i));
787                  if (to == end) {
788                      if (end != head)
789                          throw new ConcurrentModificationException();
790 <                    lastRet = head;
790 >                    lastRet = end;
791                      break;
792                  }
793              }
# Line 857 | Line 866 | public class ArrayDeque<E> extends Abstr
866          public boolean tryAdvance(Consumer<? super E> action) {
867              if (action == null)
868                  throw new NullPointerException();
869 <            int t, i;
870 <            if ((t = fence) < 0) t = getFence();
862 <            if (t == (i = cursor))
869 >            final int t, i;
870 >            if ((t = getFence()) == (i = cursor))
871                  return false;
872 <            final Object[] es;
865 <            action.accept(nonNullElementAt(es = elements, i));
872 >            final Object[] es = elements;
873              cursor = inc(i, es.length);
874 +            action.accept(nonNullElementAt(es, i));
875              return true;
876          }
877  
# Line 949 | Line 957 | public class ArrayDeque<E> extends Abstr
957               ; i = 0, to = end) {
958              for (; i < to; i++)
959                  if (filter.test(elementAt(es, i)))
960 <                    return bulkRemoveModified(filter, i, to);
960 >                    return bulkRemoveModified(filter, i);
961              if (to == end) {
962                  if (end != tail) throw new ConcurrentModificationException();
963                  break;
# Line 958 | Line 966 | public class ArrayDeque<E> extends Abstr
966          return false;
967      }
968  
969 +    // A tiny bit set implementation
970 +
971 +    private static long[] nBits(int n) {
972 +        return new long[((n - 1) >> 6) + 1];
973 +    }
974 +    private static void setBit(long[] bits, int i) {
975 +        bits[i >> 6] |= 1L << i;
976 +    }
977 +    private static boolean isClear(long[] bits, int i) {
978 +        return (bits[i >> 6] & (1L << i)) == 0;
979 +    }
980 +
981      /**
982       * Helper for bulkRemove, in case of at least one deletion.
983 <     * @param i valid index of first element to be deleted
983 >     * Tolerate predicates that reentrantly access the collection for
984 >     * read (but writers still get CME), so traverse once to find
985 >     * elements to delete, a second pass to physically expunge.
986 >     *
987 >     * @param beg valid index of first element to be deleted
988       */
989      private boolean bulkRemoveModified(
990 <        Predicate<? super E> filter, int i, int to) {
990 >        Predicate<? super E> filter, final int beg) {
991          final Object[] es = elements;
992          final int capacity = es.length;
969        // a two-finger algorithm, with hare i reading, tortoise j writing
970        int j = i++;
993          final int end = tail;
994 <        try {
995 <            for (;; j = 0) {    // j rejoins i on second leg
996 <                E e;
997 <                // In this loop, i and j are on the same leg, with i > j
998 <                for (; i < to; i++)
999 <                    if (!filter.test(e = elementAt(es, i)))
1000 <                        es[j++] = e;
1001 <                if (to == end) break;
1002 <                // In this loop, j is on the first leg, i on the second
1003 <                for (i = 0, to = end; i < to && j < capacity; i++)
1004 <                    if (!filter.test(e = elementAt(es, i)))
1005 <                        es[j++] = e;
1006 <                if (i >= to) {
1007 <                    if (j == capacity) j = 0; // "corner" case
1008 <                    break;
1009 <                }
994 >        final long[] deathRow = nBits(sub(end, beg, capacity));
995 >        deathRow[0] = 1L;   // set bit 0
996 >        for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
997 >             ; i = 0, to = end, k -= capacity) {
998 >            for (; i < to; i++)
999 >                if (filter.test(elementAt(es, i)))
1000 >                    setBit(deathRow, i - k);
1001 >            if (to == end) break;
1002 >        }
1003 >        // a two-finger traversal, with hare i reading, tortoise w writing
1004 >        int w = beg;
1005 >        for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
1006 >             ; w = 0) { // w rejoins i on second leg
1007 >            // In this loop, i and w are on the same leg, with i > w
1008 >            for (; i < to; i++)
1009 >                if (isClear(deathRow, i - k))
1010 >                    es[w++] = es[i];
1011 >            if (to == end) break;
1012 >            // In this loop, w is on the first leg, i on the second
1013 >            for (i = 0, to = end, k -= capacity; i < to && w < capacity; i++)
1014 >                if (isClear(deathRow, i - k))
1015 >                    es[w++] = es[i];
1016 >            if (i >= to) {
1017 >                if (w == capacity) w = 0; // "corner" case
1018 >                break;
1019              }
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();
1020          }
1021 +        if (end != tail) throw new ConcurrentModificationException();
1022 +        circularClear(es, tail = w, end);
1023 +        // checkInvariants();
1024 +        return true;
1025      }
1026  
1027      /**
# Line 1079 | Line 1104 | public class ArrayDeque<E> extends Abstr
1104      private <T> T[] toArray(Class<T[]> klazz) {
1105          final Object[] es = elements;
1106          final T[] a;
1107 <        final int size = size(), head = this.head, end;
1108 <        final int len = Math.min(size, es.length - head);
1084 <        if ((end = head + size) >= 0) {
1107 >        final int head = this.head, tail = this.tail, end;
1108 >        if ((end = tail + ((head <= tail) ? 0 : es.length)) >= 0) {
1109              a = Arrays.copyOfRange(es, head, end, klazz);
1110          } else {
1111              // integer overflow!
1112 <            a = Arrays.copyOfRange(es, 0, size, klazz);
1113 <            System.arraycopy(es, head, a, 0, len);
1112 >            a = Arrays.copyOfRange(es, 0, end - head, klazz);
1113 >            System.arraycopy(es, head, a, 0, es.length - head);
1114          }
1115 <        if (tail < head)
1116 <            System.arraycopy(es, 0, a, len, tail);
1115 >        if (end != tail)
1116 >            System.arraycopy(es, 0, a, es.length - head, tail);
1117          return a;
1118      }
1119  
# Line 1214 | Line 1238 | public class ArrayDeque<E> extends Abstr
1238  
1239      /** debugging */
1240      void checkInvariants() {
1241 +        // Use head and tail fields with empty slot at tail strategy.
1242 +        // head == tail disambiguates to "empty".
1243          try {
1244              int capacity = elements.length;
1245              // assert head >= 0 && head < capacity;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines