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

Comparing jsr166/src/jsr166e/ConcurrentHashMapV8.java (file contents):
Revision 1.101 by jsr166, Tue Jun 18 17:57:21 2013 UTC vs.
Revision 1.109 by dl, Wed Jul 3 18:16:31 2013 UTC

# Line 6 | Line 6
6  
7   package jsr166e;
8  
9 < import java.util.Comparator;
9 > import jsr166e.ForkJoinPool;
10 >
11 > import java.io.ObjectStreamField;
12 > import java.io.Serializable;
13 > import java.lang.reflect.ParameterizedType;
14 > import java.lang.reflect.Type;
15   import java.util.Arrays;
11 import java.util.Map;
12 import java.util.Set;
16   import java.util.Collection;
17 < import java.util.AbstractMap;
18 < import java.util.AbstractSet;
19 < import java.util.AbstractCollection;
17 < import java.util.Hashtable;
17 > import java.util.Comparator;
18 > import java.util.ConcurrentModificationException;
19 > import java.util.Enumeration;
20   import java.util.HashMap;
21 + import java.util.Hashtable;
22   import java.util.Iterator;
23 < import java.util.Enumeration;
21 < import java.util.ConcurrentModificationException;
23 > import java.util.Map;
24   import java.util.NoSuchElementException;
25 + import java.util.Set;
26   import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
25 import java.util.concurrent.atomic.AtomicInteger;
27   import java.util.concurrent.atomic.AtomicReference;
28 < import java.io.Serializable;
28 > import java.util.concurrent.atomic.AtomicInteger;
29 > import java.util.concurrent.locks.LockSupport;
30 > import java.util.concurrent.locks.ReentrantLock;
31  
32   /**
33   * A hash table supporting full concurrency of retrievals and
# Line 78 | Line 81 | import java.io.Serializable;
81   * expected {@code concurrencyLevel} as an additional hint for
82   * internal sizing.  Note that using many keys with exactly the same
83   * {@code hashCode()} is a sure way to slow down performance of any
84 < * hash table.
84 > * hash table. To ameliorate impact, when keys are {@link Comparable},
85 > * this class may use comparison order among keys to help break ties.
86   *
87   * <p>A {@link Set} projection of a ConcurrentHashMapV8 may be created
88   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
# Line 86 | Line 90 | import java.io.Serializable;
90   * mapped values are (perhaps transiently) not used or all take the
91   * same mapping value.
92   *
89 * <p>A ConcurrentHashMapV8 can be used as scalable frequency map (a
90 * form of histogram or multiset) by using {@link LongAdder} values
91 * and initializing via {@link #computeIfAbsent}. For example, to add
92 * a count to a {@code ConcurrentHashMapV8<String,LongAdder> freqs}, you
93 * can use {@code freqs.computeIfAbsent(k -> new
94 * LongAdder()).increment();}
95 *
93   * <p>This class and its views and iterators implement all of the
94   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
95   * interfaces.
# Line 100 | Line 97 | import java.io.Serializable;
97   * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
98   * does <em>not</em> allow {@code null} to be used as a key or value.
99   *
100 < * <p>ConcurrentHashMapV8s support sequential and parallel operations
101 < * bulk operations. (Parallel forms use the {@link
102 < * ForkJoinPool#commonPool()}). Tasks that may be used in other
103 < * contexts are available in class {@link ForkJoinTasks}. These
104 < * operations are designed to be safely, and often sensibly, applied
105 < * even with maps that are being concurrently updated by other
106 < * threads; for example, when computing a snapshot summary of the
107 < * values in a shared registry.  There are three kinds of operation,
108 < * each with four forms, accepting functions with Keys, Values,
109 < * Entries, and (Key, Value) arguments and/or return values. Because
110 < * the elements of a ConcurrentHashMapV8 are not ordered in any
111 < * particular way, and may be processed in different orders in
112 < * different parallel executions, the correctness of supplied
113 < * functions should not depend on any ordering, or on any other
114 < * objects or values that may transiently change while computation is
118 < * in progress; and except for forEach actions, should ideally be
119 < * side-effect-free.
100 > * <p>ConcurrentHashMapV8s support a set of sequential and parallel bulk
101 > * operations that are designed
102 > * to be safely, and often sensibly, applied even with maps that are
103 > * being concurrently updated by other threads; for example, when
104 > * computing a snapshot summary of the values in a shared registry.
105 > * There are three kinds of operation, each with four forms, accepting
106 > * functions with Keys, Values, Entries, and (Key, Value) arguments
107 > * and/or return values. Because the elements of a ConcurrentHashMapV8
108 > * are not ordered in any particular way, and may be processed in
109 > * different orders in different parallel executions, the correctness
110 > * of supplied functions should not depend on any ordering, or on any
111 > * other objects or values that may transiently change while
112 > * computation is in progress; and except for forEach actions, should
113 > * ideally be side-effect-free. Bulk operations on {@link java.util.Map.Entry}
114 > * objects do not support method {@code setValue}.
115   *
116   * <ul>
117   * <li> forEach: Perform a given action on each element.
# Line 143 | Line 138 | import java.io.Serializable;
138   * <li> Reductions to scalar doubles, longs, and ints, using a
139   * given basis value.</li>
140   *
146 * </li>
141   * </ul>
142 + * </li>
143   * </ul>
144   *
145 + * <p>These bulk operations accept a {@code parallelismThreshold}
146 + * argument. Methods proceed sequentially if the current map size is
147 + * estimated to be less than the given threshold. Using a value of
148 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
149 + * of {@code 1} results in maximal parallelism by partitioning into
150 + * enough subtasks to fully utilize the {@link
151 + * ForkJoinPool#commonPool()} that is used for all parallel
152 + * computations. Normally, you would initially choose one of these
153 + * extreme values, and then measure performance of using in-between
154 + * values that trade off overhead versus throughput.
155 + *
156   * <p>The concurrency properties of bulk operations follow
157   * from those of ConcurrentHashMapV8: Any non-null result returned
158   * from {@code get(key)} and related access methods bears a
# Line 217 | Line 223 | public class ConcurrentHashMapV8<K,V>
223      private static final long serialVersionUID = 7249069246763182397L;
224  
225      /**
226 <     * A partitionable iterator. A Spliterator can be traversed
227 <     * directly, but can also be partitioned (before traversal) by
228 <     * creating another Spliterator that covers a non-overlapping
223 <     * portion of the elements, and so may be amenable to parallel
224 <     * execution.
225 <     *
226 <     * <p>This interface exports a subset of expected JDK8
227 <     * functionality.
228 <     *
229 <     * <p>Sample usage: Here is one (of the several) ways to compute
230 <     * the sum of the values held in a map using the ForkJoin
231 <     * framework. As illustrated here, Spliterators are well suited to
232 <     * designs in which a task repeatedly splits off half its work
233 <     * into forked subtasks until small enough to process directly,
234 <     * and then joins these subtasks. Variants of this style can also
235 <     * be used in completion-based designs.
236 <     *
237 <     * <pre>
238 <     * {@code ConcurrentHashMapV8<String, Long> m = ...
239 <     * // split as if have 8 * parallelism, for load balance
240 <     * int n = m.size();
241 <     * int p = aForkJoinPool.getParallelism() * 8;
242 <     * int split = (n < p)? n : p;
243 <     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
244 <     * // ...
245 <     * static class SumValues extends RecursiveTask<Long> {
246 <     *   final Spliterator<Long> s;
247 <     *   final int split;             // split while > 1
248 <     *   final SumValues nextJoin;    // records forked subtasks to join
249 <     *   SumValues(Spliterator<Long> s, int depth, SumValues nextJoin) {
250 <     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
251 <     *   }
252 <     *   public Long compute() {
253 <     *     long sum = 0;
254 <     *     SumValues subtasks = null; // fork subtasks
255 <     *     for (int s = split >>> 1; s > 0; s >>>= 1)
256 <     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
257 <     *     while (s.hasNext())        // directly process remaining elements
258 <     *       sum += s.next();
259 <     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
260 <     *       sum += t.join();         // collect subtask results
261 <     *     return sum;
262 <     *   }
263 <     * }
264 <     * }</pre>
226 >     * An object for traversing and partitioning elements of a source.
227 >     * This interface provides a subset of the functionality of JDK8
228 >     * java.util.Spliterator.
229       */
230 <    public static interface Spliterator<T> extends Iterator<T> {
230 >    public static interface ConcurrentHashMapSpliterator<T> {
231          /**
232 <         * Returns a Spliterator covering approximately half of the
233 <         * elements, guaranteed not to overlap with those subsequently
234 <         * returned by this Spliterator.  After invoking this method,
235 <         * the current Spliterator will <em>not</em> produce any of
236 <         * the elements of the returned Spliterator, but the two
237 <         * Spliterators together will produce all of the elements that
238 <         * would have been produced by this Spliterator had this
239 <         * method not been called. The exact number of elements
240 <         * produced by the returned Spliterator is not guaranteed, and
277 <         * may be zero (i.e., with {@code hasNext()} reporting {@code
278 <         * false}) if this Spliterator cannot be further split.
279 <         *
280 <         * @return a Spliterator covering approximately half of the
281 <         * elements
282 <         * @throws IllegalStateException if this Spliterator has
283 <         * already commenced traversing elements
232 >         * If possible, returns a new spliterator covering
233 >         * approximately one half of the elements, which will not be
234 >         * covered by this spliterator. Returns null if cannot be
235 >         * split.
236 >         */
237 >        ConcurrentHashMapSpliterator<T> trySplit();
238 >        /**
239 >         * Returns an estimate of the number of elements covered by
240 >         * this Spliterator.
241           */
242 <        Spliterator<T> split();
242 >        long estimateSize();
243 >
244 >        /** Applies the action to each untraversed element */
245 >        void forEachRemaining(Action<? super T> action);
246 >        /** If an element remains, applies the action and returns true. */
247 >        boolean tryAdvance(Action<? super T> action);
248      }
249  
250 +    // Sams
251 +    /** Interface describing a void action of one argument */
252 +    public interface Action<A> { void apply(A a); }
253 +    /** Interface describing a void action of two arguments */
254 +    public interface BiAction<A,B> { void apply(A a, B b); }
255 +    /** Interface describing a function of one argument */
256 +    public interface Fun<A,T> { T apply(A a); }
257 +    /** Interface describing a function of two arguments */
258 +    public interface BiFun<A,B,T> { T apply(A a, B b); }
259 +    /** Interface describing a function mapping its argument to a double */
260 +    public interface ObjectToDouble<A> { double apply(A a); }
261 +    /** Interface describing a function mapping its argument to a long */
262 +    public interface ObjectToLong<A> { long apply(A a); }
263 +    /** Interface describing a function mapping its argument to an int */
264 +    public interface ObjectToInt<A> {int apply(A a); }
265 +    /** Interface describing a function mapping two arguments to a double */
266 +    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
267 +    /** Interface describing a function mapping two arguments to a long */
268 +    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
269 +    /** Interface describing a function mapping two arguments to an int */
270 +    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
271 +    /** Interface describing a function mapping two doubles to a double */
272 +    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
273 +    /** Interface describing a function mapping two longs to a long */
274 +    public interface LongByLongToLong { long apply(long a, long b); }
275 +    /** Interface describing a function mapping two ints to an int */
276 +    public interface IntByIntToInt { int apply(int a, int b); }
277 +
278      /*
279       * Overview:
280       *
# Line 295 | Line 285 | public class ConcurrentHashMapV8<K,V>
285       * the same or better than java.util.HashMap, and to support high
286       * initial insertion rates on an empty table by many threads.
287       *
288 <     * Each key-value mapping is held in a Node.  Because Node key
289 <     * fields can contain special values, they are defined using plain
290 <     * Object types (not type "K"). This leads to a lot of explicit
291 <     * casting (and many explicit warning suppressions to tell
292 <     * compilers not to complain about it). It also allows some of the
293 <     * public methods to be factored into a smaller number of internal
294 <     * methods (although sadly not so for the five variants of
295 <     * put-related operations). The validation-based approach
296 <     * explained below leads to a lot of code sprawl because
297 <     * retry-control precludes factoring into smaller methods.
288 >     * This map usually acts as a binned (bucketed) hash table.  Each
289 >     * key-value mapping is held in a Node.  Most nodes are instances
290 >     * of the basic Node class with hash, key, value, and next
291 >     * fields. However, various subclasses exist: TreeNodes are
292 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
293 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
294 >     * of bins during resizing. ReservationNodes are used as
295 >     * placeholders while establishing values in computeIfAbsent and
296 >     * related methods.  The types TreeBin, ForwardingNode, and
297 >     * ReservationNode do not hold normal user keys, values, or
298 >     * hashes, and are readily distinguishable during search etc
299 >     * because they have negative hash fields and null key and value
300 >     * fields. (These special nodes are either uncommon or transient,
301 >     * so the impact of carrying around some unused fields is
302 >     * insignificant.)
303       *
304       * The table is lazily initialized to a power-of-two size upon the
305       * first insertion.  Each bin in the table normally contains a
# Line 312 | Line 307 | public class ConcurrentHashMapV8<K,V>
307       * Table accesses require volatile/atomic reads, writes, and
308       * CASes.  Because there is no other way to arrange this without
309       * adding further indirections, we use intrinsics
310 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
316 <     * are always accurately traversable under volatile reads, so long
317 <     * as lookups check hash code and non-nullness of value before
318 <     * checking key equality.
310 >     * (sun.misc.Unsafe) operations.
311       *
312       * We use the top (sign) bit of Node hash fields for control
313       * purposes -- it is available anyway because of addressing
314 <     * constraints.  Nodes with negative hash fields are forwarding
315 <     * nodes to either TreeBins or resized tables.  The lower 31 bits
324 <     * of each normal Node's hash field contain a transformation of
325 <     * the key's hash code.
314 >     * constraints.  Nodes with negative hash fields are specially
315 >     * handled or ignored in map methods.
316       *
317       * Insertion (via put or its variants) of the first node in an
318       * empty bin is performed by just CASing it to the bin.  This is
# Line 339 | Line 329 | public class ConcurrentHashMapV8<K,V>
329       * validate that it is still the first node after locking it, and
330       * retry if not. Because new nodes are always appended to lists,
331       * once a node is first in a bin, it remains first until deleted
332 <     * or the bin becomes invalidated (upon resizing).  However,
343 <     * operations that only conditionally update may inspect nodes
344 <     * until the point of update. This is a converse of sorts to the
345 <     * lazy locking technique described by Herlihy & Shavit.
332 >     * or the bin becomes invalidated (upon resizing).
333       *
334       * The main disadvantage of per-bin locks is that other update
335       * operations on other nodes in a bin list protected by the same
# Line 375 | Line 362 | public class ConcurrentHashMapV8<K,V>
362       * sometimes deviate significantly from uniform randomness.  This
363       * includes the case when N > (1<<30), so some keys MUST collide.
364       * Similarly for dumb or hostile usages in which multiple keys are
365 <     * designed to have identical hash codes. Also, although we guard
366 <     * against the worst effects of this (see method spread), sets of
367 <     * hashes may differ only in bits that do not impact their bin
368 <     * index for a given power-of-two mask.  So we use a secondary
369 <     * strategy that applies when the number of nodes in a bin exceeds
370 <     * a threshold, and at least one of the keys implements
384 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
385 <     * (a specialized form of red-black trees), bounding search time
386 <     * to O(log N).  Each search step in a TreeBin is around twice as
365 >     * designed to have identical hash codes or ones that differs only
366 >     * in masked-out high bits. So we use a secondary strategy that
367 >     * applies when the number of nodes in a bin exceeds a
368 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
369 >     * specialized form of red-black trees), bounding search time to
370 >     * O(log N).  Each search step in a TreeBin is at least twice as
371       * slow as in a regular list, but given that N cannot exceed
372       * (1<<64) (before running out of addresses) this bounds search
373       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 456 | Line 440 | public class ConcurrentHashMapV8<K,V>
440       * bin already holding two or more nodes. Under uniform hash
441       * distributions, the probability of this occurring at threshold
442       * is around 13%, meaning that only about 1 in 8 puts check
443 <     * threshold (and after resizing, many fewer do so). The bulk
444 <     * putAll operation further reduces contention by only committing
445 <     * count updates upon these size checks.
443 >     * threshold (and after resizing, many fewer do so).
444 >     *
445 >     * TreeBins use a special form of comparison for search and
446 >     * related operations (which is the main reason we cannot use
447 >     * existing collections such as TreeMaps). TreeBins contain
448 >     * Comparable elements, but may contain others, as well as
449 >     * elements that are Comparable but not necessarily Comparable
450 >     * for the same T, so we cannot invoke compareTo among them. To
451 >     * handle this, the tree is ordered primarily by hash value, then
452 >     * by Comparable.compareTo order if applicable.  On lookup at a
453 >     * node, if elements are not comparable or compare as 0 then both
454 >     * left and right children may need to be searched in the case of
455 >     * tied hash values. (This corresponds to the full list search
456 >     * that would be necessary if all elements were non-Comparable and
457 >     * had tied hashes.)  The red-black balancing code is updated from
458 >     * pre-jdk-collections
459 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
460 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
461 >     * Algorithms" (CLR).
462 >     *
463 >     * TreeBins also require an additional locking mechanism.  While
464 >     * list traversal is always possible by readers even during
465 >     * updates, tree traversal is not, mainly because of tree-rotations
466 >     * that may change the root node and/or its linkages.  TreeBins
467 >     * include a simple read-write lock mechanism parasitic on the
468 >     * main bin-synchronization strategy: Structural adjustments
469 >     * associated with an insertion or removal are already bin-locked
470 >     * (and so cannot conflict with other writers) but must wait for
471 >     * ongoing readers to finish. Since there can be only one such
472 >     * waiter, we use a simple scheme using a single "waiter" field to
473 >     * block writers.  However, readers need never block.  If the root
474 >     * lock is held, they proceed along the slow traversal path (via
475 >     * next-pointers) until the lock becomes available or the list is
476 >     * exhausted, whichever comes first. These cases are not fast, but
477 >     * maximize aggregate expected throughput.
478       *
479       * Maintaining API and serialization compatibility with previous
480       * versions of this class introduces several oddities. Mainly: We
# Line 468 | Line 484 | public class ConcurrentHashMapV8<K,V>
484       * time that we can guarantee to honor it.) We also declare an
485       * unused "Segment" class that is instantiated in minimal form
486       * only when serializing.
487 +     *
488 +     * This file is organized to make things a little easier to follow
489 +     * while reading than they might otherwise: First the main static
490 +     * declarations and utilities, then fields, then main public
491 +     * methods (with a few factorings of multiple public methods into
492 +     * internal ones), then sizing methods, trees, traversers, and
493 +     * bulk operations.
494       */
495  
496      /* ---------------- Constants -------------- */
# Line 510 | Line 533 | public class ConcurrentHashMapV8<K,V>
533  
534      /**
535       * The bin count threshold for using a tree rather than list for a
536 <     * bin.  The value reflects the approximate break-even point for
537 <     * using tree-based operations.
536 >     * bin.  Bins are converted to trees when adding an element to a
537 >     * bin with at least this many nodes. The value must be greater
538 >     * than 2, and should be at least 8 to mesh with assumptions in
539 >     * tree removal about conversion back to plain bins upon
540 >     * shrinkage.
541 >     */
542 >    static final int TREEIFY_THRESHOLD = 8;
543 >
544 >    /**
545 >     * The bin count threshold for untreeifying a (split) bin during a
546 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
547 >     * most 6 to mesh with shrinkage detection under removal.
548       */
549 <    private static final int TREE_THRESHOLD = 8;
549 >    static final int UNTREEIFY_THRESHOLD = 6;
550 >
551 >    /**
552 >     * The smallest table capacity for which bins may be treeified.
553 >     * (Otherwise the table is resized if too many nodes in a bin.)
554 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
555 >     * conflicts between resizing and treeification thresholds.
556 >     */
557 >    static final int MIN_TREEIFY_CAPACITY = 64;
558  
559      /**
560       * Minimum number of rebinnings per transfer step. Ranges are
# Line 527 | Line 568 | public class ConcurrentHashMapV8<K,V>
568      /*
569       * Encodings for Node hash fields. See above for explanation.
570       */
571 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
571 >    static final int MOVED     = -1; // hash for forwarding nodes
572 >    static final int TREEBIN   = -2; // hash for roots of trees
573 >    static final int RESERVED  = -3; // hash for transient reservations
574      static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
575  
576      /** Number of CPUS, to place bounds on some sizings */
577      static final int NCPU = Runtime.getRuntime().availableProcessors();
578  
579 <    /* ---------------- Counters -------------- */
579 >    /** For serialization compatibility. */
580 >    private static final ObjectStreamField[] serialPersistentFields = {
581 >        new ObjectStreamField("segments", Segment[].class),
582 >        new ObjectStreamField("segmentMask", Integer.TYPE),
583 >        new ObjectStreamField("segmentShift", Integer.TYPE)
584 >    };
585  
586 <    // Adapted from LongAdder and Striped64.
539 <    // See their internal docs for explanation.
586 >    /* ---------------- Nodes -------------- */
587  
588 <    // A padded cell for distributing counts
589 <    static final class CounterCell {
590 <        volatile long p0, p1, p2, p3, p4, p5, p6;
591 <        volatile long value;
592 <        volatile long q0, q1, q2, q3, q4, q5, q6;
593 <        CounterCell(long x) { value = x; }
588 >    /**
589 >     * Key-value entry.  This class is never exported out as a
590 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
591 >     * MapEntry below), but can be used for read-only traversals used
592 >     * in bulk tasks.  Subclasses of Node with a negative hash field
593 >     * are special, and contain null keys and values (but are never
594 >     * exported).  Otherwise, keys and vals are never null.
595 >     */
596 >    static class Node<K,V> implements Map.Entry<K,V> {
597 >        final int hash;
598 >        final K key;
599 >        volatile V val;
600 >        volatile Node<K,V> next;
601 >
602 >        Node(int hash, K key, V val, Node<K,V> next) {
603 >            this.hash = hash;
604 >            this.key = key;
605 >            this.val = val;
606 >            this.next = next;
607 >        }
608 >
609 >        public final K getKey()       { return key; }
610 >        public final V getValue()     { return val; }
611 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
612 >        public final String toString(){ return key + "=" + val; }
613 >        public final V setValue(V value) {
614 >            throw new UnsupportedOperationException();
615 >        }
616 >
617 >        public final boolean equals(Object o) {
618 >            Object k, v, u; Map.Entry<?,?> e;
619 >            return ((o instanceof Map.Entry) &&
620 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
621 >                    (v = e.getValue()) != null &&
622 >                    (k == key || k.equals(key)) &&
623 >                    (v == (u = val) || v.equals(u)));
624 >        }
625 >
626 >        /**
627 >         * Virtualized support for map.get(); overridden in subclasses.
628 >         */
629 >        Node<K,V> find(int h, Object k) {
630 >            Node<K,V> e = this;
631 >            if (k != null) {
632 >                do {
633 >                    K ek;
634 >                    if (e.hash == h &&
635 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
636 >                        return e;
637 >                } while ((e = e.next) != null);
638 >            }
639 >            return null;
640 >        }
641      }
642  
643 +    /* ---------------- Static utilities -------------- */
644 +
645      /**
646 <     * Holder for the thread-local hash code determining which
647 <     * CounterCell to use. The code is initialized via the
648 <     * counterHashCodeGenerator, but may be moved upon collisions.
646 >     * Spreads (XORs) higher bits of hash to lower and also forces top
647 >     * bit to 0. Because the table uses power-of-two masking, sets of
648 >     * hashes that vary only in bits above the current mask will
649 >     * always collide. (Among known examples are sets of Float keys
650 >     * holding consecutive whole numbers in small tables.)  So we
651 >     * apply a transform that spreads the impact of higher bits
652 >     * downward. There is a tradeoff between speed, utility, and
653 >     * quality of bit-spreading. Because many common sets of hashes
654 >     * are already reasonably distributed (so don't benefit from
655 >     * spreading), and because we use trees to handle large sets of
656 >     * collisions in bins, we just XOR some shifted bits in the
657 >     * cheapest possible way to reduce systematic lossage, as well as
658 >     * to incorporate impact of the highest bits that would otherwise
659 >     * never be used in index calculations because of table bounds.
660       */
661 <    static final class CounterHashCode {
662 <        int code;
661 >    static final int spread(int h) {
662 >        return (h ^ (h >>> 16)) & HASH_BITS;
663      }
664  
665      /**
666 <     * Generates initial value for per-thread CounterHashCodes
666 >     * Returns a power of two table size for the given desired capacity.
667 >     * See Hackers Delight, sec 3.2
668       */
669 <    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
669 >    private static final int tableSizeFor(int c) {
670 >        int n = c - 1;
671 >        n |= n >>> 1;
672 >        n |= n >>> 2;
673 >        n |= n >>> 4;
674 >        n |= n >>> 8;
675 >        n |= n >>> 16;
676 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
677 >    }
678  
679      /**
680 <     * Increment for counterHashCodeGenerator. See class ThreadLocal
681 <     * for explanation.
680 >     * Returns x's Class if it is of the form "class C implements
681 >     * Comparable<C>", else null.
682       */
683 <    static final int SEED_INCREMENT = 0x61c88647;
683 >    static Class<?> comparableClassFor(Object x) {
684 >        if (x instanceof Comparable) {
685 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
686 >            if ((c = x.getClass()) == String.class) // bypass checks
687 >                return c;
688 >            if ((ts = c.getGenericInterfaces()) != null) {
689 >                for (int i = 0; i < ts.length; ++i) {
690 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
691 >                        ((p = (ParameterizedType)t).getRawType() ==
692 >                         Comparable.class) &&
693 >                        (as = p.getActualTypeArguments()) != null &&
694 >                        as.length == 1 && as[0] == c) // type arg is c
695 >                        return c;
696 >                }
697 >            }
698 >        }
699 >        return null;
700 >    }
701  
702      /**
703 <     * Per-thread counter hash codes. Shared across all instances.
703 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
704 >     * class), else 0.
705       */
706 <    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
707 <        new ThreadLocal<CounterHashCode>();
706 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
707 >    static int compareComparables(Class<?> kc, Object k, Object x) {
708 >        return (x == null || x.getClass() != kc ? 0 :
709 >                ((Comparable)k).compareTo(x));
710 >    }
711 >
712 >    /* ---------------- Table element access -------------- */
713 >
714 >    /*
715 >     * Volatile access methods are used for table elements as well as
716 >     * elements of in-progress next table while resizing.  All uses of
717 >     * the tab arguments must be null checked by callers.  All callers
718 >     * also paranoically precheck that tab's length is not zero (or an
719 >     * equivalent check), thus ensuring that any index argument taking
720 >     * the form of a hash value anded with (length - 1) is a valid
721 >     * index.  Note that, to be correct wrt arbitrary concurrency
722 >     * errors by users, these checks must operate on local variables,
723 >     * which accounts for some odd-looking inline assignments below.
724 >     * Note that calls to setTabAt always occur within locked regions,
725 >     * and so in principle require only release ordering, not need
726 >     * full volatile semantics, but are currently coded as volatile
727 >     * writes to be conservative.
728 >     */
729 >
730 >    @SuppressWarnings("unchecked")
731 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
732 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
733 >    }
734 >
735 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
736 >                                        Node<K,V> c, Node<K,V> v) {
737 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
738 >    }
739 >
740 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
741 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
742 >    }
743  
744      /* ---------------- Fields -------------- */
745  
# Line 578 | Line 747 | public class ConcurrentHashMapV8<K,V>
747       * The array of bins. Lazily initialized upon first insertion.
748       * Size is always a power of two. Accessed directly by iterators.
749       */
750 <    transient volatile Node<V>[] table;
750 >    transient volatile Node<K,V>[] table;
751  
752      /**
753       * The next table to use; non-null only while resizing.
754       */
755 <    private transient volatile Node<V>[] nextTable;
755 >    private transient volatile Node<K,V>[] nextTable;
756  
757      /**
758       * Base counter value, used mainly when there is no contention,
# Line 613 | Line 782 | public class ConcurrentHashMapV8<K,V>
782      private transient volatile int transferOrigin;
783  
784      /**
785 <     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
785 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
786       */
787 <    private transient volatile int counterBusy;
787 >    private transient volatile int cellsBusy;
788  
789      /**
790       * Table of counter cells. When non-null, size is a power of 2.
# Line 627 | Line 796 | public class ConcurrentHashMapV8<K,V>
796      private transient ValuesView<K,V> values;
797      private transient EntrySetView<K,V> entrySet;
798  
630    /** For serialization compatibility. Null unless serialized; see below */
631    private Segment<K,V>[] segments;
799  
800 <    /* ---------------- Table element access -------------- */
800 >    /* ---------------- Public operations -------------- */
801  
802 <    /*
803 <     * Volatile access methods are used for table elements as well as
804 <     * elements of in-progress next table while resizing.  Uses are
805 <     * null checked by callers, and implicitly bounds-checked, relying
639 <     * on the invariants that tab arrays have non-zero size, and all
640 <     * indices are masked with (tab.length - 1) which is never
641 <     * negative and always less than length. Note that, to be correct
642 <     * wrt arbitrary concurrency errors by users, bounds checks must
643 <     * operate on local variables, which accounts for some odd-looking
644 <     * inline assignments below.
645 <     */
646 <
647 <    @SuppressWarnings("unchecked") static final <V> Node<V> tabAt
648 <        (Node<V>[] tab, int i) { // used by Traverser
649 <        return (Node<V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
802 >    /**
803 >     * Creates a new, empty map with the default initial table size (16).
804 >     */
805 >    public ConcurrentHashMapV8() {
806      }
807  
808 <    private static final <V> boolean casTabAt
809 <        (Node<V>[] tab, int i, Node<V> c, Node<V> v) {
810 <        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
808 >    /**
809 >     * Creates a new, empty map with an initial table size
810 >     * accommodating the specified number of elements without the need
811 >     * to dynamically resize.
812 >     *
813 >     * @param initialCapacity The implementation performs internal
814 >     * sizing to accommodate this many elements.
815 >     * @throws IllegalArgumentException if the initial capacity of
816 >     * elements is negative
817 >     */
818 >    public ConcurrentHashMapV8(int initialCapacity) {
819 >        if (initialCapacity < 0)
820 >            throw new IllegalArgumentException();
821 >        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
822 >                   MAXIMUM_CAPACITY :
823 >                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
824 >        this.sizeCtl = cap;
825      }
826  
827 <    private static final <V> void setTabAt
828 <        (Node<V>[] tab, int i, Node<V> v) {
829 <        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
827 >    /**
828 >     * Creates a new map with the same mappings as the given map.
829 >     *
830 >     * @param m the map
831 >     */
832 >    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
833 >        this.sizeCtl = DEFAULT_CAPACITY;
834 >        putAll(m);
835      }
836  
662    /* ---------------- Nodes -------------- */
663
837      /**
838 <     * Key-value entry. Note that this is never exported out as a
839 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
840 <     * field of MOVED are special, and do not contain user keys or
841 <     * values.  Otherwise, keys are never null, and null val fields
842 <     * indicate that a node is in the process of being deleted or
843 <     * created. For purposes of read-only access, a key may be read
844 <     * before a val, but can only be used after checking val to be
845 <     * non-null.
838 >     * Creates a new, empty map with an initial table size based on
839 >     * the given number of elements ({@code initialCapacity}) and
840 >     * initial table density ({@code loadFactor}).
841 >     *
842 >     * @param initialCapacity the initial capacity. The implementation
843 >     * performs internal sizing to accommodate this many elements,
844 >     * given the specified load factor.
845 >     * @param loadFactor the load factor (table density) for
846 >     * establishing the initial table size
847 >     * @throws IllegalArgumentException if the initial capacity of
848 >     * elements is negative or the load factor is nonpositive
849 >     *
850 >     * @since 1.6
851       */
852 <    static class Node<V> {
853 <        final int hash;
854 <        final Object key;
677 <        volatile V val;
678 <        volatile Node<V> next;
852 >    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
853 >        this(initialCapacity, loadFactor, 1);
854 >    }
855  
856 <        Node(int hash, Object key, V val, Node<V> next) {
857 <            this.hash = hash;
858 <            this.key = key;
859 <            this.val = val;
860 <            this.next = next;
861 <        }
856 >    /**
857 >     * Creates a new, empty map with an initial table size based on
858 >     * the given number of elements ({@code initialCapacity}), table
859 >     * density ({@code loadFactor}), and number of concurrently
860 >     * updating threads ({@code concurrencyLevel}).
861 >     *
862 >     * @param initialCapacity the initial capacity. The implementation
863 >     * performs internal sizing to accommodate this many elements,
864 >     * given the specified load factor.
865 >     * @param loadFactor the load factor (table density) for
866 >     * establishing the initial table size
867 >     * @param concurrencyLevel the estimated number of concurrently
868 >     * updating threads. The implementation may use this value as
869 >     * a sizing hint.
870 >     * @throws IllegalArgumentException if the initial capacity is
871 >     * negative or the load factor or concurrencyLevel are
872 >     * nonpositive
873 >     */
874 >    public ConcurrentHashMapV8(int initialCapacity,
875 >                             float loadFactor, int concurrencyLevel) {
876 >        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
877 >            throw new IllegalArgumentException();
878 >        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
879 >            initialCapacity = concurrencyLevel;   // as estimated threads
880 >        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
881 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
882 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
883 >        this.sizeCtl = cap;
884      }
885  
886 <    /* ---------------- TreeBins -------------- */
886 >    // Original (since JDK1.2) Map methods
887  
888      /**
889 <     * Nodes for use in TreeBins
889 >     * {@inheritDoc}
890       */
891 <    static final class TreeNode<V> extends Node<V> {
892 <        TreeNode<V> parent;  // red-black tree links
893 <        TreeNode<V> left;
894 <        TreeNode<V> right;
895 <        TreeNode<V> prev;    // needed to unlink next upon deletion
896 <        boolean red;
891 >    public int size() {
892 >        long n = sumCount();
893 >        return ((n < 0L) ? 0 :
894 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
895 >                (int)n);
896 >    }
897  
898 <        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
899 <            super(hash, key, val, next);
900 <            this.parent = parent;
901 <        }
898 >    /**
899 >     * {@inheritDoc}
900 >     */
901 >    public boolean isEmpty() {
902 >        return sumCount() <= 0L; // ignore transient negative values
903      }
904  
905      /**
906 <     * A specialized form of red-black tree for use in bins
907 <     * whose size exceeds a threshold.
906 >     * Returns the value to which the specified key is mapped,
907 >     * or {@code null} if this map contains no mapping for the key.
908       *
909 <     * TreeBins use a special form of comparison for search and
910 <     * related operations (which is the main reason we cannot use
911 <     * existing collections such as TreeMaps). TreeBins contain
912 <     * Comparable elements, but may contain others, as well as
714 <     * elements that are Comparable but not necessarily Comparable<T>
715 <     * for the same T, so we cannot invoke compareTo among them. To
716 <     * handle this, the tree is ordered primarily by hash value, then
717 <     * by getClass().getName() order, and then by Comparator order
718 <     * among elements of the same class.  On lookup at a node, if
719 <     * elements are not comparable or compare as 0, both left and
720 <     * right children may need to be searched in the case of tied hash
721 <     * values. (This corresponds to the full list search that would be
722 <     * necessary if all elements were non-Comparable and had tied
723 <     * hashes.)  The red-black balancing code is updated from
724 <     * pre-jdk-collections
725 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
726 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
727 <     * Algorithms" (CLR).
909 >     * <p>More formally, if this map contains a mapping from a key
910 >     * {@code k} to a value {@code v} such that {@code key.equals(k)},
911 >     * then this method returns {@code v}; otherwise it returns
912 >     * {@code null}.  (There can be at most one such mapping.)
913       *
914 <     * TreeBins also maintain a separate locking discipline than
730 <     * regular bins. Because they are forwarded via special MOVED
731 <     * nodes at bin heads (which can never change once established),
732 <     * we cannot use those nodes as locks. Instead, TreeBin
733 <     * extends AbstractQueuedSynchronizer to support a simple form of
734 <     * read-write lock. For update operations and table validation,
735 <     * the exclusive form of lock behaves in the same way as bin-head
736 <     * locks. However, lookups use shared read-lock mechanics to allow
737 <     * multiple readers in the absence of writers.  Additionally,
738 <     * these lookups do not ever block: While the lock is not
739 <     * available, they proceed along the slow traversal path (via
740 <     * next-pointers) until the lock becomes available or the list is
741 <     * exhausted, whichever comes first. (These cases are not fast,
742 <     * but maximize aggregate expected throughput.)  The AQS mechanics
743 <     * for doing this are straightforward.  The lock state is held as
744 <     * AQS getState().  Read counts are negative; the write count (1)
745 <     * is positive.  There are no signalling preferences among readers
746 <     * and writers. Since we don't need to export full Lock API, we
747 <     * just override the minimal AQS methods and use them directly.
914 >     * @throws NullPointerException if the specified key is null
915       */
916 <    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
917 <        private static final long serialVersionUID = 2249069246763182397L;
918 <        transient TreeNode<V> root;  // root of tree
919 <        transient TreeNode<V> first; // head of next-pointer list
920 <
921 <        /* AQS overrides */
922 <        public final boolean isHeldExclusively() { return getState() > 0; }
923 <        public final boolean tryAcquire(int ignore) {
924 <            if (compareAndSetState(0, 1)) {
925 <                setExclusiveOwnerThread(Thread.currentThread());
926 <                return true;
927 <            }
928 <            return false;
929 <        }
930 <        public final boolean tryRelease(int ignore) {
764 <            setExclusiveOwnerThread(null);
765 <            setState(0);
766 <            return true;
767 <        }
768 <        public final int tryAcquireShared(int ignore) {
769 <            for (int c;;) {
770 <                if ((c = getState()) > 0)
771 <                    return -1;
772 <                if (compareAndSetState(c, c -1))
773 <                    return 1;
774 <            }
775 <        }
776 <        public final boolean tryReleaseShared(int ignore) {
777 <            int c;
778 <            do {} while (!compareAndSetState(c = getState(), c + 1));
779 <            return c == -1;
780 <        }
781 <
782 <        /** From CLR */
783 <        private void rotateLeft(TreeNode<V> p) {
784 <            if (p != null) {
785 <                TreeNode<V> r = p.right, pp, rl;
786 <                if ((rl = p.right = r.left) != null)
787 <                    rl.parent = p;
788 <                if ((pp = r.parent = p.parent) == null)
789 <                    root = r;
790 <                else if (pp.left == p)
791 <                    pp.left = r;
792 <                else
793 <                    pp.right = r;
794 <                r.left = p;
795 <                p.parent = r;
796 <            }
797 <        }
798 <
799 <        /** From CLR */
800 <        private void rotateRight(TreeNode<V> p) {
801 <            if (p != null) {
802 <                TreeNode<V> l = p.left, pp, lr;
803 <                if ((lr = p.left = l.right) != null)
804 <                    lr.parent = p;
805 <                if ((pp = l.parent = p.parent) == null)
806 <                    root = l;
807 <                else if (pp.right == p)
808 <                    pp.right = l;
809 <                else
810 <                    pp.left = l;
811 <                l.right = p;
812 <                p.parent = l;
916 >    public V get(Object key) {
917 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
918 >        int h = spread(key.hashCode());
919 >        if ((tab = table) != null && (n = tab.length) > 0 &&
920 >            (e = tabAt(tab, (n - 1) & h)) != null) {
921 >            if ((eh = e.hash) == h) {
922 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
923 >                    return e.val;
924 >            }
925 >            else if (eh < 0)
926 >                return (p = e.find(h, key)) != null ? p.val : null;
927 >            while ((e = e.next) != null) {
928 >                if (e.hash == h &&
929 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
930 >                    return e.val;
931              }
932          }
933 +        return null;
934 +    }
935  
936 <        /**
937 <         * Returns the TreeNode (or null if not found) for the given key
938 <         * starting at given root.
939 <         */
940 <        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
941 <            (int h, Object k, TreeNode<V> p) {
942 <            Class<?> c = k.getClass();
943 <            while (p != null) {
944 <                int dir, ph;  Object pk; Class<?> pc;
945 <                if ((ph = p.hash) == h) {
946 <                    if ((pk = p.key) == k || k.equals(pk))
947 <                        return p;
828 <                    if (c != (pc = pk.getClass()) ||
829 <                        !(k instanceof Comparable) ||
830 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
831 <                        if ((dir = (c == pc) ? 0 :
832 <                             c.getName().compareTo(pc.getName())) == 0) {
833 <                            TreeNode<V> r = null, pl, pr; // check both sides
834 <                            if ((pr = p.right) != null && h >= pr.hash &&
835 <                                (r = getTreeNode(h, k, pr)) != null)
836 <                                return r;
837 <                            else if ((pl = p.left) != null && h <= pl.hash)
838 <                                dir = -1;
839 <                            else // nothing there
840 <                                return null;
841 <                        }
842 <                    }
843 <                }
844 <                else
845 <                    dir = (h < ph) ? -1 : 1;
846 <                p = (dir > 0) ? p.right : p.left;
847 <            }
848 <            return null;
849 <        }
936 >    /**
937 >     * Tests if the specified object is a key in this table.
938 >     *
939 >     * @param  key possible key
940 >     * @return {@code true} if and only if the specified object
941 >     *         is a key in this table, as determined by the
942 >     *         {@code equals} method; {@code false} otherwise
943 >     * @throws NullPointerException if the specified key is null
944 >     */
945 >    public boolean containsKey(Object key) {
946 >        return get(key) != null;
947 >    }
948  
949 <        /**
950 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
951 <         * read-lock to call getTreeNode, but during failure to get
952 <         * lock, searches along next links.
953 <         */
954 <        final V getValue(int h, Object k) {
955 <            Node<V> r = null;
956 <            int c = getState(); // Must read lock state first
957 <            for (Node<V> e = first; e != null; e = e.next) {
958 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
959 <                    try {
960 <                        r = getTreeNode(h, k, root);
961 <                    } finally {
962 <                        releaseShared(0);
963 <                    }
964 <                    break;
965 <                }
966 <                else if (e.hash == h && k.equals(e.key)) {
967 <                    r = e;
968 <                    break;
871 <                }
872 <                else
873 <                    c = getState();
949 >    /**
950 >     * Returns {@code true} if this map maps one or more keys to the
951 >     * specified value. Note: This method may require a full traversal
952 >     * of the map, and is much slower than method {@code containsKey}.
953 >     *
954 >     * @param value value whose presence in this map is to be tested
955 >     * @return {@code true} if this map maps one or more keys to the
956 >     *         specified value
957 >     * @throws NullPointerException if the specified value is null
958 >     */
959 >    public boolean containsValue(Object value) {
960 >        if (value == null)
961 >            throw new NullPointerException();
962 >        Node<K,V>[] t;
963 >        if ((t = table) != null) {
964 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
965 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
966 >                V v;
967 >                if ((v = p.val) == value || (v != null && value.equals(v)))
968 >                    return true;
969              }
875            return r == null ? null : r.val;
970          }
971 +        return false;
972 +    }
973  
974 <        /**
975 <         * Finds or adds a node.
976 <         * @return null if added
977 <         */
978 <        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
979 <            (int h, Object k, V v) {
980 <            Class<?> c = k.getClass();
981 <            TreeNode<V> pp = root, p = null;
982 <            int dir = 0;
983 <            while (pp != null) { // find existing node or leaf to insert at
984 <                int ph;  Object pk; Class<?> pc;
985 <                p = pp;
986 <                if ((ph = p.hash) == h) {
987 <                    if ((pk = p.key) == k || k.equals(pk))
988 <                        return p;
989 <                    if (c != (pc = pk.getClass()) ||
894 <                        !(k instanceof Comparable) ||
895 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
896 <                        TreeNode<V> s = null, r = null, pr;
897 <                        if ((dir = (c == pc) ? 0 :
898 <                             c.getName().compareTo(pc.getName())) == 0) {
899 <                            if ((pr = p.right) != null && h >= pr.hash &&
900 <                                (r = getTreeNode(h, k, pr)) != null)
901 <                                return r;
902 <                            else // continue left
903 <                                dir = -1;
904 <                        }
905 <                        else if ((pr = p.right) != null && h >= pr.hash)
906 <                            s = pr;
907 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
908 <                            return r;
909 <                    }
910 <                }
911 <                else
912 <                    dir = (h < ph) ? -1 : 1;
913 <                pp = (dir > 0) ? p.right : p.left;
914 <            }
915 <
916 <            TreeNode<V> f = first;
917 <            TreeNode<V> x = first = new TreeNode<V>(h, k, v, f, p);
918 <            if (p == null)
919 <                root = x;
920 <            else { // attach and rebalance; adapted from CLR
921 <                TreeNode<V> xp, xpp;
922 <                if (f != null)
923 <                    f.prev = x;
924 <                if (dir <= 0)
925 <                    p.left = x;
926 <                else
927 <                    p.right = x;
928 <                x.red = true;
929 <                while (x != null && (xp = x.parent) != null && xp.red &&
930 <                       (xpp = xp.parent) != null) {
931 <                    TreeNode<V> xppl = xpp.left;
932 <                    if (xp == xppl) {
933 <                        TreeNode<V> y = xpp.right;
934 <                        if (y != null && y.red) {
935 <                            y.red = false;
936 <                            xp.red = false;
937 <                            xpp.red = true;
938 <                            x = xpp;
939 <                        }
940 <                        else {
941 <                            if (x == xp.right) {
942 <                                rotateLeft(x = xp);
943 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
944 <                            }
945 <                            if (xp != null) {
946 <                                xp.red = false;
947 <                                if (xpp != null) {
948 <                                    xpp.red = true;
949 <                                    rotateRight(xpp);
950 <                                }
951 <                            }
952 <                        }
953 <                    }
954 <                    else {
955 <                        TreeNode<V> y = xppl;
956 <                        if (y != null && y.red) {
957 <                            y.red = false;
958 <                            xp.red = false;
959 <                            xpp.red = true;
960 <                            x = xpp;
961 <                        }
962 <                        else {
963 <                            if (x == xp.left) {
964 <                                rotateRight(x = xp);
965 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
966 <                            }
967 <                            if (xp != null) {
968 <                                xp.red = false;
969 <                                if (xpp != null) {
970 <                                    xpp.red = true;
971 <                                    rotateLeft(xpp);
972 <                                }
973 <                            }
974 <                        }
975 <                    }
976 <                }
977 <                TreeNode<V> r = root;
978 <                if (r != null && r.red)
979 <                    r.red = false;
980 <            }
981 <            return null;
982 <        }
974 >    /**
975 >     * Maps the specified key to the specified value in this table.
976 >     * Neither the key nor the value can be null.
977 >     *
978 >     * <p>The value can be retrieved by calling the {@code get} method
979 >     * with a key that is equal to the original key.
980 >     *
981 >     * @param key key with which the specified value is to be associated
982 >     * @param value value to be associated with the specified key
983 >     * @return the previous value associated with {@code key}, or
984 >     *         {@code null} if there was no mapping for {@code key}
985 >     * @throws NullPointerException if the specified key or value is null
986 >     */
987 >    public V put(K key, V value) {
988 >        return putVal(key, value, false);
989 >    }
990  
991 <        /**
992 <         * Removes the given node, that must be present before this
993 <         * call.  This is messier than typical red-black deletion code
994 <         * because we cannot swap the contents of an interior node
995 <         * with a leaf successor that is pinned by "next" pointers
996 <         * that are accessible independently of lock. So instead we
997 <         * swap the tree linkages.
998 <         */
999 <        final void deleteTreeNode(TreeNode<V> p) {
1000 <            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
1001 <            TreeNode<V> pred = p.prev;
1002 <            if (pred == null)
1003 <                first = next;
997 <            else
998 <                pred.next = next;
999 <            if (next != null)
1000 <                next.prev = pred;
1001 <            TreeNode<V> replacement;
1002 <            TreeNode<V> pl = p.left;
1003 <            TreeNode<V> pr = p.right;
1004 <            if (pl != null && pr != null) {
1005 <                TreeNode<V> s = pr, sl;
1006 <                while ((sl = s.left) != null) // find successor
1007 <                    s = sl;
1008 <                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
1009 <                TreeNode<V> sr = s.right;
1010 <                TreeNode<V> pp = p.parent;
1011 <                if (s == pr) { // p was s's direct parent
1012 <                    p.parent = s;
1013 <                    s.right = p;
1014 <                }
1015 <                else {
1016 <                    TreeNode<V> sp = s.parent;
1017 <                    if ((p.parent = sp) != null) {
1018 <                        if (s == sp.left)
1019 <                            sp.left = p;
1020 <                        else
1021 <                            sp.right = p;
1022 <                    }
1023 <                    if ((s.right = pr) != null)
1024 <                        pr.parent = s;
1025 <                }
1026 <                p.left = null;
1027 <                if ((p.right = sr) != null)
1028 <                    sr.parent = p;
1029 <                if ((s.left = pl) != null)
1030 <                    pl.parent = s;
1031 <                if ((s.parent = pp) == null)
1032 <                    root = s;
1033 <                else if (p == pp.left)
1034 <                    pp.left = s;
1035 <                else
1036 <                    pp.right = s;
1037 <                replacement = sr;
1038 <            }
1039 <            else
1040 <                replacement = (pl != null) ? pl : pr;
1041 <            TreeNode<V> pp = p.parent;
1042 <            if (replacement == null) {
1043 <                if (pp == null) {
1044 <                    root = null;
1045 <                    return;
1046 <                }
1047 <                replacement = p;
991 >    /** Implementation for put and putIfAbsent */
992 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
993 >        if (key == null || value == null) throw new NullPointerException();
994 >        int hash = spread(key.hashCode());
995 >        int binCount = 0;
996 >        for (Node<K,V>[] tab = table;;) {
997 >            Node<K,V> f; int n, i, fh;
998 >            if (tab == null || (n = tab.length) == 0)
999 >                tab = initTable();
1000 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
1001 >                if (casTabAt(tab, i, null,
1002 >                             new Node<K,V>(hash, key, value, null)))
1003 >                    break;                   // no lock when adding to empty bin
1004              }
1005 +            else if ((fh = f.hash) == MOVED)
1006 +                tab = helpTransfer(tab, f);
1007              else {
1008 <                replacement.parent = pp;
1009 <                if (pp == null)
1010 <                    root = replacement;
1011 <                else if (p == pp.left)
1012 <                    pp.left = replacement;
1013 <                else
1014 <                    pp.right = replacement;
1015 <                p.left = p.right = p.parent = null;
1016 <            }
1017 <            if (!p.red) { // rebalance, from CLR
1018 <                TreeNode<V> x = replacement;
1019 <                while (x != null) {
1020 <                    TreeNode<V> xp, xpl;
1021 <                    if (x.red || (xp = x.parent) == null) {
1064 <                        x.red = false;
1065 <                        break;
1066 <                    }
1067 <                    if (x == (xpl = xp.left)) {
1068 <                        TreeNode<V> sib = xp.right;
1069 <                        if (sib != null && sib.red) {
1070 <                            sib.red = false;
1071 <                            xp.red = true;
1072 <                            rotateLeft(xp);
1073 <                            sib = (xp = x.parent) == null ? null : xp.right;
1074 <                        }
1075 <                        if (sib == null)
1076 <                            x = xp;
1077 <                        else {
1078 <                            TreeNode<V> sl = sib.left, sr = sib.right;
1079 <                            if ((sr == null || !sr.red) &&
1080 <                                (sl == null || !sl.red)) {
1081 <                                sib.red = true;
1082 <                                x = xp;
1083 <                            }
1084 <                            else {
1085 <                                if (sr == null || !sr.red) {
1086 <                                    if (sl != null)
1087 <                                        sl.red = false;
1088 <                                    sib.red = true;
1089 <                                    rotateRight(sib);
1090 <                                    sib = (xp = x.parent) == null ?
1091 <                                        null : xp.right;
1092 <                                }
1093 <                                if (sib != null) {
1094 <                                    sib.red = (xp == null) ? false : xp.red;
1095 <                                    if ((sr = sib.right) != null)
1096 <                                        sr.red = false;
1008 >                V oldVal = null;
1009 >                synchronized (f) {
1010 >                    if (tabAt(tab, i) == f) {
1011 >                        if (fh >= 0) {
1012 >                            binCount = 1;
1013 >                            for (Node<K,V> e = f;; ++binCount) {
1014 >                                K ek;
1015 >                                if (e.hash == hash &&
1016 >                                    ((ek = e.key) == key ||
1017 >                                     (ek != null && key.equals(ek)))) {
1018 >                                    oldVal = e.val;
1019 >                                    if (!onlyIfAbsent)
1020 >                                        e.val = value;
1021 >                                    break;
1022                                  }
1023 <                                if (xp != null) {
1024 <                                    xp.red = false;
1025 <                                    rotateLeft(xp);
1023 >                                Node<K,V> pred = e;
1024 >                                if ((e = e.next) == null) {
1025 >                                    pred.next = new Node<K,V>(hash, key,
1026 >                                                              value, null);
1027 >                                    break;
1028                                  }
1102                                x = root;
1029                              }
1030                          }
1031 <                    }
1032 <                    else { // symmetric
1033 <                        TreeNode<V> sib = xpl;
1034 <                        if (sib != null && sib.red) {
1035 <                            sib.red = false;
1036 <                            xp.red = true;
1037 <                            rotateRight(xp);
1038 <                            sib = (xp = x.parent) == null ? null : xp.left;
1113 <                        }
1114 <                        if (sib == null)
1115 <                            x = xp;
1116 <                        else {
1117 <                            TreeNode<V> sl = sib.left, sr = sib.right;
1118 <                            if ((sl == null || !sl.red) &&
1119 <                                (sr == null || !sr.red)) {
1120 <                                sib.red = true;
1121 <                                x = xp;
1122 <                            }
1123 <                            else {
1124 <                                if (sl == null || !sl.red) {
1125 <                                    if (sr != null)
1126 <                                        sr.red = false;
1127 <                                    sib.red = true;
1128 <                                    rotateLeft(sib);
1129 <                                    sib = (xp = x.parent) == null ?
1130 <                                        null : xp.left;
1131 <                                }
1132 <                                if (sib != null) {
1133 <                                    sib.red = (xp == null) ? false : xp.red;
1134 <                                    if ((sl = sib.left) != null)
1135 <                                        sl.red = false;
1136 <                                }
1137 <                                if (xp != null) {
1138 <                                    xp.red = false;
1139 <                                    rotateRight(xp);
1140 <                                }
1141 <                                x = root;
1031 >                        else if (f instanceof TreeBin) {
1032 >                            Node<K,V> p;
1033 >                            binCount = 2;
1034 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1035 >                                                           value)) != null) {
1036 >                                oldVal = p.val;
1037 >                                if (!onlyIfAbsent)
1038 >                                    p.val = value;
1039                              }
1040                          }
1041                      }
1042                  }
1043 <            }
1044 <            if (p == replacement && (pp = p.parent) != null) {
1045 <                if (p == pp.left) // detach pointers
1046 <                    pp.left = null;
1047 <                else if (p == pp.right)
1048 <                    pp.right = null;
1049 <                p.parent = null;
1043 >                if (binCount != 0) {
1044 >                    if (binCount >= TREEIFY_THRESHOLD)
1045 >                        treeifyBin(tab, i);
1046 >                    if (oldVal != null)
1047 >                        return oldVal;
1048 >                    break;
1049 >                }
1050              }
1051          }
1052 +        addCount(1L, binCount);
1053 +        return null;
1054      }
1055  
1157    /* ---------------- Collision reduction methods -------------- */
1158
1056      /**
1057 <     * Spreads higher bits to lower, and also forces top bit to 0.
1058 <     * Because the table uses power-of-two masking, sets of hashes
1059 <     * that vary only in bits above the current mask will always
1060 <     * collide. (Among known examples are sets of Float keys holding
1061 <     * consecutive whole numbers in small tables.)  To counter this,
1165 <     * we apply a transform that spreads the impact of higher bits
1166 <     * downward. There is a tradeoff between speed, utility, and
1167 <     * quality of bit-spreading. Because many common sets of hashes
1168 <     * are already reasonably distributed across bits (so don't benefit
1169 <     * from spreading), and because we use trees to handle large sets
1170 <     * of collisions in bins, we don't need excessively high quality.
1057 >     * Copies all of the mappings from the specified map to this one.
1058 >     * These mappings replace any mappings that this map had for any of the
1059 >     * keys currently in the specified map.
1060 >     *
1061 >     * @param m mappings to be stored in this map
1062       */
1063 <    private static final int spread(int h) {
1064 <        h ^= (h >>> 18) ^ (h >>> 12);
1065 <        return (h ^ (h >>> 10)) & HASH_BITS;
1063 >    public void putAll(Map<? extends K, ? extends V> m) {
1064 >        tryPresize(m.size());
1065 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1066 >            putVal(e.getKey(), e.getValue(), false);
1067      }
1068  
1069      /**
1070 <     * Replaces a list bin with a tree bin if key is comparable.  Call
1071 <     * only when locked.
1070 >     * Removes the key (and its corresponding value) from this map.
1071 >     * This method does nothing if the key is not in the map.
1072 >     *
1073 >     * @param  key the key that needs to be removed
1074 >     * @return the previous value associated with {@code key}, or
1075 >     *         {@code null} if there was no mapping for {@code key}
1076 >     * @throws NullPointerException if the specified key is null
1077       */
1078 <    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1079 <        if (key instanceof Comparable) {
1183 <            TreeBin<V> t = new TreeBin<V>();
1184 <            for (Node<V> e = tabAt(tab, index); e != null; e = e.next)
1185 <                t.putTreeNode(e.hash, e.key, e.val);
1186 <            setTabAt(tab, index, new Node<V>(MOVED, t, null, null));
1187 <        }
1188 <    }
1189 <
1190 <    /* ---------------- Internal access and update methods -------------- */
1191 <
1192 <    /** Implementation for get and containsKey */
1193 <    @SuppressWarnings("unchecked") private final V internalGet(Object k) {
1194 <        int h = spread(k.hashCode());
1195 <        retry: for (Node<V>[] tab = table; tab != null;) {
1196 <            Node<V> e; Object ek; V ev; int eh; // locals to read fields once
1197 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1198 <                if ((eh = e.hash) < 0) {
1199 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1200 <                        return ((TreeBin<V>)ek).getValue(h, k);
1201 <                    else {                      // restart with new table
1202 <                        tab = (Node<V>[])ek;
1203 <                        continue retry;
1204 <                    }
1205 <                }
1206 <                else if (eh == h && (ev = e.val) != null &&
1207 <                         ((ek = e.key) == k || k.equals(ek)))
1208 <                    return ev;
1209 <            }
1210 <            break;
1211 <        }
1212 <        return null;
1078 >    public V remove(Object key) {
1079 >        return replaceNode(key, null, null);
1080      }
1081  
1082      /**
# Line 1217 | Line 1084 | public class ConcurrentHashMapV8<K,V>
1084       * Replaces node value with v, conditional upon match of cv if
1085       * non-null.  If resulting value is null, delete.
1086       */
1087 <    @SuppressWarnings("unchecked") private final V internalReplace
1088 <        (Object k, V v, Object cv) {
1089 <        int h = spread(k.hashCode());
1090 <        V oldVal = null;
1091 <        for (Node<V>[] tab = table;;) {
1092 <            Node<V> f; int i, fh; Object fk;
1226 <            if (tab == null ||
1227 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1087 >    final V replaceNode(Object key, V value, Object cv) {
1088 >        int hash = spread(key.hashCode());
1089 >        for (Node<K,V>[] tab = table;;) {
1090 >            Node<K,V> f; int n, i, fh;
1091 >            if (tab == null || (n = tab.length) == 0 ||
1092 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1093                  break;
1094 <            else if ((fh = f.hash) < 0) {
1095 <                if ((fk = f.key) instanceof TreeBin) {
1096 <                    TreeBin<V> t = (TreeBin<V>)fk;
1097 <                    boolean validated = false;
1098 <                    boolean deleted = false;
1099 <                    t.acquire(0);
1100 <                    try {
1101 <                        if (tabAt(tab, i) == f) {
1094 >            else if ((fh = f.hash) == MOVED)
1095 >                tab = helpTransfer(tab, f);
1096 >            else {
1097 >                V oldVal = null;
1098 >                boolean validated = false;
1099 >                synchronized (f) {
1100 >                    if (tabAt(tab, i) == f) {
1101 >                        if (fh >= 0) {
1102 >                            validated = true;
1103 >                            for (Node<K,V> e = f, pred = null;;) {
1104 >                                K ek;
1105 >                                if (e.hash == hash &&
1106 >                                    ((ek = e.key) == key ||
1107 >                                     (ek != null && key.equals(ek)))) {
1108 >                                    V ev = e.val;
1109 >                                    if (cv == null || cv == ev ||
1110 >                                        (ev != null && cv.equals(ev))) {
1111 >                                        oldVal = ev;
1112 >                                        if (value != null)
1113 >                                            e.val = value;
1114 >                                        else if (pred != null)
1115 >                                            pred.next = e.next;
1116 >                                        else
1117 >                                            setTabAt(tab, i, e.next);
1118 >                                    }
1119 >                                    break;
1120 >                                }
1121 >                                pred = e;
1122 >                                if ((e = e.next) == null)
1123 >                                    break;
1124 >                            }
1125 >                        }
1126 >                        else if (f instanceof TreeBin) {
1127                              validated = true;
1128 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1129 <                            if (p != null) {
1128 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1129 >                            TreeNode<K,V> r, p;
1130 >                            if ((r = t.root) != null &&
1131 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1132                                  V pv = p.val;
1133 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1133 >                                if (cv == null || cv == pv ||
1134 >                                    (pv != null && cv.equals(pv))) {
1135                                      oldVal = pv;
1136 <                                    if ((p.val = v) == null) {
1137 <                                        deleted = true;
1138 <                                        t.deleteTreeNode(p);
1139 <                                    }
1136 >                                    if (value != null)
1137 >                                        p.val = value;
1138 >                                    else if (t.removeTreeNode(p))
1139 >                                        setTabAt(tab, i, untreeify(t.first));
1140                                  }
1141                              }
1142                          }
1250                    } finally {
1251                        t.release(0);
1143                      }
1144 <                    if (validated) {
1145 <                        if (deleted)
1144 >                }
1145 >                if (validated) {
1146 >                    if (oldVal != null) {
1147 >                        if (value == null)
1148                              addCount(-1L, -1);
1149 <                        break;
1149 >                        return oldVal;
1150                      }
1151 +                    break;
1152                  }
1259                else
1260                    tab = (Node<V>[])fk;
1153              }
1154 <            else if (fh != h && f.next == null) // precheck
1155 <                break;                          // rules out possible existence
1154 >        }
1155 >        return null;
1156 >    }
1157 >
1158 >    /**
1159 >     * Removes all of the mappings from this map.
1160 >     */
1161 >    public void clear() {
1162 >        long delta = 0L; // negative number of deletions
1163 >        int i = 0;
1164 >        Node<K,V>[] tab = table;
1165 >        while (tab != null && i < tab.length) {
1166 >            int fh;
1167 >            Node<K,V> f = tabAt(tab, i);
1168 >            if (f == null)
1169 >                ++i;
1170 >            else if ((fh = f.hash) == MOVED) {
1171 >                tab = helpTransfer(tab, f);
1172 >                i = 0; // restart
1173 >            }
1174              else {
1265                boolean validated = false;
1266                boolean deleted = false;
1175                  synchronized (f) {
1176                      if (tabAt(tab, i) == f) {
1177 <                        validated = true;
1178 <                        for (Node<V> e = f, pred = null;;) {
1179 <                            Object ek; V ev;
1180 <                            if (e.hash == h &&
1181 <                                ((ev = e.val) != null) &&
1182 <                                ((ek = e.key) == k || k.equals(ek))) {
1275 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1276 <                                    oldVal = ev;
1277 <                                    if ((e.val = v) == null) {
1278 <                                        deleted = true;
1279 <                                        Node<V> en = e.next;
1280 <                                        if (pred != null)
1281 <                                            pred.next = en;
1282 <                                        else
1283 <                                            setTabAt(tab, i, en);
1284 <                                    }
1285 <                                }
1286 <                                break;
1287 <                            }
1288 <                            pred = e;
1289 <                            if ((e = e.next) == null)
1290 <                                break;
1177 >                        Node<K,V> p = (fh >= 0 ? f :
1178 >                                       (f instanceof TreeBin) ?
1179 >                                       ((TreeBin<K,V>)f).first : null);
1180 >                        while (p != null) {
1181 >                            --delta;
1182 >                            p = p.next;
1183                          }
1184 +                        setTabAt(tab, i++, null);
1185                      }
1186                  }
1187 <                if (validated) {
1188 <                    if (deleted)
1189 <                        addCount(-1L, -1);
1187 >            }
1188 >        }
1189 >        if (delta != 0L)
1190 >            addCount(delta, -1);
1191 >    }
1192 >
1193 >    /**
1194 >     * Returns a {@link Set} view of the keys contained in this map.
1195 >     * The set is backed by the map, so changes to the map are
1196 >     * reflected in the set, and vice-versa. The set supports element
1197 >     * removal, which removes the corresponding mapping from this map,
1198 >     * via the {@code Iterator.remove}, {@code Set.remove},
1199 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1200 >     * operations.  It does not support the {@code add} or
1201 >     * {@code addAll} operations.
1202 >     *
1203 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1204 >     * that will never throw {@link ConcurrentModificationException},
1205 >     * and guarantees to traverse elements as they existed upon
1206 >     * construction of the iterator, and may (but is not guaranteed to)
1207 >     * reflect any modifications subsequent to construction.
1208 >     *
1209 >     * @return the set view
1210 >     */
1211 >    public KeySetView<K,V> keySet() {
1212 >        KeySetView<K,V> ks;
1213 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1214 >    }
1215 >
1216 >    /**
1217 >     * Returns a {@link Collection} view of the values contained in this map.
1218 >     * The collection is backed by the map, so changes to the map are
1219 >     * reflected in the collection, and vice-versa.  The collection
1220 >     * supports element removal, which removes the corresponding
1221 >     * mapping from this map, via the {@code Iterator.remove},
1222 >     * {@code Collection.remove}, {@code removeAll},
1223 >     * {@code retainAll}, and {@code clear} operations.  It does not
1224 >     * support the {@code add} or {@code addAll} operations.
1225 >     *
1226 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1227 >     * that will never throw {@link ConcurrentModificationException},
1228 >     * and guarantees to traverse elements as they existed upon
1229 >     * construction of the iterator, and may (but is not guaranteed to)
1230 >     * reflect any modifications subsequent to construction.
1231 >     *
1232 >     * @return the collection view
1233 >     */
1234 >    public Collection<V> values() {
1235 >        ValuesView<K,V> vs;
1236 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1237 >    }
1238 >
1239 >    /**
1240 >     * Returns a {@link Set} view of the mappings contained in this map.
1241 >     * The set is backed by the map, so changes to the map are
1242 >     * reflected in the set, and vice-versa.  The set supports element
1243 >     * removal, which removes the corresponding mapping from the map,
1244 >     * via the {@code Iterator.remove}, {@code Set.remove},
1245 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1246 >     * operations.
1247 >     *
1248 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1249 >     * that will never throw {@link ConcurrentModificationException},
1250 >     * and guarantees to traverse elements as they existed upon
1251 >     * construction of the iterator, and may (but is not guaranteed to)
1252 >     * reflect any modifications subsequent to construction.
1253 >     *
1254 >     * @return the set view
1255 >     */
1256 >    public Set<Map.Entry<K,V>> entrySet() {
1257 >        EntrySetView<K,V> es;
1258 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1259 >    }
1260 >
1261 >    /**
1262 >     * Returns the hash code value for this {@link Map}, i.e.,
1263 >     * the sum of, for each key-value pair in the map,
1264 >     * {@code key.hashCode() ^ value.hashCode()}.
1265 >     *
1266 >     * @return the hash code value for this map
1267 >     */
1268 >    public int hashCode() {
1269 >        int h = 0;
1270 >        Node<K,V>[] t;
1271 >        if ((t = table) != null) {
1272 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1273 >            for (Node<K,V> p; (p = it.advance()) != null; )
1274 >                h += p.key.hashCode() ^ p.val.hashCode();
1275 >        }
1276 >        return h;
1277 >    }
1278 >
1279 >    /**
1280 >     * Returns a string representation of this map.  The string
1281 >     * representation consists of a list of key-value mappings (in no
1282 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1283 >     * mappings are separated by the characters {@code ", "} (comma
1284 >     * and space).  Each key-value mapping is rendered as the key
1285 >     * followed by an equals sign ("{@code =}") followed by the
1286 >     * associated value.
1287 >     *
1288 >     * @return a string representation of this map
1289 >     */
1290 >    public String toString() {
1291 >        Node<K,V>[] t;
1292 >        int f = (t = table) == null ? 0 : t.length;
1293 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1294 >        StringBuilder sb = new StringBuilder();
1295 >        sb.append('{');
1296 >        Node<K,V> p;
1297 >        if ((p = it.advance()) != null) {
1298 >            for (;;) {
1299 >                K k = p.key;
1300 >                V v = p.val;
1301 >                sb.append(k == this ? "(this Map)" : k);
1302 >                sb.append('=');
1303 >                sb.append(v == this ? "(this Map)" : v);
1304 >                if ((p = it.advance()) == null)
1305                      break;
1306 <                }
1306 >                sb.append(',').append(' ');
1307              }
1308          }
1309 <        return oldVal;
1309 >        return sb.append('}').toString();
1310      }
1311  
1312 <    /*
1313 <     * Internal versions of insertion methods
1314 <     * All have the same basic structure as the first (internalPut):
1315 <     *  1. If table uninitialized, create
1316 <     *  2. If bin empty, try to CAS new node
1317 <     *  3. If bin stale, use new table
1318 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1319 <     *  5. Lock and validate; if valid, scan and add or update
1320 <     *
1313 <     * The putAll method differs mainly in attempting to pre-allocate
1314 <     * enough table space, and also more lazily performs count updates
1315 <     * and checks.
1316 <     *
1317 <     * Most of the function-accepting methods can't be factored nicely
1318 <     * because they require different functional forms, so instead
1319 <     * sprawl out similar mechanics.
1312 >    /**
1313 >     * Compares the specified object with this map for equality.
1314 >     * Returns {@code true} if the given object is a map with the same
1315 >     * mappings as this map.  This operation may return misleading
1316 >     * results if either map is concurrently modified during execution
1317 >     * of this method.
1318 >     *
1319 >     * @param o object to be compared for equality with this map
1320 >     * @return {@code true} if the specified object is equal to this map
1321       */
1322 +    public boolean equals(Object o) {
1323 +        if (o != this) {
1324 +            if (!(o instanceof Map))
1325 +                return false;
1326 +            Map<?,?> m = (Map<?,?>) o;
1327 +            Node<K,V>[] t;
1328 +            int f = (t = table) == null ? 0 : t.length;
1329 +            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1330 +            for (Node<K,V> p; (p = it.advance()) != null; ) {
1331 +                V val = p.val;
1332 +                Object v = m.get(p.key);
1333 +                if (v == null || (v != val && !v.equals(val)))
1334 +                    return false;
1335 +            }
1336 +            for (Map.Entry<?,?> e : m.entrySet()) {
1337 +                Object mk, mv, v;
1338 +                if ((mk = e.getKey()) == null ||
1339 +                    (mv = e.getValue()) == null ||
1340 +                    (v = get(mk)) == null ||
1341 +                    (mv != v && !mv.equals(v)))
1342 +                    return false;
1343 +            }
1344 +        }
1345 +        return true;
1346 +    }
1347  
1348 <    /** Implementation for put and putIfAbsent */
1349 <    @SuppressWarnings("unchecked") private final V internalPut
1350 <        (K k, V v, boolean onlyIfAbsent) {
1351 <        if (k == null || v == null) throw new NullPointerException();
1352 <        int h = spread(k.hashCode());
1353 <        int len = 0;
1354 <        for (Node<V>[] tab = table;;) {
1355 <            int i, fh; Node<V> f; Object fk; V fv;
1356 <            if (tab == null)
1357 <                tab = initTable();
1358 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1359 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1360 <                    break;                   // no lock when adding to empty bin
1348 >    /**
1349 >     * Stripped-down version of helper class used in previous version,
1350 >     * declared for the sake of serialization compatibility
1351 >     */
1352 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1353 >        private static final long serialVersionUID = 2249069246763182397L;
1354 >        final float loadFactor;
1355 >        Segment(float lf) { this.loadFactor = lf; }
1356 >    }
1357 >
1358 >    /**
1359 >     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
1360 >     * stream (i.e., serializes it).
1361 >     * @param s the stream
1362 >     * @serialData
1363 >     * the key (Object) and value (Object)
1364 >     * for each key-value mapping, followed by a null pair.
1365 >     * The key-value mappings are emitted in no particular order.
1366 >     */
1367 >    private void writeObject(java.io.ObjectOutputStream s)
1368 >        throws java.io.IOException {
1369 >        // For serialization compatibility
1370 >        // Emulate segment calculation from previous version of this class
1371 >        int sshift = 0;
1372 >        int ssize = 1;
1373 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1374 >            ++sshift;
1375 >            ssize <<= 1;
1376 >        }
1377 >        int segmentShift = 32 - sshift;
1378 >        int segmentMask = ssize - 1;
1379 >        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1380 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1381 >        for (int i = 0; i < segments.length; ++i)
1382 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1383 >        s.putFields().put("segments", segments);
1384 >        s.putFields().put("segmentShift", segmentShift);
1385 >        s.putFields().put("segmentMask", segmentMask);
1386 >        s.writeFields();
1387 >
1388 >        Node<K,V>[] t;
1389 >        if ((t = table) != null) {
1390 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1391 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1392 >                s.writeObject(p.key);
1393 >                s.writeObject(p.val);
1394              }
1395 <            else if ((fh = f.hash) < 0) {
1396 <                if ((fk = f.key) instanceof TreeBin) {
1397 <                    TreeBin<V> t = (TreeBin<V>)fk;
1398 <                    V oldVal = null;
1399 <                    t.acquire(0);
1400 <                    try {
1401 <                        if (tabAt(tab, i) == f) {
1402 <                            len = 2;
1403 <                            TreeNode<V> p = t.putTreeNode(h, k, v);
1404 <                            if (p != null) {
1405 <                                oldVal = p.val;
1406 <                                if (!onlyIfAbsent)
1407 <                                    p.val = v;
1408 <                            }
1409 <                        }
1410 <                    } finally {
1411 <                        t.release(0);
1412 <                    }
1413 <                    if (len != 0) {
1414 <                        if (oldVal != null)
1415 <                            return oldVal;
1416 <                        break;
1417 <                    }
1418 <                }
1419 <                else
1420 <                    tab = (Node<V>[])fk;
1395 >        }
1396 >        s.writeObject(null);
1397 >        s.writeObject(null);
1398 >        segments = null; // throw away
1399 >    }
1400 >
1401 >    /**
1402 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1403 >     * @param s the stream
1404 >     */
1405 >    private void readObject(java.io.ObjectInputStream s)
1406 >        throws java.io.IOException, ClassNotFoundException {
1407 >        /*
1408 >         * To improve performance in typical cases, we create nodes
1409 >         * while reading, then place in table once size is known.
1410 >         * However, we must also validate uniqueness and deal with
1411 >         * overpopulated bins while doing so, which requires
1412 >         * specialized versions of putVal mechanics.
1413 >         */
1414 >        sizeCtl = -1; // force exclusion for table construction
1415 >        s.defaultReadObject();
1416 >        long size = 0L;
1417 >        Node<K,V> p = null;
1418 >        for (;;) {
1419 >            @SuppressWarnings("unchecked") K k = (K) s.readObject();
1420 >            @SuppressWarnings("unchecked") V v = (V) s.readObject();
1421 >            if (k != null && v != null) {
1422 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1423 >                ++size;
1424              }
1425 <            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1426 <                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1427 <                return fv;
1425 >            else
1426 >                break;
1427 >        }
1428 >        if (size == 0L)
1429 >            sizeCtl = 0;
1430 >        else {
1431 >            int n;
1432 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1433 >                n = MAXIMUM_CAPACITY;
1434              else {
1435 <                V oldVal = null;
1436 <                synchronized (f) {
1437 <                    if (tabAt(tab, i) == f) {
1438 <                        len = 1;
1439 <                        for (Node<V> e = f;; ++len) {
1440 <                            Object ek; V ev;
1441 <                            if (e.hash == h &&
1442 <                                (ev = e.val) != null &&
1443 <                                ((ek = e.key) == k || k.equals(ek))) {
1444 <                                oldVal = ev;
1445 <                                if (!onlyIfAbsent)
1446 <                                    e.val = v;
1435 >                int sz = (int)size;
1436 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1437 >            }
1438 >            @SuppressWarnings({"rawtypes","unchecked"})
1439 >                Node<K,V>[] tab = (Node<K,V>[])new Node[n];
1440 >            int mask = n - 1;
1441 >            long added = 0L;
1442 >            while (p != null) {
1443 >                boolean insertAtFront;
1444 >                Node<K,V> next = p.next, first;
1445 >                int h = p.hash, j = h & mask;
1446 >                if ((first = tabAt(tab, j)) == null)
1447 >                    insertAtFront = true;
1448 >                else {
1449 >                    K k = p.key;
1450 >                    if (first.hash < 0) {
1451 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1452 >                        if (t.putTreeVal(h, k, p.val) == null)
1453 >                            ++added;
1454 >                        insertAtFront = false;
1455 >                    }
1456 >                    else {
1457 >                        int binCount = 0;
1458 >                        insertAtFront = true;
1459 >                        Node<K,V> q; K qk;
1460 >                        for (q = first; q != null; q = q.next) {
1461 >                            if (q.hash == h &&
1462 >                                ((qk = q.key) == k ||
1463 >                                 (qk != null && k.equals(qk)))) {
1464 >                                insertAtFront = false;
1465                                  break;
1466                              }
1467 <                            Node<V> last = e;
1468 <                            if ((e = e.next) == null) {
1469 <                                last.next = new Node<V>(h, k, v, null);
1470 <                                if (len >= TREE_THRESHOLD)
1471 <                                    replaceWithTreeBin(tab, i, k);
1472 <                                break;
1467 >                            ++binCount;
1468 >                        }
1469 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1470 >                            insertAtFront = false;
1471 >                            ++added;
1472 >                            p.next = first;
1473 >                            TreeNode<K,V> hd = null, tl = null;
1474 >                            for (q = p; q != null; q = q.next) {
1475 >                                TreeNode<K,V> t = new TreeNode<K,V>
1476 >                                    (q.hash, q.key, q.val, null, null);
1477 >                                if ((t.prev = tl) == null)
1478 >                                    hd = t;
1479 >                                else
1480 >                                    tl.next = t;
1481 >                                tl = t;
1482                              }
1483 +                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1484                          }
1485                      }
1486                  }
1487 <                if (len != 0) {
1488 <                    if (oldVal != null)
1489 <                        return oldVal;
1490 <                    break;
1487 >                if (insertAtFront) {
1488 >                    ++added;
1489 >                    p.next = first;
1490 >                    setTabAt(tab, j, p);
1491                  }
1492 +                p = next;
1493              }
1494 +            table = tab;
1495 +            sizeCtl = n - (n >>> 2);
1496 +            baseCount = added;
1497          }
1398        addCount(1L, len);
1399        return null;
1498      }
1499  
1500 <    /** Implementation for computeIfAbsent */
1501 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1502 <        (K k, Fun<? super K, ? extends V> mf) {
1503 <        if (k == null || mf == null)
1500 >    // ConcurrentMap methods
1501 >
1502 >    /**
1503 >     * {@inheritDoc}
1504 >     *
1505 >     * @return the previous value associated with the specified key,
1506 >     *         or {@code null} if there was no mapping for the key
1507 >     * @throws NullPointerException if the specified key or value is null
1508 >     */
1509 >    public V putIfAbsent(K key, V value) {
1510 >        return putVal(key, value, true);
1511 >    }
1512 >
1513 >    /**
1514 >     * {@inheritDoc}
1515 >     *
1516 >     * @throws NullPointerException if the specified key is null
1517 >     */
1518 >    public boolean remove(Object key, Object value) {
1519 >        if (key == null)
1520              throw new NullPointerException();
1521 <        int h = spread(k.hashCode());
1521 >        return value != null && replaceNode(key, null, value) != null;
1522 >    }
1523 >
1524 >    /**
1525 >     * {@inheritDoc}
1526 >     *
1527 >     * @throws NullPointerException if any of the arguments are null
1528 >     */
1529 >    public boolean replace(K key, V oldValue, V newValue) {
1530 >        if (key == null || oldValue == null || newValue == null)
1531 >            throw new NullPointerException();
1532 >        return replaceNode(key, newValue, oldValue) != null;
1533 >    }
1534 >
1535 >    /**
1536 >     * {@inheritDoc}
1537 >     *
1538 >     * @return the previous value associated with the specified key,
1539 >     *         or {@code null} if there was no mapping for the key
1540 >     * @throws NullPointerException if the specified key or value is null
1541 >     */
1542 >    public V replace(K key, V value) {
1543 >        if (key == null || value == null)
1544 >            throw new NullPointerException();
1545 >        return replaceNode(key, value, null);
1546 >    }
1547 >
1548 >    // Overrides of JDK8+ Map extension method defaults
1549 >
1550 >    /**
1551 >     * Returns the value to which the specified key is mapped, or the
1552 >     * given default value if this map contains no mapping for the
1553 >     * key.
1554 >     *
1555 >     * @param key the key whose associated value is to be returned
1556 >     * @param defaultValue the value to return if this map contains
1557 >     * no mapping for the given key
1558 >     * @return the mapping for the key, if present; else the default value
1559 >     * @throws NullPointerException if the specified key is null
1560 >     */
1561 >    public V getOrDefault(Object key, V defaultValue) {
1562 >        V v;
1563 >        return (v = get(key)) == null ? defaultValue : v;
1564 >    }
1565 >
1566 >    public void forEach(BiAction<? super K, ? super V> action) {
1567 >        if (action == null) throw new NullPointerException();
1568 >        Node<K,V>[] t;
1569 >        if ((t = table) != null) {
1570 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1571 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1572 >                action.apply(p.key, p.val);
1573 >            }
1574 >        }
1575 >    }
1576 >
1577 >    public void replaceAll(BiFun<? super K, ? super V, ? extends V> function) {
1578 >        if (function == null) throw new NullPointerException();
1579 >        Node<K,V>[] t;
1580 >        if ((t = table) != null) {
1581 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1582 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1583 >                V oldValue = p.val;
1584 >                for (K key = p.key;;) {
1585 >                    V newValue = function.apply(key, oldValue);
1586 >                    if (newValue == null)
1587 >                        throw new NullPointerException();
1588 >                    if (replaceNode(key, newValue, oldValue) != null ||
1589 >                        (oldValue = get(key)) == null)
1590 >                        break;
1591 >                }
1592 >            }
1593 >        }
1594 >    }
1595 >
1596 >    /**
1597 >     * If the specified key is not already associated with a value,
1598 >     * attempts to compute its value using the given mapping function
1599 >     * and enters it into this map unless {@code null}.  The entire
1600 >     * method invocation is performed atomically, so the function is
1601 >     * applied at most once per key.  Some attempted update operations
1602 >     * on this map by other threads may be blocked while computation
1603 >     * is in progress, so the computation should be short and simple,
1604 >     * and must not attempt to update any other mappings of this map.
1605 >     *
1606 >     * @param key key with which the specified value is to be associated
1607 >     * @param mappingFunction the function to compute a value
1608 >     * @return the current (existing or computed) value associated with
1609 >     *         the specified key, or null if the computed value is null
1610 >     * @throws NullPointerException if the specified key or mappingFunction
1611 >     *         is null
1612 >     * @throws IllegalStateException if the computation detectably
1613 >     *         attempts a recursive update to this map that would
1614 >     *         otherwise never complete
1615 >     * @throws RuntimeException or Error if the mappingFunction does so,
1616 >     *         in which case the mapping is left unestablished
1617 >     */
1618 >    public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
1619 >        if (key == null || mappingFunction == null)
1620 >            throw new NullPointerException();
1621 >        int h = spread(key.hashCode());
1622          V val = null;
1623 <        int len = 0;
1624 <        for (Node<V>[] tab = table;;) {
1625 <            Node<V> f; int i; Object fk;
1626 <            if (tab == null)
1623 >        int binCount = 0;
1624 >        for (Node<K,V>[] tab = table;;) {
1625 >            Node<K,V> f; int n, i, fh;
1626 >            if (tab == null || (n = tab.length) == 0)
1627                  tab = initTable();
1628 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1629 <                Node<V> node = new Node<V>(h, k, null, null);
1630 <                synchronized (node) {
1631 <                    if (casTabAt(tab, i, null, node)) {
1632 <                        len = 1;
1628 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1629 >                Node<K,V> r = new ReservationNode<K,V>();
1630 >                synchronized (r) {
1631 >                    if (casTabAt(tab, i, null, r)) {
1632 >                        binCount = 1;
1633 >                        Node<K,V> node = null;
1634                          try {
1635 <                            if ((val = mf.apply(k)) != null)
1636 <                                node.val = val;
1635 >                            if ((val = mappingFunction.apply(key)) != null)
1636 >                                node = new Node<K,V>(h, key, val, null);
1637                          } finally {
1638 <                            if (val == null)
1424 <                                setTabAt(tab, i, null);
1638 >                            setTabAt(tab, i, node);
1639                          }
1640                      }
1641                  }
1642 <                if (len != 0)
1642 >                if (binCount != 0)
1643                      break;
1644              }
1645 <            else if (f.hash < 0) {
1646 <                if ((fk = f.key) instanceof TreeBin) {
1647 <                    TreeBin<V> t = (TreeBin<V>)fk;
1648 <                    boolean added = false;
1649 <                    t.acquire(0);
1650 <                    try {
1651 <                        if (tabAt(tab, i) == f) {
1652 <                            len = 1;
1653 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1654 <                            if (p != null)
1645 >            else if ((fh = f.hash) == MOVED)
1646 >                tab = helpTransfer(tab, f);
1647 >            else {
1648 >                boolean added = false;
1649 >                synchronized (f) {
1650 >                    if (tabAt(tab, i) == f) {
1651 >                        if (fh >= 0) {
1652 >                            binCount = 1;
1653 >                            for (Node<K,V> e = f;; ++binCount) {
1654 >                                K ek; V ev;
1655 >                                if (e.hash == h &&
1656 >                                    ((ek = e.key) == key ||
1657 >                                     (ek != null && key.equals(ek)))) {
1658 >                                    val = e.val;
1659 >                                    break;
1660 >                                }
1661 >                                Node<K,V> pred = e;
1662 >                                if ((e = e.next) == null) {
1663 >                                    if ((val = mappingFunction.apply(key)) != null) {
1664 >                                        added = true;
1665 >                                        pred.next = new Node<K,V>(h, key, val, null);
1666 >                                    }
1667 >                                    break;
1668 >                                }
1669 >                            }
1670 >                        }
1671 >                        else if (f instanceof TreeBin) {
1672 >                            binCount = 2;
1673 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1674 >                            TreeNode<K,V> r, p;
1675 >                            if ((r = t.root) != null &&
1676 >                                (p = r.findTreeNode(h, key, null)) != null)
1677                                  val = p.val;
1678 <                            else if ((val = mf.apply(k)) != null) {
1678 >                            else if ((val = mappingFunction.apply(key)) != null) {
1679                                  added = true;
1680 <                                len = 2;
1445 <                                t.putTreeNode(h, k, val);
1680 >                                t.putTreeVal(h, key, val);
1681                              }
1682                          }
1448                    } finally {
1449                        t.release(0);
1450                    }
1451                    if (len != 0) {
1452                        if (!added)
1453                            return val;
1454                        break;
1683                      }
1684                  }
1685 <                else
1686 <                    tab = (Node<V>[])fk;
1685 >                if (binCount != 0) {
1686 >                    if (binCount >= TREEIFY_THRESHOLD)
1687 >                        treeifyBin(tab, i);
1688 >                    if (!added)
1689 >                        return val;
1690 >                    break;
1691 >                }
1692              }
1693 +        }
1694 +        if (val != null)
1695 +            addCount(1L, binCount);
1696 +        return val;
1697 +    }
1698 +
1699 +    /**
1700 +     * If the value for the specified key is present, attempts to
1701 +     * compute a new mapping given the key and its current mapped
1702 +     * value.  The entire method invocation is performed atomically.
1703 +     * Some attempted update operations on this map by other threads
1704 +     * may be blocked while computation is in progress, so the
1705 +     * computation should be short and simple, and must not attempt to
1706 +     * update any other mappings of this map.
1707 +     *
1708 +     * @param key key with which a value may be associated
1709 +     * @param remappingFunction the function to compute a value
1710 +     * @return the new value associated with the specified key, or null if none
1711 +     * @throws NullPointerException if the specified key or remappingFunction
1712 +     *         is null
1713 +     * @throws IllegalStateException if the computation detectably
1714 +     *         attempts a recursive update to this map that would
1715 +     *         otherwise never complete
1716 +     * @throws RuntimeException or Error if the remappingFunction does so,
1717 +     *         in which case the mapping is unchanged
1718 +     */
1719 +    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1720 +        if (key == null || remappingFunction == null)
1721 +            throw new NullPointerException();
1722 +        int h = spread(key.hashCode());
1723 +        V val = null;
1724 +        int delta = 0;
1725 +        int binCount = 0;
1726 +        for (Node<K,V>[] tab = table;;) {
1727 +            Node<K,V> f; int n, i, fh;
1728 +            if (tab == null || (n = tab.length) == 0)
1729 +                tab = initTable();
1730 +            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1731 +                break;
1732 +            else if ((fh = f.hash) == MOVED)
1733 +                tab = helpTransfer(tab, f);
1734              else {
1461                for (Node<V> e = f; e != null; e = e.next) { // prescan
1462                    Object ek; V ev;
1463                    if (e.hash == h && (ev = e.val) != null &&
1464                        ((ek = e.key) == k || k.equals(ek)))
1465                        return ev;
1466                }
1467                boolean added = false;
1735                  synchronized (f) {
1736                      if (tabAt(tab, i) == f) {
1737 <                        len = 1;
1738 <                        for (Node<V> e = f;; ++len) {
1739 <                            Object ek; V ev;
1740 <                            if (e.hash == h &&
1741 <                                (ev = e.val) != null &&
1742 <                                ((ek = e.key) == k || k.equals(ek))) {
1743 <                                val = ev;
1744 <                                break;
1737 >                        if (fh >= 0) {
1738 >                            binCount = 1;
1739 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1740 >                                K ek;
1741 >                                if (e.hash == h &&
1742 >                                    ((ek = e.key) == key ||
1743 >                                     (ek != null && key.equals(ek)))) {
1744 >                                    val = remappingFunction.apply(key, e.val);
1745 >                                    if (val != null)
1746 >                                        e.val = val;
1747 >                                    else {
1748 >                                        delta = -1;
1749 >                                        Node<K,V> en = e.next;
1750 >                                        if (pred != null)
1751 >                                            pred.next = en;
1752 >                                        else
1753 >                                            setTabAt(tab, i, en);
1754 >                                    }
1755 >                                    break;
1756 >                                }
1757 >                                pred = e;
1758 >                                if ((e = e.next) == null)
1759 >                                    break;
1760                              }
1761 <                            Node<V> last = e;
1762 <                            if ((e = e.next) == null) {
1763 <                                if ((val = mf.apply(k)) != null) {
1764 <                                    added = true;
1765 <                                    last.next = new Node<V>(h, k, val, null);
1766 <                                    if (len >= TREE_THRESHOLD)
1767 <                                        replaceWithTreeBin(tab, i, k);
1761 >                        }
1762 >                        else if (f instanceof TreeBin) {
1763 >                            binCount = 2;
1764 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1765 >                            TreeNode<K,V> r, p;
1766 >                            if ((r = t.root) != null &&
1767 >                                (p = r.findTreeNode(h, key, null)) != null) {
1768 >                                val = remappingFunction.apply(key, p.val);
1769 >                                if (val != null)
1770 >                                    p.val = val;
1771 >                                else {
1772 >                                    delta = -1;
1773 >                                    if (t.removeTreeNode(p))
1774 >                                        setTabAt(tab, i, untreeify(t.first));
1775                                  }
1487                                break;
1776                              }
1777                          }
1778                      }
1779                  }
1780 <                if (len != 0) {
1493 <                    if (!added)
1494 <                        return val;
1780 >                if (binCount != 0)
1781                      break;
1496                }
1782              }
1783          }
1784 <        if (val != null)
1785 <            addCount(1L, len);
1784 >        if (delta != 0)
1785 >            addCount((long)delta, binCount);
1786          return val;
1787      }
1788  
1789 <    /** Implementation for compute */
1790 <    @SuppressWarnings("unchecked") private final V internalCompute
1791 <        (K k, boolean onlyIfPresent,
1792 <         BiFun<? super K, ? super V, ? extends V> mf) {
1793 <        if (k == null || mf == null)
1789 >    /**
1790 >     * Attempts to compute a mapping for the specified key and its
1791 >     * current mapped value (or {@code null} if there is no current
1792 >     * mapping). The entire method invocation is performed atomically.
1793 >     * Some attempted update operations on this map by other threads
1794 >     * may be blocked while computation is in progress, so the
1795 >     * computation should be short and simple, and must not attempt to
1796 >     * update any other mappings of this Map.
1797 >     *
1798 >     * @param key key with which the specified value is to be associated
1799 >     * @param remappingFunction the function to compute a value
1800 >     * @return the new value associated with the specified key, or null if none
1801 >     * @throws NullPointerException if the specified key or remappingFunction
1802 >     *         is null
1803 >     * @throws IllegalStateException if the computation detectably
1804 >     *         attempts a recursive update to this map that would
1805 >     *         otherwise never complete
1806 >     * @throws RuntimeException or Error if the remappingFunction does so,
1807 >     *         in which case the mapping is unchanged
1808 >     */
1809 >    public V compute(K key,
1810 >                     BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1811 >        if (key == null || remappingFunction == null)
1812              throw new NullPointerException();
1813 <        int h = spread(k.hashCode());
1813 >        int h = spread(key.hashCode());
1814          V val = null;
1815          int delta = 0;
1816 <        int len = 0;
1817 <        for (Node<V>[] tab = table;;) {
1818 <            Node<V> f; int i, fh; Object fk;
1819 <            if (tab == null)
1816 >        int binCount = 0;
1817 >        for (Node<K,V>[] tab = table;;) {
1818 >            Node<K,V> f; int n, i, fh;
1819 >            if (tab == null || (n = tab.length) == 0)
1820                  tab = initTable();
1821 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1822 <                if (onlyIfPresent)
1823 <                    break;
1824 <                Node<V> node = new Node<V>(h, k, null, null);
1825 <                synchronized (node) {
1826 <                    if (casTabAt(tab, i, null, node)) {
1821 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1822 >                Node<K,V> r = new ReservationNode<K,V>();
1823 >                synchronized (r) {
1824 >                    if (casTabAt(tab, i, null, r)) {
1825 >                        binCount = 1;
1826 >                        Node<K,V> node = null;
1827                          try {
1828 <                            len = 1;
1526 <                            if ((val = mf.apply(k, null)) != null) {
1527 <                                node.val = val;
1828 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1829                                  delta = 1;
1830 +                                node = new Node<K,V>(h, key, val, null);
1831                              }
1832                          } finally {
1833 <                            if (delta == 0)
1532 <                                setTabAt(tab, i, null);
1833 >                            setTabAt(tab, i, node);
1834                          }
1835                      }
1836                  }
1837 <                if (len != 0)
1837 >                if (binCount != 0)
1838                      break;
1839              }
1840 <            else if ((fh = f.hash) < 0) {
1841 <                if ((fk = f.key) instanceof TreeBin) {
1842 <                    TreeBin<V> t = (TreeBin<V>)fk;
1843 <                    t.acquire(0);
1844 <                    try {
1845 <                        if (tabAt(tab, i) == f) {
1846 <                            len = 1;
1847 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1848 <                            if (p == null && onlyIfPresent)
1849 <                                break;
1840 >            else if ((fh = f.hash) == MOVED)
1841 >                tab = helpTransfer(tab, f);
1842 >            else {
1843 >                synchronized (f) {
1844 >                    if (tabAt(tab, i) == f) {
1845 >                        if (fh >= 0) {
1846 >                            binCount = 1;
1847 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1848 >                                K ek;
1849 >                                if (e.hash == h &&
1850 >                                    ((ek = e.key) == key ||
1851 >                                     (ek != null && key.equals(ek)))) {
1852 >                                    val = remappingFunction.apply(key, e.val);
1853 >                                    if (val != null)
1854 >                                        e.val = val;
1855 >                                    else {
1856 >                                        delta = -1;
1857 >                                        Node<K,V> en = e.next;
1858 >                                        if (pred != null)
1859 >                                            pred.next = en;
1860 >                                        else
1861 >                                            setTabAt(tab, i, en);
1862 >                                    }
1863 >                                    break;
1864 >                                }
1865 >                                pred = e;
1866 >                                if ((e = e.next) == null) {
1867 >                                    val = remappingFunction.apply(key, null);
1868 >                                    if (val != null) {
1869 >                                        delta = 1;
1870 >                                        pred.next =
1871 >                                            new Node<K,V>(h, key, val, null);
1872 >                                    }
1873 >                                    break;
1874 >                                }
1875 >                            }
1876 >                        }
1877 >                        else if (f instanceof TreeBin) {
1878 >                            binCount = 1;
1879 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1880 >                            TreeNode<K,V> r, p;
1881 >                            if ((r = t.root) != null)
1882 >                                p = r.findTreeNode(h, key, null);
1883 >                            else
1884 >                                p = null;
1885                              V pv = (p == null) ? null : p.val;
1886 <                            if ((val = mf.apply(k, pv)) != null) {
1886 >                            val = remappingFunction.apply(key, pv);
1887 >                            if (val != null) {
1888                                  if (p != null)
1889                                      p.val = val;
1890                                  else {
1554                                    len = 2;
1891                                      delta = 1;
1892 <                                    t.putTreeNode(h, k, val);
1892 >                                    t.putTreeVal(h, key, val);
1893                                  }
1894                              }
1895                              else if (p != null) {
1896                                  delta = -1;
1897 <                                t.deleteTreeNode(p);
1897 >                                if (t.removeTreeNode(p))
1898 >                                    setTabAt(tab, i, untreeify(t.first));
1899                              }
1900                          }
1564                    } finally {
1565                        t.release(0);
1901                      }
1567                    if (len != 0)
1568                        break;
1902                  }
1903 <                else
1904 <                    tab = (Node<V>[])fk;
1905 <            }
1573 <            else {
1574 <                synchronized (f) {
1575 <                    if (tabAt(tab, i) == f) {
1576 <                        len = 1;
1577 <                        for (Node<V> e = f, pred = null;; ++len) {
1578 <                            Object ek; V ev;
1579 <                            if (e.hash == h &&
1580 <                                (ev = e.val) != null &&
1581 <                                ((ek = e.key) == k || k.equals(ek))) {
1582 <                                val = mf.apply(k, ev);
1583 <                                if (val != null)
1584 <                                    e.val = val;
1585 <                                else {
1586 <                                    delta = -1;
1587 <                                    Node<V> en = e.next;
1588 <                                    if (pred != null)
1589 <                                        pred.next = en;
1590 <                                    else
1591 <                                        setTabAt(tab, i, en);
1592 <                                }
1593 <                                break;
1594 <                            }
1595 <                            pred = e;
1596 <                            if ((e = e.next) == null) {
1597 <                                if (!onlyIfPresent &&
1598 <                                    (val = mf.apply(k, null)) != null) {
1599 <                                    pred.next = new Node<V>(h, k, val, null);
1600 <                                    delta = 1;
1601 <                                    if (len >= TREE_THRESHOLD)
1602 <                                        replaceWithTreeBin(tab, i, k);
1603 <                                }
1604 <                                break;
1605 <                            }
1606 <                        }
1607 <                    }
1608 <                }
1609 <                if (len != 0)
1903 >                if (binCount != 0) {
1904 >                    if (binCount >= TREEIFY_THRESHOLD)
1905 >                        treeifyBin(tab, i);
1906                      break;
1907 +                }
1908              }
1909          }
1910          if (delta != 0)
1911 <            addCount((long)delta, len);
1911 >            addCount((long)delta, binCount);
1912          return val;
1913      }
1914  
1915 <    /** Implementation for merge */
1916 <    @SuppressWarnings("unchecked") private final V internalMerge
1917 <        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1918 <        if (k == null || v == null || mf == null)
1915 >    /**
1916 >     * If the specified key is not already associated with a
1917 >     * (non-null) value, associates it with the given value.
1918 >     * Otherwise, replaces the value with the results of the given
1919 >     * remapping function, or removes if {@code null}. The entire
1920 >     * method invocation is performed atomically.  Some attempted
1921 >     * update operations on this map by other threads may be blocked
1922 >     * while computation is in progress, so the computation should be
1923 >     * short and simple, and must not attempt to update any other
1924 >     * mappings of this Map.
1925 >     *
1926 >     * @param key key with which the specified value is to be associated
1927 >     * @param value the value to use if absent
1928 >     * @param remappingFunction the function to recompute a value if present
1929 >     * @return the new value associated with the specified key, or null if none
1930 >     * @throws NullPointerException if the specified key or the
1931 >     *         remappingFunction is null
1932 >     * @throws RuntimeException or Error if the remappingFunction does so,
1933 >     *         in which case the mapping is unchanged
1934 >     */
1935 >    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1936 >        if (key == null || value == null || remappingFunction == null)
1937              throw new NullPointerException();
1938 <        int h = spread(k.hashCode());
1938 >        int h = spread(key.hashCode());
1939          V val = null;
1940          int delta = 0;
1941 <        int len = 0;
1942 <        for (Node<V>[] tab = table;;) {
1943 <            int i; Node<V> f; Object fk; V fv;
1944 <            if (tab == null)
1941 >        int binCount = 0;
1942 >        for (Node<K,V>[] tab = table;;) {
1943 >            Node<K,V> f; int n, i, fh;
1944 >            if (tab == null || (n = tab.length) == 0)
1945                  tab = initTable();
1946 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1947 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
1946 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1947 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1948                      delta = 1;
1949 <                    val = v;
1949 >                    val = value;
1950                      break;
1951                  }
1952              }
1953 <            else if (f.hash < 0) {
1954 <                if ((fk = f.key) instanceof TreeBin) {
1955 <                    TreeBin<V> t = (TreeBin<V>)fk;
1956 <                    t.acquire(0);
1957 <                    try {
1958 <                        if (tabAt(tab, i) == f) {
1959 <                            len = 1;
1960 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1961 <                            val = (p == null) ? v : mf.apply(p.val, v);
1953 >            else if ((fh = f.hash) == MOVED)
1954 >                tab = helpTransfer(tab, f);
1955 >            else {
1956 >                synchronized (f) {
1957 >                    if (tabAt(tab, i) == f) {
1958 >                        if (fh >= 0) {
1959 >                            binCount = 1;
1960 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1961 >                                K ek;
1962 >                                if (e.hash == h &&
1963 >                                    ((ek = e.key) == key ||
1964 >                                     (ek != null && key.equals(ek)))) {
1965 >                                    val = remappingFunction.apply(e.val, value);
1966 >                                    if (val != null)
1967 >                                        e.val = val;
1968 >                                    else {
1969 >                                        delta = -1;
1970 >                                        Node<K,V> en = e.next;
1971 >                                        if (pred != null)
1972 >                                            pred.next = en;
1973 >                                        else
1974 >                                            setTabAt(tab, i, en);
1975 >                                    }
1976 >                                    break;
1977 >                                }
1978 >                                pred = e;
1979 >                                if ((e = e.next) == null) {
1980 >                                    delta = 1;
1981 >                                    val = value;
1982 >                                    pred.next =
1983 >                                        new Node<K,V>(h, key, val, null);
1984 >                                    break;
1985 >                                }
1986 >                            }
1987 >                        }
1988 >                        else if (f instanceof TreeBin) {
1989 >                            binCount = 2;
1990 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1991 >                            TreeNode<K,V> r = t.root;
1992 >                            TreeNode<K,V> p = (r == null) ? null :
1993 >                                r.findTreeNode(h, key, null);
1994 >                            val = (p == null) ? value :
1995 >                                remappingFunction.apply(p.val, value);
1996                              if (val != null) {
1997                                  if (p != null)
1998                                      p.val = val;
1999                                  else {
1651                                    len = 2;
2000                                      delta = 1;
2001 <                                    t.putTreeNode(h, k, val);
2001 >                                    t.putTreeVal(h, key, val);
2002                                  }
2003                              }
2004                              else if (p != null) {
2005                                  delta = -1;
2006 <                                t.deleteTreeNode(p);
2007 <                            }
1660 <                        }
1661 <                    } finally {
1662 <                        t.release(0);
1663 <                    }
1664 <                    if (len != 0)
1665 <                        break;
1666 <                }
1667 <                else
1668 <                    tab = (Node<V>[])fk;
1669 <            }
1670 <            else {
1671 <                synchronized (f) {
1672 <                    if (tabAt(tab, i) == f) {
1673 <                        len = 1;
1674 <                        for (Node<V> e = f, pred = null;; ++len) {
1675 <                            Object ek; V ev;
1676 <                            if (e.hash == h &&
1677 <                                (ev = e.val) != null &&
1678 <                                ((ek = e.key) == k || k.equals(ek))) {
1679 <                                val = mf.apply(ev, v);
1680 <                                if (val != null)
1681 <                                    e.val = val;
1682 <                                else {
1683 <                                    delta = -1;
1684 <                                    Node<V> en = e.next;
1685 <                                    if (pred != null)
1686 <                                        pred.next = en;
1687 <                                    else
1688 <                                        setTabAt(tab, i, en);
1689 <                                }
1690 <                                break;
1691 <                            }
1692 <                            pred = e;
1693 <                            if ((e = e.next) == null) {
1694 <                                val = v;
1695 <                                pred.next = new Node<V>(h, k, val, null);
1696 <                                delta = 1;
1697 <                                if (len >= TREE_THRESHOLD)
1698 <                                    replaceWithTreeBin(tab, i, k);
1699 <                                break;
2006 >                                if (t.removeTreeNode(p))
2007 >                                    setTabAt(tab, i, untreeify(t.first));
2008                              }
2009                          }
2010                      }
2011                  }
2012 <                if (len != 0)
2012 >                if (binCount != 0) {
2013 >                    if (binCount >= TREEIFY_THRESHOLD)
2014 >                        treeifyBin(tab, i);
2015                      break;
2016 +                }
2017              }
2018          }
2019          if (delta != 0)
2020 <            addCount((long)delta, len);
2020 >            addCount((long)delta, binCount);
2021          return val;
2022      }
2023  
2024 <    /** Implementation for putAll */
2025 <    @SuppressWarnings("unchecked") private final void internalPutAll
2026 <        (Map<? extends K, ? extends V> m) {
2027 <        tryPresize(m.size());
2028 <        long delta = 0L;     // number of uncommitted additions
2029 <        boolean npe = false; // to throw exception on exit for nulls
2030 <        try {                // to clean up counts on other exceptions
2031 <            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
2032 <                Object k; V v;
2033 <                if (entry == null || (k = entry.getKey()) == null ||
2034 <                    (v = entry.getValue()) == null) {
2035 <                    npe = true;
2036 <                    break;
2037 <                }
2038 <                int h = spread(k.hashCode());
2039 <                for (Node<V>[] tab = table;;) {
2040 <                    int i; Node<V> f; int fh; Object fk;
2041 <                    if (tab == null)
2042 <                        tab = initTable();
2043 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
2044 <                        if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
2045 <                            ++delta;
2046 <                            break;
2047 <                        }
2048 <                    }
2049 <                    else if ((fh = f.hash) < 0) {
2050 <                        if ((fk = f.key) instanceof TreeBin) {
2051 <                            TreeBin<V> t = (TreeBin<V>)fk;
2052 <                            boolean validated = false;
2053 <                            t.acquire(0);
2054 <                            try {
2055 <                                if (tabAt(tab, i) == f) {
2056 <                                    validated = true;
2057 <                                    TreeNode<V> p = t.getTreeNode(h, k, t.root);
2058 <                                    if (p != null)
2059 <                                        p.val = v;
2060 <                                    else {
2061 <                                        t.putTreeNode(h, k, v);
2062 <                                        ++delta;
2063 <                                    }
2064 <                                }
2065 <                            } finally {
2066 <                                t.release(0);
2067 <                            }
2068 <                            if (validated)
2069 <                                break;
2070 <                        }
2071 <                        else
2072 <                            tab = (Node<V>[])fk;
2073 <                    }
2074 <                    else {
2075 <                        int len = 0;
2076 <                        synchronized (f) {
2077 <                            if (tabAt(tab, i) == f) {
2078 <                                len = 1;
2079 <                                for (Node<V> e = f;; ++len) {
2080 <                                    Object ek; V ev;
2081 <                                    if (e.hash == h &&
2082 <                                        (ev = e.val) != null &&
2083 <                                        ((ek = e.key) == k || k.equals(ek))) {
2084 <                                        e.val = v;
2085 <                                        break;
2086 <                                    }
2087 <                                    Node<V> last = e;
2088 <                                    if ((e = e.next) == null) {
2089 <                                        ++delta;
2090 <                                        last.next = new Node<V>(h, k, v, null);
2091 <                                        if (len >= TREE_THRESHOLD)
2092 <                                            replaceWithTreeBin(tab, i, k);
2093 <                                        break;
2094 <                                    }
2095 <                                }
2096 <                            }
2097 <                        }
2098 <                        if (len != 0) {
2099 <                            if (len > 1) {
2100 <                                addCount(delta, len);
2101 <                                delta = 0L;
2102 <                            }
2103 <                            break;
2104 <                        }
2105 <                    }
2106 <                }
2107 <            }
2108 <        } finally {
2109 <            if (delta != 0L)
2110 <                addCount(delta, 2);
2111 <        }
2112 <        if (npe)
2024 >    // Hashtable legacy methods
2025 >
2026 >    /**
2027 >     * Legacy method testing if some key maps into the specified value
2028 >     * in this table.  This method is identical in functionality to
2029 >     * {@link #containsValue(Object)}, and exists solely to ensure
2030 >     * full compatibility with class {@link java.util.Hashtable},
2031 >     * which supported this method prior to introduction of the
2032 >     * Java Collections framework.
2033 >     *
2034 >     * @param  value a value to search for
2035 >     * @return {@code true} if and only if some key maps to the
2036 >     *         {@code value} argument in this table as
2037 >     *         determined by the {@code equals} method;
2038 >     *         {@code false} otherwise
2039 >     * @throws NullPointerException if the specified value is null
2040 >     */
2041 >    @Deprecated public boolean contains(Object value) {
2042 >        return containsValue(value);
2043 >    }
2044 >
2045 >    /**
2046 >     * Returns an enumeration of the keys in this table.
2047 >     *
2048 >     * @return an enumeration of the keys in this table
2049 >     * @see #keySet()
2050 >     */
2051 >    public Enumeration<K> keys() {
2052 >        Node<K,V>[] t;
2053 >        int f = (t = table) == null ? 0 : t.length;
2054 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2055 >    }
2056 >
2057 >    /**
2058 >     * Returns an enumeration of the values in this table.
2059 >     *
2060 >     * @return an enumeration of the values in this table
2061 >     * @see #values()
2062 >     */
2063 >    public Enumeration<V> elements() {
2064 >        Node<K,V>[] t;
2065 >        int f = (t = table) == null ? 0 : t.length;
2066 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2067 >    }
2068 >
2069 >    // ConcurrentHashMapV8-only methods
2070 >
2071 >    /**
2072 >     * Returns the number of mappings. This method should be used
2073 >     * instead of {@link #size} because a ConcurrentHashMapV8 may
2074 >     * contain more mappings than can be represented as an int. The
2075 >     * value returned is an estimate; the actual count may differ if
2076 >     * there are concurrent insertions or removals.
2077 >     *
2078 >     * @return the number of mappings
2079 >     * @since 1.8
2080 >     */
2081 >    public long mappingCount() {
2082 >        long n = sumCount();
2083 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2084 >    }
2085 >
2086 >    /**
2087 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2088 >     * from the given type to {@code Boolean.TRUE}.
2089 >     *
2090 >     * @return the new set
2091 >     * @since 1.8
2092 >     */
2093 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2094 >        return new KeySetView<K,Boolean>
2095 >            (new ConcurrentHashMapV8<K,Boolean>(), Boolean.TRUE);
2096 >    }
2097 >
2098 >    /**
2099 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2100 >     * from the given type to {@code Boolean.TRUE}.
2101 >     *
2102 >     * @param initialCapacity The implementation performs internal
2103 >     * sizing to accommodate this many elements.
2104 >     * @throws IllegalArgumentException if the initial capacity of
2105 >     * elements is negative
2106 >     * @return the new set
2107 >     * @since 1.8
2108 >     */
2109 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2110 >        return new KeySetView<K,Boolean>
2111 >            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2112 >    }
2113 >
2114 >    /**
2115 >     * Returns a {@link Set} view of the keys in this map, using the
2116 >     * given common mapped value for any additions (i.e., {@link
2117 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2118 >     * This is of course only appropriate if it is acceptable to use
2119 >     * the same value for all additions from this view.
2120 >     *
2121 >     * @param mappedValue the mapped value to use for any additions
2122 >     * @return the set view
2123 >     * @throws NullPointerException if the mappedValue is null
2124 >     */
2125 >    public KeySetView<K,V> keySet(V mappedValue) {
2126 >        if (mappedValue == null)
2127              throw new NullPointerException();
2128 +        return new KeySetView<K,V>(this, mappedValue);
2129      }
2130  
2131 +    /* ---------------- Special Nodes -------------- */
2132 +
2133      /**
2134 <     * Implementation for clear. Steps through each bin, removing all
1807 <     * nodes.
2134 >     * A node inserted at head of bins during transfer operations.
2135       */
2136 <    @SuppressWarnings("unchecked") private final void internalClear() {
2137 <        long delta = 0L; // negative number of deletions
2138 <        int i = 0;
2139 <        Node<V>[] tab = table;
2140 <        while (tab != null && i < tab.length) {
2141 <            Node<V> f = tabAt(tab, i);
2142 <            if (f == null)
2143 <                ++i;
2144 <            else if (f.hash < 0) {
2145 <                Object fk;
2146 <                if ((fk = f.key) instanceof TreeBin) {
2147 <                    TreeBin<V> t = (TreeBin<V>)fk;
2148 <                    t.acquire(0);
2149 <                    try {
2150 <                        if (tabAt(tab, i) == f) {
2151 <                            for (Node<V> p = t.first; p != null; p = p.next) {
2152 <                                if (p.val != null) { // (currently always true)
2153 <                                    p.val = null;
2154 <                                    --delta;
2155 <                                }
1829 <                            }
1830 <                            t.first = null;
1831 <                            t.root = null;
1832 <                            ++i;
1833 <                        }
1834 <                    } finally {
1835 <                        t.release(0);
1836 <                    }
1837 <                }
1838 <                else
1839 <                    tab = (Node<V>[])fk;
1840 <            }
1841 <            else {
1842 <                synchronized (f) {
1843 <                    if (tabAt(tab, i) == f) {
1844 <                        for (Node<V> e = f; e != null; e = e.next) {
1845 <                            if (e.val != null) {  // (currently always true)
1846 <                                e.val = null;
1847 <                                --delta;
1848 <                            }
1849 <                        }
1850 <                        setTabAt(tab, i, null);
1851 <                        ++i;
1852 <                    }
1853 <                }
2136 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2137 >        final Node<K,V>[] nextTable;
2138 >        ForwardingNode(Node<K,V>[] tab) {
2139 >            super(MOVED, null, null, null);
2140 >            this.nextTable = tab;
2141 >        }
2142 >
2143 >        Node<K,V> find(int h, Object k) {
2144 >            Node<K,V> e; int n;
2145 >            Node<K,V>[] tab = nextTable;
2146 >            if (k != null && tab != null && (n = tab.length) > 0 &&
2147 >                (e = tabAt(tab, (n - 1) & h)) != null) {
2148 >                do {
2149 >                    int eh; K ek;
2150 >                    if ((eh = e.hash) == h &&
2151 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2152 >                        return e;
2153 >                    if (eh < 0)
2154 >                        return e.find(h, k);
2155 >                } while ((e = e.next) != null);
2156              }
2157 +            return null;
2158          }
1856        if (delta != 0L)
1857            addCount(delta, -1);
2159      }
2160  
1860    /* ---------------- Table Initialization and Resizing -------------- */
1861
2161      /**
2162 <     * Returns a power of two table size for the given desired capacity.
1864 <     * See Hackers Delight, sec 3.2
2162 >     * A place-holder node used in computeIfAbsent and compute
2163       */
2164 <    private static final int tableSizeFor(int c) {
2165 <        int n = c - 1;
2166 <        n |= n >>> 1;
2167 <        n |= n >>> 2;
2168 <        n |= n >>> 4;
2169 <        n |= n >>> 8;
2170 <        n |= n >>> 16;
2171 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
2164 >    static final class ReservationNode<K,V> extends Node<K,V> {
2165 >        ReservationNode() {
2166 >            super(RESERVED, null, null, null);
2167 >        }
2168 >
2169 >        Node<K,V> find(int h, Object k) {
2170 >            return null;
2171 >        }
2172      }
2173  
2174 +    /* ---------------- Table Initialization and Resizing -------------- */
2175 +
2176      /**
2177       * Initializes table, using the size recorded in sizeCtl.
2178       */
2179 <    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
2180 <        Node<V>[] tab; int sc;
2181 <        while ((tab = table) == null) {
2179 >    private final Node<K,V>[] initTable() {
2180 >        Node<K,V>[] tab; int sc;
2181 >        while ((tab = table) == null || tab.length == 0) {
2182              if ((sc = sizeCtl) < 0)
2183                  Thread.yield(); // lost initialization race; just spin
2184              else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2185                  try {
2186 <                    if ((tab = table) == null) {
2186 >                    if ((tab = table) == null || tab.length == 0) {
2187                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2188 <                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2189 <                        table = tab = (Node<V>[])tb;
2188 >                        @SuppressWarnings({"rawtypes","unchecked"})
2189 >                            Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2190 >                        table = tab = nt;
2191                          sc = n - (n >>> 2);
2192                      }
2193                  } finally {
# Line 1927 | Line 2228 | public class ConcurrentHashMapV8<K,V>
2228              s = sumCount();
2229          }
2230          if (check >= 0) {
2231 <            Node<V>[] tab, nt; int sc;
2231 >            Node<K,V>[] tab, nt; int sc;
2232              while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2233                     tab.length < MAXIMUM_CAPACITY) {
2234                  if (sc < 0) {
# Line 1945 | Line 2246 | public class ConcurrentHashMapV8<K,V>
2246      }
2247  
2248      /**
2249 +     * Helps transfer if a resize is in progress.
2250 +     */
2251 +    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2252 +        Node<K,V>[] nextTab; int sc;
2253 +        if ((f instanceof ForwardingNode) &&
2254 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2255 +            if (nextTab == nextTable && tab == table &&
2256 +                transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
2257 +                U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2258 +                transfer(tab, nextTab);
2259 +            return nextTab;
2260 +        }
2261 +        return table;
2262 +    }
2263 +
2264 +    /**
2265       * Tries to presize table to accommodate the given number of elements.
2266       *
2267       * @param size number of elements (doesn't need to be perfectly accurate)
2268       */
2269 <    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
2269 >    private final void tryPresize(int size) {
2270          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2271              tableSizeFor(size + (size >>> 1) + 1);
2272          int sc;
2273          while ((sc = sizeCtl) >= 0) {
2274 <            Node<V>[] tab = table; int n;
2274 >            Node<K,V>[] tab = table; int n;
2275              if (tab == null || (n = tab.length) == 0) {
2276                  n = (sc > c) ? sc : c;
2277                  if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2278                      try {
2279                          if (table == tab) {
2280 <                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2281 <                            table = (Node<V>[])tb;
2280 >                            @SuppressWarnings({"rawtypes","unchecked"})
2281 >                                Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2282 >                            table = nt;
2283                              sc = n - (n >>> 2);
2284                          }
2285                      } finally {
# Line 1981 | Line 2299 | public class ConcurrentHashMapV8<K,V>
2299       * Moves and/or copies the nodes in each bin to new table. See
2300       * above for explanation.
2301       */
2302 <    @SuppressWarnings("unchecked") private final void transfer
1985 <        (Node<V>[] tab, Node<V>[] nextTab) {
2302 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2303          int n = tab.length, stride;
2304          if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2305              stride = MIN_TRANSFER_STRIDE; // subdivide range
2306          if (nextTab == null) {            // initiating
2307              try {
2308 <                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
2309 <                nextTab = (Node<V>[])tb;
2308 >                @SuppressWarnings({"rawtypes","unchecked"})
2309 >                    Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
2310 >                nextTab = nt;
2311              } catch (Throwable ex) {      // try to cope with OOME
2312                  sizeCtl = Integer.MAX_VALUE;
2313                  return;
# Line 1997 | Line 2315 | public class ConcurrentHashMapV8<K,V>
2315              nextTable = nextTab;
2316              transferOrigin = n;
2317              transferIndex = n;
2318 <            Node<V> rev = new Node<V>(MOVED, tab, null, null);
2318 >            ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
2319              for (int k = n; k > 0;) {    // progressively reveal ready slots
2320                  int nextk = (k > stride) ? k - stride : 0;
2321                  for (int m = nextk; m < k; ++m)
# Line 2008 | Line 2326 | public class ConcurrentHashMapV8<K,V>
2326              }
2327          }
2328          int nextn = nextTab.length;
2329 <        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2329 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2330          boolean advance = true;
2331          for (int i = 0, bound = 0;;) {
2332 <            int nextIndex, nextBound; Node<V> f; Object fk;
2332 >            int nextIndex, nextBound, fh; Node<K,V> f;
2333              while (advance) {
2334                  if (--i >= bound)
2335                      advance = false;
# Line 2047 | Line 2365 | public class ConcurrentHashMapV8<K,V>
2365                      advance = true;
2366                  }
2367              }
2368 <            else if (f.hash >= 0) {
2368 >            else if ((fh = f.hash) == MOVED)
2369 >                advance = true; // already processed
2370 >            else {
2371                  synchronized (f) {
2372                      if (tabAt(tab, i) == f) {
2373 <                        int runBit = f.hash & n;
2374 <                        Node<V> lastRun = f, lo = null, hi = null;
2375 <                        for (Node<V> p = f.next; p != null; p = p.next) {
2376 <                            int b = p.hash & n;
2377 <                            if (b != runBit) {
2378 <                                runBit = b;
2379 <                                lastRun = p;
2373 >                        Node<K,V> ln, hn;
2374 >                        if (fh >= 0) {
2375 >                            int runBit = fh & n;
2376 >                            Node<K,V> lastRun = f;
2377 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2378 >                                int b = p.hash & n;
2379 >                                if (b != runBit) {
2380 >                                    runBit = b;
2381 >                                    lastRun = p;
2382 >                                }
2383                              }
2384 <                        }
2385 <                        if (runBit == 0)
2386 <                            lo = lastRun;
2064 <                        else
2065 <                            hi = lastRun;
2066 <                        for (Node<V> p = f; p != lastRun; p = p.next) {
2067 <                            int ph = p.hash;
2068 <                            Object pk = p.key; V pv = p.val;
2069 <                            if ((ph & n) == 0)
2070 <                                lo = new Node<V>(ph, pk, pv, lo);
2071 <                            else
2072 <                                hi = new Node<V>(ph, pk, pv, hi);
2073 <                        }
2074 <                        setTabAt(nextTab, i, lo);
2075 <                        setTabAt(nextTab, i + n, hi);
2076 <                        setTabAt(tab, i, fwd);
2077 <                        advance = true;
2078 <                    }
2079 <                }
2080 <            }
2081 <            else if ((fk = f.key) instanceof TreeBin) {
2082 <                TreeBin<V> t = (TreeBin<V>)fk;
2083 <                t.acquire(0);
2084 <                try {
2085 <                    if (tabAt(tab, i) == f) {
2086 <                        TreeBin<V> lt = new TreeBin<V>();
2087 <                        TreeBin<V> ht = new TreeBin<V>();
2088 <                        int lc = 0, hc = 0;
2089 <                        for (Node<V> e = t.first; e != null; e = e.next) {
2090 <                            int h = e.hash;
2091 <                            Object k = e.key; V v = e.val;
2092 <                            if ((h & n) == 0) {
2093 <                                ++lc;
2094 <                                lt.putTreeNode(h, k, v);
2384 >                            if (runBit == 0) {
2385 >                                ln = lastRun;
2386 >                                hn = null;
2387                              }
2388                              else {
2389 <                                ++hc;
2390 <                                ht.putTreeNode(h, k, v);
2389 >                                hn = lastRun;
2390 >                                ln = null;
2391                              }
2392 +                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2393 +                                int ph = p.hash; K pk = p.key; V pv = p.val;
2394 +                                if ((ph & n) == 0)
2395 +                                    ln = new Node<K,V>(ph, pk, pv, ln);
2396 +                                else
2397 +                                    hn = new Node<K,V>(ph, pk, pv, hn);
2398 +                            }
2399 +                            setTabAt(nextTab, i, ln);
2400 +                            setTabAt(nextTab, i + n, hn);
2401 +                            setTabAt(tab, i, fwd);
2402 +                            advance = true;
2403                          }
2404 <                        Node<V> ln, hn; // throw away trees if too small
2405 <                        if (lc < TREE_THRESHOLD) {
2406 <                            ln = null;
2407 <                            for (Node<V> p = lt.first; p != null; p = p.next)
2408 <                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2409 <                        }
2410 <                        else
2411 <                            ln = new Node<V>(MOVED, lt, null, null);
2412 <                        setTabAt(nextTab, i, ln);
2413 <                        if (hc < TREE_THRESHOLD) {
2414 <                            hn = null;
2415 <                            for (Node<V> p = ht.first; p != null; p = p.next)
2416 <                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2404 >                        else if (f instanceof TreeBin) {
2405 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2406 >                            TreeNode<K,V> lo = null, loTail = null;
2407 >                            TreeNode<K,V> hi = null, hiTail = null;
2408 >                            int lc = 0, hc = 0;
2409 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2410 >                                int h = e.hash;
2411 >                                TreeNode<K,V> p = new TreeNode<K,V>
2412 >                                    (h, e.key, e.val, null, null);
2413 >                                if ((h & n) == 0) {
2414 >                                    if ((p.prev = loTail) == null)
2415 >                                        lo = p;
2416 >                                    else
2417 >                                        loTail.next = p;
2418 >                                    loTail = p;
2419 >                                    ++lc;
2420 >                                }
2421 >                                else {
2422 >                                    if ((p.prev = hiTail) == null)
2423 >                                        hi = p;
2424 >                                    else
2425 >                                        hiTail.next = p;
2426 >                                    hiTail = p;
2427 >                                    ++hc;
2428 >                                }
2429 >                            }
2430 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2431 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2432 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2433 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2434 >                            setTabAt(nextTab, i, ln);
2435 >                            setTabAt(nextTab, i + n, hn);
2436 >                            setTabAt(tab, i, fwd);
2437 >                            advance = true;
2438                          }
2115                        else
2116                            hn = new Node<V>(MOVED, ht, null, null);
2117                        setTabAt(nextTab, i + n, hn);
2118                        setTabAt(tab, i, fwd);
2119                        advance = true;
2439                      }
2121                } finally {
2122                    t.release(0);
2440                  }
2441              }
2125            else
2126                advance = true; // already processed
2442          }
2443      }
2444  
2445 <    /* ---------------- Counter support -------------- */
2445 >    /* ---------------- Conversion from/to TreeBins -------------- */
2446  
2447 <    final long sumCount() {
2448 <        CounterCell[] as = counterCells; CounterCell a;
2449 <        long sum = baseCount;
2450 <        if (as != null) {
2451 <            for (int i = 0; i < as.length; ++i) {
2452 <                if ((a = as[i]) != null)
2453 <                    sum += a.value;
2447 >    /**
2448 >     * Replaces all linked nodes in bin at given index unless table is
2449 >     * too small, in which case resizes instead.
2450 >     */
2451 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2452 >        Node<K,V> b; int n, sc;
2453 >        if (tab != null) {
2454 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2455 >                if (tab == table && (sc = sizeCtl) >= 0 &&
2456 >                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
2457 >                    transfer(tab, null);
2458              }
2459 <        }
2460 <        return sum;
2461 <    }
2462 <
2463 <    // See LongAdder version for explanation
2464 <    private final void fullAddCount(long x, CounterHashCode hc,
2465 <                                    boolean wasUncontended) {
2466 <        int h;
2467 <        if (hc == null) {
2468 <            hc = new CounterHashCode();
2469 <            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
2470 <            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
2471 <            threadCounterHashCode.set(hc);
2153 <        }
2154 <        else
2155 <            h = hc.code;
2156 <        boolean collide = false;                // True if last slot nonempty
2157 <        for (;;) {
2158 <            CounterCell[] as; CounterCell a; int n; long v;
2159 <            if ((as = counterCells) != null && (n = as.length) > 0) {
2160 <                if ((a = as[(n - 1) & h]) == null) {
2161 <                    if (counterBusy == 0) {            // Try to attach new Cell
2162 <                        CounterCell r = new CounterCell(x); // Optimistic create
2163 <                        if (counterBusy == 0 &&
2164 <                            U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2165 <                            boolean created = false;
2166 <                            try {               // Recheck under lock
2167 <                                CounterCell[] rs; int m, j;
2168 <                                if ((rs = counterCells) != null &&
2169 <                                    (m = rs.length) > 0 &&
2170 <                                    rs[j = (m - 1) & h] == null) {
2171 <                                    rs[j] = r;
2172 <                                    created = true;
2173 <                                }
2174 <                            } finally {
2175 <                                counterBusy = 0;
2176 <                            }
2177 <                            if (created)
2178 <                                break;
2179 <                            continue;           // Slot is now non-empty
2180 <                        }
2181 <                    }
2182 <                    collide = false;
2183 <                }
2184 <                else if (!wasUncontended)       // CAS already known to fail
2185 <                    wasUncontended = true;      // Continue after rehash
2186 <                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2187 <                    break;
2188 <                else if (counterCells != as || n >= NCPU)
2189 <                    collide = false;            // At max size or stale
2190 <                else if (!collide)
2191 <                    collide = true;
2192 <                else if (counterBusy == 0 &&
2193 <                         U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2194 <                    try {
2195 <                        if (counterCells == as) {// Expand table unless stale
2196 <                            CounterCell[] rs = new CounterCell[n << 1];
2197 <                            for (int i = 0; i < n; ++i)
2198 <                                rs[i] = as[i];
2199 <                            counterCells = rs;
2459 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2460 >                synchronized (b) {
2461 >                    if (tabAt(tab, index) == b) {
2462 >                        TreeNode<K,V> hd = null, tl = null;
2463 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2464 >                            TreeNode<K,V> p =
2465 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2466 >                                                  null, null);
2467 >                            if ((p.prev = tl) == null)
2468 >                                hd = p;
2469 >                            else
2470 >                                tl.next = p;
2471 >                            tl = p;
2472                          }
2473 <                    } finally {
2202 <                        counterBusy = 0;
2473 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2474                      }
2204                    collide = false;
2205                    continue;                   // Retry with expanded table
2475                  }
2207                h ^= h << 13;                   // Rehash
2208                h ^= h >>> 17;
2209                h ^= h << 5;
2476              }
2211            else if (counterBusy == 0 && counterCells == as &&
2212                     U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2213                boolean init = false;
2214                try {                           // Initialize table
2215                    if (counterCells == as) {
2216                        CounterCell[] rs = new CounterCell[2];
2217                        rs[h & 1] = new CounterCell(x);
2218                        counterCells = rs;
2219                        init = true;
2220                    }
2221                } finally {
2222                    counterBusy = 0;
2223                }
2224                if (init)
2225                    break;
2226            }
2227            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2228                break;                          // Fall back on using base
2477          }
2230        hc.code = h;                            // Record index for next time
2478      }
2479  
2480 <    /* ----------------Table Traversal -------------- */
2480 >    /**
2481 >     * Returns a list on non-TreeNodes replacing those in given list.
2482 >     */
2483 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2484 >        Node<K,V> hd = null, tl = null;
2485 >        for (Node<K,V> q = b; q != null; q = q.next) {
2486 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2487 >            if (tl == null)
2488 >                hd = p;
2489 >            else
2490 >                tl.next = p;
2491 >            tl = p;
2492 >        }
2493 >        return hd;
2494 >    }
2495 >
2496 >    /* ---------------- TreeNodes -------------- */
2497  
2498      /**
2499 <     * Encapsulates traversal for methods such as containsValue; also
2237 <     * serves as a base class for other iterators and bulk tasks.
2238 <     *
2239 <     * At each step, the iterator snapshots the key ("nextKey") and
2240 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2241 <     * snapshot, has a non-null user value). Because val fields can
2242 <     * change (including to null, indicating deletion), field nextVal
2243 <     * might not be accurate at point of use, but still maintains the
2244 <     * weak consistency property of holding a value that was once
2245 <     * valid. To support iterator.remove, the nextKey field is not
2246 <     * updated (nulled out) when the iterator cannot advance.
2247 <     *
2248 <     * Internal traversals directly access these fields, as in:
2249 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2250 <     *
2251 <     * Exported iterators must track whether the iterator has advanced
2252 <     * (in hasNext vs next) (by setting/checking/nulling field
2253 <     * nextVal), and then extract key, value, or key-value pairs as
2254 <     * return values of next().
2255 <     *
2256 <     * The iterator visits once each still-valid node that was
2257 <     * reachable upon iterator construction. It might miss some that
2258 <     * were added to a bin after the bin was visited, which is OK wrt
2259 <     * consistency guarantees. Maintaining this property in the face
2260 <     * of possible ongoing resizes requires a fair amount of
2261 <     * bookkeeping state that is difficult to optimize away amidst
2262 <     * volatile accesses.  Even so, traversal maintains reasonable
2263 <     * throughput.
2264 <     *
2265 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2266 <     * However, if the table has been resized, then all future steps
2267 <     * must traverse both the bin at the current index as well as at
2268 <     * (index + baseSize); and so on for further resizings. To
2269 <     * paranoically cope with potential sharing by users of iterators
2270 <     * across threads, iteration terminates if a bounds checks fails
2271 <     * for a table read.
2272 <     *
2273 <     * This class extends CountedCompleter to streamline parallel
2274 <     * iteration in bulk operations. This adds only a few fields of
2275 <     * space overhead, which is small enough in cases where it is not
2276 <     * needed to not worry about it.  Because CountedCompleter is
2277 <     * Serializable, but iterators need not be, we need to add warning
2278 <     * suppressions.
2499 >     * Nodes for use in TreeBins
2500       */
2501 <    @SuppressWarnings("serial") static class Traverser<K,V,R>
2502 <        extends CountedCompleter<R> {
2503 <        final ConcurrentHashMapV8<K,V> map;
2504 <        Node<V> next;        // the next entry to use
2505 <        Object nextKey;      // cached key field of next
2506 <        V nextVal;           // cached val field of next
2286 <        Node<V>[] tab;       // current table; updated if resized
2287 <        int index;           // index of bin to use next
2288 <        int baseIndex;       // current index of initial table
2289 <        int baseLimit;       // index bound for initial table
2290 <        int baseSize;        // initial table size
2291 <        int batch;           // split control
2501 >    static final class TreeNode<K,V> extends Node<K,V> {
2502 >        TreeNode<K,V> parent;  // red-black tree links
2503 >        TreeNode<K,V> left;
2504 >        TreeNode<K,V> right;
2505 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2506 >        boolean red;
2507  
2508 <        /** Creates iterator for all entries in the table. */
2509 <        Traverser(ConcurrentHashMapV8<K,V> map) {
2510 <            this.map = map;
2508 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2509 >                 TreeNode<K,V> parent) {
2510 >            super(hash, key, val, next);
2511 >            this.parent = parent;
2512          }
2513  
2514 <        /** Creates iterator for split() methods and task constructors */
2515 <        Traverser(ConcurrentHashMapV8<K,V> map, Traverser<K,V,?> it, int batch) {
2300 <            super(it);
2301 <            this.batch = batch;
2302 <            if ((this.map = map) != null && it != null) { // split parent
2303 <                Node<V>[] t;
2304 <                if ((t = it.tab) == null &&
2305 <                    (t = it.tab = map.table) != null)
2306 <                    it.baseLimit = it.baseSize = t.length;
2307 <                this.tab = t;
2308 <                this.baseSize = it.baseSize;
2309 <                int hi = this.baseLimit = it.baseLimit;
2310 <                it.baseLimit = this.index = this.baseIndex =
2311 <                    (hi + it.baseIndex + 1) >>> 1;
2312 <            }
2514 >        Node<K,V> find(int h, Object k) {
2515 >            return findTreeNode(h, k, null);
2516          }
2517  
2518          /**
2519 <         * Advances next; returns nextVal or null if terminated.
2520 <         * See above for explanation.
2519 >         * Returns the TreeNode (or null if not found) for the given key
2520 >         * starting at given root.
2521           */
2522 <        @SuppressWarnings("unchecked") final V advance() {
2523 <            Node<V> e = next;
2524 <            V ev = null;
2525 <            outer: do {
2526 <                if (e != null)                  // advance past used/skipped node
2527 <                    e = e.next;
2528 <                while (e == null) {             // get to next non-null bin
2529 <                    ConcurrentHashMapV8<K,V> m;
2530 <                    Node<V>[] t; int b, i, n; Object ek; //  must use locals
2531 <                    if ((t = tab) != null)
2532 <                        n = t.length;
2533 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2534 <                        n = baseLimit = baseSize = t.length;
2522 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2523 >            if (k != null) {
2524 >                TreeNode<K,V> p = this;
2525 >                do  {
2526 >                    int ph, dir; K pk; TreeNode<K,V> q;
2527 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2528 >                    if ((ph = p.hash) > h)
2529 >                        p = pl;
2530 >                    else if (ph < h)
2531 >                        p = pr;
2532 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2533 >                        return p;
2534 >                    else if (pl == null && pr == null)
2535 >                        break;
2536 >                    else if ((kc != null ||
2537 >                              (kc = comparableClassFor(k)) != null) &&
2538 >                             (dir = compareComparables(kc, k, pk)) != 0)
2539 >                        p = (dir < 0) ? pl : pr;
2540 >                    else if (pl == null)
2541 >                        p = pr;
2542 >                    else if (pr == null ||
2543 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2544 >                        p = pl;
2545                      else
2546 <                        break outer;
2547 <                    if ((b = baseIndex) >= baseLimit ||
2548 <                        (i = index) < 0 || i >= n)
2549 <                        break outer;
2550 <                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2551 <                        if ((ek = e.key) instanceof TreeBin)
2552 <                            e = ((TreeBin<V>)ek).first;
2553 <                        else {
2554 <                            tab = (Node<V>[])ek;
2555 <                            continue;           // restarts due to null val
2546 >                        return q;
2547 >                } while (p != null);
2548 >            }
2549 >            return null;
2550 >        }
2551 >    }
2552 >
2553 >    /* ---------------- TreeBins -------------- */
2554 >
2555 >    /**
2556 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2557 >     * keys or values, but instead point to list of TreeNodes and
2558 >     * their root. They also maintain a parasitic read-write lock
2559 >     * forcing writers (who hold bin lock) to wait for readers (who do
2560 >     * not) to complete before tree restructuring operations.
2561 >     */
2562 >    static final class TreeBin<K,V> extends Node<K,V> {
2563 >        TreeNode<K,V> root;
2564 >        volatile TreeNode<K,V> first;
2565 >        volatile Thread waiter;
2566 >        volatile int lockState;
2567 >        // values for lockState
2568 >        static final int WRITER = 1; // set while holding write lock
2569 >        static final int WAITER = 2; // set when waiting for write lock
2570 >        static final int READER = 4; // increment value for setting read lock
2571 >
2572 >        /**
2573 >         * Creates bin with initial set of nodes headed by b.
2574 >         */
2575 >        TreeBin(TreeNode<K,V> b) {
2576 >            super(TREEBIN, null, null, null);
2577 >            this.first = b;
2578 >            TreeNode<K,V> r = null;
2579 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2580 >                next = (TreeNode<K,V>)x.next;
2581 >                x.left = x.right = null;
2582 >                if (r == null) {
2583 >                    x.parent = null;
2584 >                    x.red = false;
2585 >                    r = x;
2586 >                }
2587 >                else {
2588 >                    Object key = x.key;
2589 >                    int hash = x.hash;
2590 >                    Class<?> kc = null;
2591 >                    for (TreeNode<K,V> p = r;;) {
2592 >                        int dir, ph;
2593 >                        if ((ph = p.hash) > hash)
2594 >                            dir = -1;
2595 >                        else if (ph < hash)
2596 >                            dir = 1;
2597 >                        else if ((kc != null ||
2598 >                                  (kc = comparableClassFor(key)) != null))
2599 >                            dir = compareComparables(kc, key, p.key);
2600 >                        else
2601 >                            dir = 0;
2602 >                        TreeNode<K,V> xp = p;
2603 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2604 >                            x.parent = xp;
2605 >                            if (dir <= 0)
2606 >                                xp.left = x;
2607 >                            else
2608 >                                xp.right = x;
2609 >                            r = balanceInsertion(r, x);
2610 >                            break;
2611                          }
2612 <                    }                           // visit upper slots if present
2345 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2612 >                    }
2613                  }
2614 <                nextKey = e.key;
2615 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2349 <            next = e;
2350 <            return nextVal = ev;
2614 >            }
2615 >            this.root = r;
2616          }
2617  
2618 <        public final void remove() {
2619 <            Object k = nextKey;
2620 <            if (k == null && (advance() == null || (k = nextKey) == null))
2621 <                throw new IllegalStateException();
2622 <            map.internalReplace(k, null, null);
2618 >        /**
2619 >         * Acquires write lock for tree restructuring.
2620 >         */
2621 >        private final void lockRoot() {
2622 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2623 >                contendedLock(); // offload to separate method
2624          }
2625  
2626 <        public final boolean hasNext() {
2627 <            return nextVal != null || advance() != null;
2626 >        /**
2627 >         * Releases write lock for tree restructuring.
2628 >         */
2629 >        private final void unlockRoot() {
2630 >            lockState = 0;
2631          }
2632  
2364        public final boolean hasMoreElements() { return hasNext(); }
2365
2366        public void compute() { } // default no-op CountedCompleter body
2367
2633          /**
2634 <         * Returns a batch value > 0 if this task should (and must) be
2370 <         * split, if so, adding to pending count, and in any case
2371 <         * updating batch value. The initial batch value is approx
2372 <         * exp2 of the number of times (minus one) to split task by
2373 <         * two before executing leaf action. This value is faster to
2374 <         * compute and more convenient to use as a guide to splitting
2375 <         * than is the depth, since it is used while dividing by two
2376 <         * anyway.
2634 >         * Possibly blocks awaiting root lock.
2635           */
2636 <        final int preSplit() {
2637 <            ConcurrentHashMapV8<K,V> m; int b; Node<V>[] t;  ForkJoinPool pool;
2638 <            if ((b = batch) < 0 && (m = map) != null) { // force initialization
2639 <                if ((t = tab) == null && (t = tab = m.table) != null)
2640 <                    baseLimit = baseSize = t.length;
2641 <                if (t != null) {
2642 <                    long n = m.sumCount();
2643 <                    int par = ((pool = getPool()) == null) ?
2644 <                        ForkJoinPool.getCommonPoolParallelism() :
2645 <                        pool.getParallelism();
2646 <                    int sp = par << 3; // slack of 8
2647 <                    b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2648 <                }
2649 <            }
2650 <            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2651 <            if ((batch = b) > 0)
2652 <                addToPendingCount(1);
2653 <            return b;
2636 >        private final void contendedLock() {
2637 >            boolean waiting = false;
2638 >            for (int s;;) {
2639 >                if (((s = lockState) & WRITER) == 0) {
2640 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2641 >                        if (waiting)
2642 >                            waiter = null;
2643 >                        return;
2644 >                    }
2645 >                }
2646 >                else if ((s | WAITER) == 0) {
2647 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2648 >                        waiting = true;
2649 >                        waiter = Thread.currentThread();
2650 >                    }
2651 >                }
2652 >                else if (waiting)
2653 >                    LockSupport.park(this);
2654 >            }
2655          }
2656  
2657 <    }
2658 <
2659 <    /* ---------------- Public operations -------------- */
2660 <
2661 <    /**
2662 <     * Creates a new, empty map with the default initial table size (16).
2663 <     */
2664 <    public ConcurrentHashMapV8() {
2665 <    }
2666 <
2667 <    /**
2668 <     * Creates a new, empty map with an initial table size
2669 <     * accommodating the specified number of elements without the need
2670 <     * to dynamically resize.
2671 <     *
2672 <     * @param initialCapacity The implementation performs internal
2673 <     * sizing to accommodate this many elements.
2674 <     * @throws IllegalArgumentException if the initial capacity of
2675 <     * elements is negative
2676 <     */
2677 <    public ConcurrentHashMapV8(int initialCapacity) {
2678 <        if (initialCapacity < 0)
2679 <            throw new IllegalArgumentException();
2680 <        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2681 <                   MAXIMUM_CAPACITY :
2682 <                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2683 <        this.sizeCtl = cap;
2684 <    }
2685 <
2686 <    /**
2687 <     * Creates a new map with the same mappings as the given map.
2688 <     *
2689 <     * @param m the map
2690 <     */
2432 <    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2433 <        this.sizeCtl = DEFAULT_CAPACITY;
2434 <        internalPutAll(m);
2435 <    }
2436 <
2437 <    /**
2438 <     * Creates a new, empty map with an initial table size based on
2439 <     * the given number of elements ({@code initialCapacity}) and
2440 <     * initial table density ({@code loadFactor}).
2441 <     *
2442 <     * @param initialCapacity the initial capacity. The implementation
2443 <     * performs internal sizing to accommodate this many elements,
2444 <     * given the specified load factor.
2445 <     * @param loadFactor the load factor (table density) for
2446 <     * establishing the initial table size
2447 <     * @throws IllegalArgumentException if the initial capacity of
2448 <     * elements is negative or the load factor is nonpositive
2449 <     *
2450 <     * @since 1.6
2451 <     */
2452 <    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
2453 <        this(initialCapacity, loadFactor, 1);
2454 <    }
2455 <
2456 <    /**
2457 <     * Creates a new, empty map with an initial table size based on
2458 <     * the given number of elements ({@code initialCapacity}), table
2459 <     * density ({@code loadFactor}), and number of concurrently
2460 <     * updating threads ({@code concurrencyLevel}).
2461 <     *
2462 <     * @param initialCapacity the initial capacity. The implementation
2463 <     * performs internal sizing to accommodate this many elements,
2464 <     * given the specified load factor.
2465 <     * @param loadFactor the load factor (table density) for
2466 <     * establishing the initial table size
2467 <     * @param concurrencyLevel the estimated number of concurrently
2468 <     * updating threads. The implementation may use this value as
2469 <     * a sizing hint.
2470 <     * @throws IllegalArgumentException if the initial capacity is
2471 <     * negative or the load factor or concurrencyLevel are
2472 <     * nonpositive
2473 <     */
2474 <    public ConcurrentHashMapV8(int initialCapacity,
2475 <                               float loadFactor, int concurrencyLevel) {
2476 <        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2477 <            throw new IllegalArgumentException();
2478 <        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2479 <            initialCapacity = concurrencyLevel;   // as estimated threads
2480 <        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2481 <        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2482 <            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2483 <        this.sizeCtl = cap;
2484 <    }
2485 <
2486 <    /**
2487 <     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2488 <     * from the given type to {@code Boolean.TRUE}.
2489 <     *
2490 <     * @return the new set
2491 <     */
2492 <    public static <K> KeySetView<K,Boolean> newKeySet() {
2493 <        return new KeySetView<K,Boolean>(new ConcurrentHashMapV8<K,Boolean>(),
2494 <                                      Boolean.TRUE);
2495 <    }
2496 <
2497 <    /**
2498 <     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2499 <     * from the given type to {@code Boolean.TRUE}.
2500 <     *
2501 <     * @param initialCapacity The implementation performs internal
2502 <     * sizing to accommodate this many elements.
2503 <     * @throws IllegalArgumentException if the initial capacity of
2504 <     * elements is negative
2505 <     * @return the new set
2506 <     */
2507 <    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2508 <        return new KeySetView<K,Boolean>
2509 <            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2510 <    }
2511 <
2512 <    /**
2513 <     * {@inheritDoc}
2514 <     */
2515 <    public boolean isEmpty() {
2516 <        return sumCount() <= 0L; // ignore transient negative values
2517 <    }
2518 <
2519 <    /**
2520 <     * {@inheritDoc}
2521 <     */
2522 <    public int size() {
2523 <        long n = sumCount();
2524 <        return ((n < 0L) ? 0 :
2525 <                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2526 <                (int)n);
2527 <    }
2528 <
2529 <    /**
2530 <     * Returns the number of mappings. This method should be used
2531 <     * instead of {@link #size} because a ConcurrentHashMapV8 may
2532 <     * contain more mappings than can be represented as an int. The
2533 <     * value returned is an estimate; the actual count may differ if
2534 <     * there are concurrent insertions or removals.
2535 <     *
2536 <     * @return the number of mappings
2537 <     */
2538 <    public long mappingCount() {
2539 <        long n = sumCount();
2540 <        return (n < 0L) ? 0L : n; // ignore transient negative values
2541 <    }
2542 <
2543 <    /**
2544 <     * Returns the value to which the specified key is mapped,
2545 <     * or {@code null} if this map contains no mapping for the key.
2546 <     *
2547 <     * <p>More formally, if this map contains a mapping from a key
2548 <     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2549 <     * then this method returns {@code v}; otherwise it returns
2550 <     * {@code null}.  (There can be at most one such mapping.)
2551 <     *
2552 <     * @throws NullPointerException if the specified key is null
2553 <     */
2554 <    public V get(Object key) {
2555 <        return internalGet(key);
2556 <    }
2557 <
2558 <    /**
2559 <     * Returns the value to which the specified key is mapped,
2560 <     * or the given defaultValue if this map contains no mapping for the key.
2561 <     *
2562 <     * @param key the key
2563 <     * @param defaultValue the value to return if this map contains
2564 <     * no mapping for the given key
2565 <     * @return the mapping for the key, if present; else the defaultValue
2566 <     * @throws NullPointerException if the specified key is null
2567 <     */
2568 <    public V getValueOrDefault(Object key, V defaultValue) {
2569 <        V v;
2570 <        return (v = internalGet(key)) == null ? defaultValue : v;
2571 <    }
2572 <
2573 <    /**
2574 <     * Tests if the specified object is a key in this table.
2575 <     *
2576 <     * @param  key possible key
2577 <     * @return {@code true} if and only if the specified object
2578 <     *         is a key in this table, as determined by the
2579 <     *         {@code equals} method; {@code false} otherwise
2580 <     * @throws NullPointerException if the specified key is null
2581 <     */
2582 <    public boolean containsKey(Object key) {
2583 <        return internalGet(key) != null;
2584 <    }
2585 <
2586 <    /**
2587 <     * Returns {@code true} if this map maps one or more keys to the
2588 <     * specified value. Note: This method may require a full traversal
2589 <     * of the map, and is much slower than method {@code containsKey}.
2590 <     *
2591 <     * @param value value whose presence in this map is to be tested
2592 <     * @return {@code true} if this map maps one or more keys to the
2593 <     *         specified value
2594 <     * @throws NullPointerException if the specified value is null
2595 <     */
2596 <    public boolean containsValue(Object value) {
2597 <        if (value == null)
2598 <            throw new NullPointerException();
2599 <        V v;
2600 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2601 <        while ((v = it.advance()) != null) {
2602 <            if (v == value || value.equals(v))
2603 <                return true;
2657 >        /**
2658 >         * Returns matching node or null if none. Tries to search
2659 >         * using tree comparisons from root, but continues linear
2660 >         * search when lock not available.
2661 >         */
2662 >        final Node<K,V> find(int h, Object k) {
2663 >            if (k != null) {
2664 >                for (Node<K,V> e = first; e != null; e = e.next) {
2665 >                    int s; K ek;
2666 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2667 >                        if (e.hash == h &&
2668 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2669 >                            return e;
2670 >                    }
2671 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2672 >                                                 s + READER)) {
2673 >                        TreeNode<K,V> r, p;
2674 >                        try {
2675 >                            p = ((r = root) == null ? null :
2676 >                                 r.findTreeNode(h, k, null));
2677 >                        } finally {
2678 >                            Thread w;
2679 >                            int ls;
2680 >                            do {} while (!U.compareAndSwapInt
2681 >                                         (this, LOCKSTATE,
2682 >                                          ls = lockState, ls - READER));
2683 >                            if (ls == (READER|WAITER) && (w = waiter) != null)
2684 >                                LockSupport.unpark(w);
2685 >                        }
2686 >                        return p;
2687 >                    }
2688 >                }
2689 >            }
2690 >            return null;
2691          }
2605        return false;
2606    }
2607
2608    /**
2609     * Legacy method testing if some key maps into the specified value
2610     * in this table.  This method is identical in functionality to
2611     * {@link #containsValue}, and exists solely to ensure
2612     * full compatibility with class {@link java.util.Hashtable},
2613     * which supported this method prior to introduction of the
2614     * Java Collections framework.
2615     *
2616     * @param  value a value to search for
2617     * @return {@code true} if and only if some key maps to the
2618     *         {@code value} argument in this table as
2619     *         determined by the {@code equals} method;
2620     *         {@code false} otherwise
2621     * @throws NullPointerException if the specified value is null
2622     */
2623    @Deprecated public boolean contains(Object value) {
2624        return containsValue(value);
2625    }
2626
2627    /**
2628     * Maps the specified key to the specified value in this table.
2629     * Neither the key nor the value can be null.
2630     *
2631     * <p>The value can be retrieved by calling the {@code get} method
2632     * with a key that is equal to the original key.
2633     *
2634     * @param key key with which the specified value is to be associated
2635     * @param value value to be associated with the specified key
2636     * @return the previous value associated with {@code key}, or
2637     *         {@code null} if there was no mapping for {@code key}
2638     * @throws NullPointerException if the specified key or value is null
2639     */
2640    public V put(K key, V value) {
2641        return internalPut(key, value, false);
2642    }
2643
2644    /**
2645     * {@inheritDoc}
2646     *
2647     * @return the previous value associated with the specified key,
2648     *         or {@code null} if there was no mapping for the key
2649     * @throws NullPointerException if the specified key or value is null
2650     */
2651    public V putIfAbsent(K key, V value) {
2652        return internalPut(key, value, true);
2653    }
2654
2655    /**
2656     * Copies all of the mappings from the specified map to this one.
2657     * These mappings replace any mappings that this map had for any of the
2658     * keys currently in the specified map.
2659     *
2660     * @param m mappings to be stored in this map
2661     */
2662    public void putAll(Map<? extends K, ? extends V> m) {
2663        internalPutAll(m);
2664    }
2665
2666    /**
2667     * If the specified key is not already associated with a value,
2668     * computes its value using the given mappingFunction and enters
2669     * it into the map unless null.  This is equivalent to
2670     * <pre> {@code
2671     * if (map.containsKey(key))
2672     *   return map.get(key);
2673     * value = mappingFunction.apply(key);
2674     * if (value != null)
2675     *   map.put(key, value);
2676     * return value;}</pre>
2677     *
2678     * except that the action is performed atomically.  If the
2679     * function returns {@code null} no mapping is recorded. If the
2680     * function itself throws an (unchecked) exception, the exception
2681     * is rethrown to its caller, and no mapping is recorded.  Some
2682     * attempted update operations on this map by other threads may be
2683     * blocked while computation is in progress, so the computation
2684     * should be short and simple, and must not attempt to update any
2685     * other mappings of this Map. The most appropriate usage is to
2686     * construct a new object serving as an initial mapped value, or
2687     * memoized result, as in:
2688     *
2689     *  <pre> {@code
2690     * map.computeIfAbsent(key, new Fun<K,V>() {
2691     *   public V map(K k) { return new Value(f(k)); }});}</pre>
2692     *
2693     * @param key key with which the specified value is to be associated
2694     * @param mappingFunction the function to compute a value
2695     * @return the current (existing or computed) value associated with
2696     *         the specified key, or null if the computed value is null
2697     * @throws NullPointerException if the specified key or mappingFunction
2698     *         is null
2699     * @throws IllegalStateException if the computation detectably
2700     *         attempts a recursive update to this map that would
2701     *         otherwise never complete
2702     * @throws RuntimeException or Error if the mappingFunction does so,
2703     *         in which case the mapping is left unestablished
2704     */
2705    public V computeIfAbsent
2706        (K key, Fun<? super K, ? extends V> mappingFunction) {
2707        return internalComputeIfAbsent(key, mappingFunction);
2708    }
2709
2710    /**
2711     * If the given key is present, computes a new mapping value given a key and
2712     * its current mapped value. This is equivalent to
2713     *  <pre> {@code
2714     *   if (map.containsKey(key)) {
2715     *     value = remappingFunction.apply(key, map.get(key));
2716     *     if (value != null)
2717     *       map.put(key, value);
2718     *     else
2719     *       map.remove(key);
2720     *   }
2721     * }</pre>
2722     *
2723     * except that the action is performed atomically.  If the
2724     * function returns {@code null}, the mapping is removed.  If the
2725     * function itself throws an (unchecked) exception, the exception
2726     * is rethrown to its caller, and the current mapping is left
2727     * unchanged.  Some attempted update operations on this map by
2728     * other threads may be blocked while computation is in progress,
2729     * so the computation should be short and simple, and must not
2730     * attempt to update any other mappings of this Map. For example,
2731     * to either create or append new messages to a value mapping:
2732     *
2733     * @param key key with which the specified value is to be associated
2734     * @param remappingFunction the function to compute a value
2735     * @return the new value associated with the specified key, or null if none
2736     * @throws NullPointerException if the specified key or remappingFunction
2737     *         is null
2738     * @throws IllegalStateException if the computation detectably
2739     *         attempts a recursive update to this map that would
2740     *         otherwise never complete
2741     * @throws RuntimeException or Error if the remappingFunction does so,
2742     *         in which case the mapping is unchanged
2743     */
2744    public V computeIfPresent
2745        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2746        return internalCompute(key, true, remappingFunction);
2747    }
2748
2749    /**
2750     * Computes a new mapping value given a key and
2751     * its current mapped value (or {@code null} if there is no current
2752     * mapping). This is equivalent to
2753     *  <pre> {@code
2754     *   value = remappingFunction.apply(key, map.get(key));
2755     *   if (value != null)
2756     *     map.put(key, value);
2757     *   else
2758     *     map.remove(key);
2759     * }</pre>
2760     *
2761     * except that the action is performed atomically.  If the
2762     * function returns {@code null}, the mapping is removed.  If the
2763     * function itself throws an (unchecked) exception, the exception
2764     * is rethrown to its caller, and the current mapping is left
2765     * unchanged.  Some attempted update operations on this map by
2766     * other threads may be blocked while computation is in progress,
2767     * so the computation should be short and simple, and must not
2768     * attempt to update any other mappings of this Map. For example,
2769     * to either create or append new messages to a value mapping:
2770     *
2771     * <pre> {@code
2772     * Map<Key, String> map = ...;
2773     * final String msg = ...;
2774     * map.compute(key, new BiFun<Key, String, String>() {
2775     *   public String apply(Key k, String v) {
2776     *    return (v == null) ? msg : v + msg;});}}</pre>
2777     *
2778     * @param key key with which the specified value is to be associated
2779     * @param remappingFunction the function to compute a value
2780     * @return the new value associated with the specified key, or null if none
2781     * @throws NullPointerException if the specified key or remappingFunction
2782     *         is null
2783     * @throws IllegalStateException if the computation detectably
2784     *         attempts a recursive update to this map that would
2785     *         otherwise never complete
2786     * @throws RuntimeException or Error if the remappingFunction does so,
2787     *         in which case the mapping is unchanged
2788     */
2789    public V compute
2790        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2791        return internalCompute(key, false, remappingFunction);
2792    }
2793
2794    /**
2795     * If the specified key is not already associated
2796     * with a value, associate it with the given value.
2797     * Otherwise, replace the value with the results of
2798     * the given remapping function. This is equivalent to:
2799     *  <pre> {@code
2800     *   if (!map.containsKey(key))
2801     *     map.put(value);
2802     *   else {
2803     *     newValue = remappingFunction.apply(map.get(key), value);
2804     *     if (value != null)
2805     *       map.put(key, value);
2806     *     else
2807     *       map.remove(key);
2808     *   }
2809     * }</pre>
2810     * except that the action is performed atomically.  If the
2811     * function returns {@code null}, the mapping is removed.  If the
2812     * function itself throws an (unchecked) exception, the exception
2813     * is rethrown to its caller, and the current mapping is left
2814     * unchanged.  Some attempted update operations on this map by
2815     * other threads may be blocked while computation is in progress,
2816     * so the computation should be short and simple, and must not
2817     * attempt to update any other mappings of this Map.
2818     */
2819    public V merge
2820        (K key, V value,
2821         BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2822        return internalMerge(key, value, remappingFunction);
2823    }
2692  
2693 <    /**
2694 <     * Removes the key (and its corresponding value) from this map.
2695 <     * This method does nothing if the key is not in the map.
2696 <     *
2697 <     * @param  key the key that needs to be removed
2698 <     * @return the previous value associated with {@code key}, or
2699 <     *         {@code null} if there was no mapping for {@code key}
2700 <     * @throws NullPointerException if the specified key is null
2701 <     */
2702 <    public V remove(Object key) {
2703 <        return internalReplace(key, null, null);
2704 <    }
2693 >        /**
2694 >         * Finds or adds a node.
2695 >         * @return null if added
2696 >         */
2697 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2698 >            Class<?> kc = null;
2699 >            for (TreeNode<K,V> p = root;;) {
2700 >                int dir, ph; K pk; TreeNode<K,V> q, pr;
2701 >                if (p == null) {
2702 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2703 >                    break;
2704 >                }
2705 >                else if ((ph = p.hash) > h)
2706 >                    dir = -1;
2707 >                else if (ph < h)
2708 >                    dir = 1;
2709 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2710 >                    return p;
2711 >                else if ((kc == null &&
2712 >                          (kc = comparableClassFor(k)) == null) ||
2713 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2714 >                    if (p.left == null)
2715 >                        dir = 1;
2716 >                    else if ((pr = p.right) == null ||
2717 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2718 >                        dir = -1;
2719 >                    else
2720 >                        return q;
2721 >                }
2722 >                TreeNode<K,V> xp = p;
2723 >                if ((p = (dir < 0) ? p.left : p.right) == null) {
2724 >                    TreeNode<K,V> x, f = first;
2725 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2726 >                    if (f != null)
2727 >                        f.prev = x;
2728 >                    if (dir < 0)
2729 >                        xp.left = x;
2730 >                    else
2731 >                        xp.right = x;
2732 >                    if (!xp.red)
2733 >                        x.red = true;
2734 >                    else {
2735 >                        lockRoot();
2736 >                        try {
2737 >                            root = balanceInsertion(root, x);
2738 >                        } finally {
2739 >                            unlockRoot();
2740 >                        }
2741 >                    }
2742 >                    break;
2743 >                }
2744 >            }
2745 >            assert checkInvariants(root);
2746 >            return null;
2747 >        }
2748  
2749 <    /**
2750 <     * {@inheritDoc}
2751 <     *
2752 <     * @throws NullPointerException if the specified key is null
2753 <     */
2754 <    public boolean remove(Object key, Object value) {
2755 <        return value != null && internalReplace(key, null, value) != null;
2756 <    }
2749 >        /**
2750 >         * Removes the given node, that must be present before this
2751 >         * call.  This is messier than typical red-black deletion code
2752 >         * because we cannot swap the contents of an interior node
2753 >         * with a leaf successor that is pinned by "next" pointers
2754 >         * that are accessible independently of lock. So instead we
2755 >         * swap the tree linkages.
2756 >         *
2757 >         * @return true if now too small, so should be untreeified
2758 >         */
2759 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2760 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2761 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2762 >            TreeNode<K,V> r, rl;
2763 >            if (pred == null)
2764 >                first = next;
2765 >            else
2766 >                pred.next = next;
2767 >            if (next != null)
2768 >                next.prev = pred;
2769 >            if (first == null) {
2770 >                root = null;
2771 >                return true;
2772 >            }
2773 >            if ((r = root) == null || r.right == null || // too small
2774 >                (rl = r.left) == null || rl.left == null)
2775 >                return true;
2776 >            lockRoot();
2777 >            try {
2778 >                TreeNode<K,V> replacement;
2779 >                TreeNode<K,V> pl = p.left;
2780 >                TreeNode<K,V> pr = p.right;
2781 >                if (pl != null && pr != null) {
2782 >                    TreeNode<K,V> s = pr, sl;
2783 >                    while ((sl = s.left) != null) // find successor
2784 >                        s = sl;
2785 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2786 >                    TreeNode<K,V> sr = s.right;
2787 >                    TreeNode<K,V> pp = p.parent;
2788 >                    if (s == pr) { // p was s's direct parent
2789 >                        p.parent = s;
2790 >                        s.right = p;
2791 >                    }
2792 >                    else {
2793 >                        TreeNode<K,V> sp = s.parent;
2794 >                        if ((p.parent = sp) != null) {
2795 >                            if (s == sp.left)
2796 >                                sp.left = p;
2797 >                            else
2798 >                                sp.right = p;
2799 >                        }
2800 >                        if ((s.right = pr) != null)
2801 >                            pr.parent = s;
2802 >                    }
2803 >                    p.left = null;
2804 >                    if ((p.right = sr) != null)
2805 >                        sr.parent = p;
2806 >                    if ((s.left = pl) != null)
2807 >                        pl.parent = s;
2808 >                    if ((s.parent = pp) == null)
2809 >                        r = s;
2810 >                    else if (p == pp.left)
2811 >                        pp.left = s;
2812 >                    else
2813 >                        pp.right = s;
2814 >                    if (sr != null)
2815 >                        replacement = sr;
2816 >                    else
2817 >                        replacement = p;
2818 >                }
2819 >                else if (pl != null)
2820 >                    replacement = pl;
2821 >                else if (pr != null)
2822 >                    replacement = pr;
2823 >                else
2824 >                    replacement = p;
2825 >                if (replacement != p) {
2826 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2827 >                    if (pp == null)
2828 >                        r = replacement;
2829 >                    else if (p == pp.left)
2830 >                        pp.left = replacement;
2831 >                    else
2832 >                        pp.right = replacement;
2833 >                    p.left = p.right = p.parent = null;
2834 >                }
2835  
2836 <    /**
2848 <     * {@inheritDoc}
2849 <     *
2850 <     * @throws NullPointerException if any of the arguments are null
2851 <     */
2852 <    public boolean replace(K key, V oldValue, V newValue) {
2853 <        if (key == null || oldValue == null || newValue == null)
2854 <            throw new NullPointerException();
2855 <        return internalReplace(key, newValue, oldValue) != null;
2856 <    }
2836 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2837  
2838 <    /**
2839 <     * {@inheritDoc}
2840 <     *
2841 <     * @return the previous value associated with the specified key,
2842 <     *         or {@code null} if there was no mapping for the key
2843 <     * @throws NullPointerException if the specified key or value is null
2844 <     */
2845 <    public V replace(K key, V value) {
2846 <        if (key == null || value == null)
2847 <            throw new NullPointerException();
2848 <        return internalReplace(key, value, null);
2849 <    }
2850 <
2851 <    /**
2852 <     * Removes all of the mappings from this map.
2853 <     */
2874 <    public void clear() {
2875 <        internalClear();
2876 <    }
2838 >                if (p == replacement) {  // detach pointers
2839 >                    TreeNode<K,V> pp;
2840 >                    if ((pp = p.parent) != null) {
2841 >                        if (p == pp.left)
2842 >                            pp.left = null;
2843 >                        else if (p == pp.right)
2844 >                            pp.right = null;
2845 >                        p.parent = null;
2846 >                    }
2847 >                }
2848 >            } finally {
2849 >                unlockRoot();
2850 >            }
2851 >            assert checkInvariants(root);
2852 >            return false;
2853 >        }
2854  
2855 <    /**
2856 <     * Returns a {@link Set} view of the keys contained in this map.
2880 <     * The set is backed by the map, so changes to the map are
2881 <     * reflected in the set, and vice-versa.
2882 <     *
2883 <     * @return the set view
2884 <     */
2885 <    public KeySetView<K,V> keySet() {
2886 <        KeySetView<K,V> ks = keySet;
2887 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2888 <    }
2855 >        /* ------------------------------------------------------------ */
2856 >        // Red-black tree methods, all adapted from CLR
2857  
2858 <    /**
2859 <     * Returns a {@link Set} view of the keys in this map, using the
2860 <     * given common mapped value for any additions (i.e., {@link
2861 <     * Collection#add} and {@link Collection#addAll}). This is of
2862 <     * course only appropriate if it is acceptable to use the same
2863 <     * value for all additions from this view.
2864 <     *
2865 <     * @param mappedValue the mapped value to use for any additions
2866 <     * @return the set view
2867 <     * @throws NullPointerException if the mappedValue is null
2868 <     */
2869 <    public KeySetView<K,V> keySet(V mappedValue) {
2870 <        if (mappedValue == null)
2871 <            throw new NullPointerException();
2872 <        return new KeySetView<K,V>(this, mappedValue);
2873 <    }
2858 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2859 >                                              TreeNode<K,V> p) {
2860 >            TreeNode<K,V> r, pp, rl;
2861 >            if (p != null && (r = p.right) != null) {
2862 >                if ((rl = p.right = r.left) != null)
2863 >                    rl.parent = p;
2864 >                if ((pp = r.parent = p.parent) == null)
2865 >                    (root = r).red = false;
2866 >                else if (pp.left == p)
2867 >                    pp.left = r;
2868 >                else
2869 >                    pp.right = r;
2870 >                r.left = p;
2871 >                p.parent = r;
2872 >            }
2873 >            return root;
2874 >        }
2875  
2876 <    /**
2877 <     * Returns a {@link Collection} view of the values contained in this map.
2878 <     * The collection is backed by the map, so changes to the map are
2879 <     * reflected in the collection, and vice-versa.
2880 <     */
2881 <    public ValuesView<K,V> values() {
2882 <        ValuesView<K,V> vs = values;
2883 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2884 <    }
2876 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2877 >                                               TreeNode<K,V> p) {
2878 >            TreeNode<K,V> l, pp, lr;
2879 >            if (p != null && (l = p.left) != null) {
2880 >                if ((lr = p.left = l.right) != null)
2881 >                    lr.parent = p;
2882 >                if ((pp = l.parent = p.parent) == null)
2883 >                    (root = l).red = false;
2884 >                else if (pp.right == p)
2885 >                    pp.right = l;
2886 >                else
2887 >                    pp.left = l;
2888 >                l.right = p;
2889 >                p.parent = l;
2890 >            }
2891 >            return root;
2892 >        }
2893  
2894 <    /**
2895 <     * Returns a {@link Set} view of the mappings contained in this map.
2896 <     * The set is backed by the map, so changes to the map are
2897 <     * reflected in the set, and vice-versa.  The set supports element
2898 <     * removal, which removes the corresponding mapping from the map,
2899 <     * via the {@code Iterator.remove}, {@code Set.remove},
2900 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
2901 <     * operations.  It does not support the {@code add} or
2902 <     * {@code addAll} operations.
2903 <     *
2904 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2905 <     * that will never throw {@link ConcurrentModificationException},
2906 <     * and guarantees to traverse elements as they existed upon
2907 <     * construction of the iterator, and may (but is not guaranteed to)
2908 <     * reflect any modifications subsequent to construction.
2909 <     */
2910 <    public Set<Map.Entry<K,V>> entrySet() {
2911 <        EntrySetView<K,V> es = entrySet;
2912 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2913 <    }
2894 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2895 >                                                    TreeNode<K,V> x) {
2896 >            x.red = true;
2897 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2898 >                if ((xp = x.parent) == null) {
2899 >                    x.red = false;
2900 >                    return x;
2901 >                }
2902 >                else if (!xp.red || (xpp = xp.parent) == null)
2903 >                    return root;
2904 >                if (xp == (xppl = xpp.left)) {
2905 >                    if ((xppr = xpp.right) != null && xppr.red) {
2906 >                        xppr.red = false;
2907 >                        xp.red = false;
2908 >                        xpp.red = true;
2909 >                        x = xpp;
2910 >                    }
2911 >                    else {
2912 >                        if (x == xp.right) {
2913 >                            root = rotateLeft(root, x = xp);
2914 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2915 >                        }
2916 >                        if (xp != null) {
2917 >                            xp.red = false;
2918 >                            if (xpp != null) {
2919 >                                xpp.red = true;
2920 >                                root = rotateRight(root, xpp);
2921 >                            }
2922 >                        }
2923 >                    }
2924 >                }
2925 >                else {
2926 >                    if (xppl != null && xppl.red) {
2927 >                        xppl.red = false;
2928 >                        xp.red = false;
2929 >                        xpp.red = true;
2930 >                        x = xpp;
2931 >                    }
2932 >                    else {
2933 >                        if (x == xp.left) {
2934 >                            root = rotateRight(root, x = xp);
2935 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2936 >                        }
2937 >                        if (xp != null) {
2938 >                            xp.red = false;
2939 >                            if (xpp != null) {
2940 >                                xpp.red = true;
2941 >                                root = rotateLeft(root, xpp);
2942 >                            }
2943 >                        }
2944 >                    }
2945 >                }
2946 >            }
2947 >        }
2948  
2949 <    /**
2950 <     * Returns an enumeration of the keys in this table.
2951 <     *
2952 <     * @return an enumeration of the keys in this table
2953 <     * @see #keySet()
2954 <     */
2955 <    public Enumeration<K> keys() {
2956 <        return new KeyIterator<K,V>(this);
2957 <    }
2949 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2950 >                                                   TreeNode<K,V> x) {
2951 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
2952 >                if (x == null || x == root)
2953 >                    return root;
2954 >                else if ((xp = x.parent) == null) {
2955 >                    x.red = false;
2956 >                    return x;
2957 >                }
2958 >                else if (x.red) {
2959 >                    x.red = false;
2960 >                    return root;
2961 >                }
2962 >                else if ((xpl = xp.left) == x) {
2963 >                    if ((xpr = xp.right) != null && xpr.red) {
2964 >                        xpr.red = false;
2965 >                        xp.red = true;
2966 >                        root = rotateLeft(root, xp);
2967 >                        xpr = (xp = x.parent) == null ? null : xp.right;
2968 >                    }
2969 >                    if (xpr == null)
2970 >                        x = xp;
2971 >                    else {
2972 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
2973 >                        if ((sr == null || !sr.red) &&
2974 >                            (sl == null || !sl.red)) {
2975 >                            xpr.red = true;
2976 >                            x = xp;
2977 >                        }
2978 >                        else {
2979 >                            if (sr == null || !sr.red) {
2980 >                                if (sl != null)
2981 >                                    sl.red = false;
2982 >                                xpr.red = true;
2983 >                                root = rotateRight(root, xpr);
2984 >                                xpr = (xp = x.parent) == null ?
2985 >                                    null : xp.right;
2986 >                            }
2987 >                            if (xpr != null) {
2988 >                                xpr.red = (xp == null) ? false : xp.red;
2989 >                                if ((sr = xpr.right) != null)
2990 >                                    sr.red = false;
2991 >                            }
2992 >                            if (xp != null) {
2993 >                                xp.red = false;
2994 >                                root = rotateLeft(root, xp);
2995 >                            }
2996 >                            x = root;
2997 >                        }
2998 >                    }
2999 >                }
3000 >                else { // symmetric
3001 >                    if (xpl != null && xpl.red) {
3002 >                        xpl.red = false;
3003 >                        xp.red = true;
3004 >                        root = rotateRight(root, xp);
3005 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3006 >                    }
3007 >                    if (xpl == null)
3008 >                        x = xp;
3009 >                    else {
3010 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3011 >                        if ((sl == null || !sl.red) &&
3012 >                            (sr == null || !sr.red)) {
3013 >                            xpl.red = true;
3014 >                            x = xp;
3015 >                        }
3016 >                        else {
3017 >                            if (sl == null || !sl.red) {
3018 >                                if (sr != null)
3019 >                                    sr.red = false;
3020 >                                xpl.red = true;
3021 >                                root = rotateLeft(root, xpl);
3022 >                                xpl = (xp = x.parent) == null ?
3023 >                                    null : xp.left;
3024 >                            }
3025 >                            if (xpl != null) {
3026 >                                xpl.red = (xp == null) ? false : xp.red;
3027 >                                if ((sl = xpl.left) != null)
3028 >                                    sl.red = false;
3029 >                            }
3030 >                            if (xp != null) {
3031 >                                xp.red = false;
3032 >                                root = rotateRight(root, xp);
3033 >                            }
3034 >                            x = root;
3035 >                        }
3036 >                    }
3037 >                }
3038 >            }
3039 >        }
3040  
3041 <    /**
3042 <     * Returns an enumeration of the values in this table.
3043 <     *
3044 <     * @return an enumeration of the values in this table
3045 <     * @see #values()
3046 <     */
3047 <    public Enumeration<V> elements() {
3048 <        return new ValueIterator<K,V>(this);
3049 <    }
3041 >        /**
3042 >         * Recursive invariant check
3043 >         */
3044 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3045 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3046 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3047 >            if (tb != null && tb.next != t)
3048 >                return false;
3049 >            if (tn != null && tn.prev != t)
3050 >                return false;
3051 >            if (tp != null && t != tp.left && t != tp.right)
3052 >                return false;
3053 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3054 >                return false;
3055 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3056 >                return false;
3057 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3058 >                return false;
3059 >            if (tl != null && !checkInvariants(tl))
3060 >                return false;
3061 >            if (tr != null && !checkInvariants(tr))
3062 >                return false;
3063 >            return true;
3064 >        }
3065  
3066 <    /**
3067 <     * Returns a partitionable iterator of the keys in this map.
3068 <     *
3069 <     * @return a partitionable iterator of the keys in this map
3070 <     */
3071 <    public Spliterator<K> keySpliterator() {
3072 <        return new KeyIterator<K,V>(this);
3066 >        private static final sun.misc.Unsafe U;
3067 >        private static final long LOCKSTATE;
3068 >        static {
3069 >            try {
3070 >                U = getUnsafe();
3071 >                Class<?> k = TreeBin.class;
3072 >                LOCKSTATE = U.objectFieldOffset
3073 >                    (k.getDeclaredField("lockState"));
3074 >            } catch (Exception e) {
3075 >                throw new Error(e);
3076 >            }
3077 >        }
3078      }
3079  
3080 <    /**
2968 <     * Returns a partitionable iterator of the values in this map.
2969 <     *
2970 <     * @return a partitionable iterator of the values in this map
2971 <     */
2972 <    public Spliterator<V> valueSpliterator() {
2973 <        return new ValueIterator<K,V>(this);
2974 <    }
3080 >    /* ----------------Table Traversal -------------- */
3081  
3082      /**
3083 <     * Returns a partitionable iterator of the entries in this map.
3083 >     * Encapsulates traversal for methods such as containsValue; also
3084 >     * serves as a base class for other iterators and spliterators.
3085       *
3086 <     * @return a partitionable iterator of the entries in this map
3087 <     */
3088 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
3089 <        return new EntryIterator<K,V>(this);
3090 <    }
3091 <
3092 <    /**
3093 <     * Returns the hash code value for this {@link Map}, i.e.,
2987 <     * the sum of, for each key-value pair in the map,
2988 <     * {@code key.hashCode() ^ value.hashCode()}.
3086 >     * Method advance visits once each still-valid node that was
3087 >     * reachable upon iterator construction. It might miss some that
3088 >     * were added to a bin after the bin was visited, which is OK wrt
3089 >     * consistency guarantees. Maintaining this property in the face
3090 >     * of possible ongoing resizes requires a fair amount of
3091 >     * bookkeeping state that is difficult to optimize away amidst
3092 >     * volatile accesses.  Even so, traversal maintains reasonable
3093 >     * throughput.
3094       *
3095 <     * @return the hash code value for this map
3095 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3096 >     * However, if the table has been resized, then all future steps
3097 >     * must traverse both the bin at the current index as well as at
3098 >     * (index + baseSize); and so on for further resizings. To
3099 >     * paranoically cope with potential sharing by users of iterators
3100 >     * across threads, iteration terminates if a bounds checks fails
3101 >     * for a table read.
3102       */
3103 <    public int hashCode() {
3104 <        int h = 0;
3105 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3106 <        V v;
3107 <        while ((v = it.advance()) != null) {
3108 <            h += it.nextKey.hashCode() ^ v.hashCode();
3103 >    static class Traverser<K,V> {
3104 >        Node<K,V>[] tab;        // current table; updated if resized
3105 >        Node<K,V> next;         // the next entry to use
3106 >        int index;              // index of bin to use next
3107 >        int baseIndex;          // current index of initial table
3108 >        int baseLimit;          // index bound for initial table
3109 >        final int baseSize;     // initial table size
3110 >
3111 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3112 >            this.tab = tab;
3113 >            this.baseSize = size;
3114 >            this.baseIndex = this.index = index;
3115 >            this.baseLimit = limit;
3116 >            this.next = null;
3117          }
2999        return h;
3000    }
3118  
3119 <    /**
3120 <     * Returns a string representation of this map.  The string
3121 <     * representation consists of a list of key-value mappings (in no
3122 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3123 <     * mappings are separated by the characters {@code ", "} (comma
3124 <     * and space).  Each key-value mapping is rendered as the key
3125 <     * followed by an equals sign ("{@code =}") followed by the
3009 <     * associated value.
3010 <     *
3011 <     * @return a string representation of this map
3012 <     */
3013 <    public String toString() {
3014 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3015 <        StringBuilder sb = new StringBuilder();
3016 <        sb.append('{');
3017 <        V v;
3018 <        if ((v = it.advance()) != null) {
3119 >        /**
3120 >         * Advances if possible, returning next valid node, or null if none.
3121 >         */
3122 >        final Node<K,V> advance() {
3123 >            Node<K,V> e;
3124 >            if ((e = next) != null)
3125 >                e = e.next;
3126              for (;;) {
3127 <                Object k = it.nextKey;
3128 <                sb.append(k == this ? "(this Map)" : k);
3129 <                sb.append('=');
3130 <                sb.append(v == this ? "(this Map)" : v);
3131 <                if ((v = it.advance()) == null)
3132 <                    break;
3133 <                sb.append(',').append(' ');
3127 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
3128 >                if (e != null)
3129 >                    return next = e;
3130 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3131 >                    (n = t.length) <= (i = index) || i < 0)
3132 >                    return next = null;
3133 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
3134 >                    if (e instanceof ForwardingNode) {
3135 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3136 >                        e = null;
3137 >                        continue;
3138 >                    }
3139 >                    else if (e instanceof TreeBin)
3140 >                        e = ((TreeBin<K,V>)e).first;
3141 >                    else
3142 >                        e = null;
3143 >                }
3144 >                if ((index += baseSize) >= n)
3145 >                    index = ++baseIndex;    // visit upper slots if present
3146              }
3147          }
3029        return sb.append('}').toString();
3148      }
3149  
3150      /**
3151 <     * Compares the specified object with this map for equality.
3152 <     * Returns {@code true} if the given object is a map with the same
3035 <     * mappings as this map.  This operation may return misleading
3036 <     * results if either map is concurrently modified during execution
3037 <     * of this method.
3038 <     *
3039 <     * @param o object to be compared for equality with this map
3040 <     * @return {@code true} if the specified object is equal to this map
3151 >     * Base of key, value, and entry Iterators. Adds fields to
3152 >     * Traverser to support iterator.remove.
3153       */
3154 <    public boolean equals(Object o) {
3155 <        if (o != this) {
3156 <            if (!(o instanceof Map))
3157 <                return false;
3158 <            Map<?,?> m = (Map<?,?>) o;
3159 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3160 <            V val;
3161 <            while ((val = it.advance()) != null) {
3050 <                Object v = m.get(it.nextKey);
3051 <                if (v == null || (v != val && !v.equals(val)))
3052 <                    return false;
3053 <            }
3054 <            for (Map.Entry<?,?> e : m.entrySet()) {
3055 <                Object mk, mv, v;
3056 <                if ((mk = e.getKey()) == null ||
3057 <                    (mv = e.getValue()) == null ||
3058 <                    (v = internalGet(mk)) == null ||
3059 <                    (mv != v && !mv.equals(v)))
3060 <                    return false;
3061 <            }
3154 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3155 >        final ConcurrentHashMapV8<K,V> map;
3156 >        Node<K,V> lastReturned;
3157 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3158 >                    ConcurrentHashMapV8<K,V> map) {
3159 >            super(tab, size, index, limit);
3160 >            this.map = map;
3161 >            advance();
3162          }
3063        return true;
3064    }
3163  
3164 <    /* ----------------Iterators -------------- */
3164 >        public final boolean hasNext() { return next != null; }
3165 >        public final boolean hasMoreElements() { return next != null; }
3166  
3167 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3168 <        extends Traverser<K,V,Object>
3169 <        implements Spliterator<K>, Enumeration<K> {
3071 <        KeyIterator(ConcurrentHashMapV8<K,V> map) { super(map); }
3072 <        KeyIterator(ConcurrentHashMapV8<K,V> map, Traverser<K,V,Object> it) {
3073 <            super(map, it, -1);
3074 <        }
3075 <        public KeyIterator<K,V> split() {
3076 <            if (nextKey != null)
3167 >        public final void remove() {
3168 >            Node<K,V> p;
3169 >            if ((p = lastReturned) == null)
3170                  throw new IllegalStateException();
3171 <            return new KeyIterator<K,V>(map, this);
3171 >            lastReturned = null;
3172 >            map.replaceNode(p.key, null, null);
3173 >        }
3174 >    }
3175 >
3176 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3177 >        implements Iterator<K>, Enumeration<K> {
3178 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3179 >                    ConcurrentHashMapV8<K,V> map) {
3180 >            super(tab, index, size, limit, map);
3181          }
3182 <        @SuppressWarnings("unchecked") public final K next() {
3183 <            if (nextVal == null && advance() == null)
3182 >
3183 >        public final K next() {
3184 >            Node<K,V> p;
3185 >            if ((p = next) == null)
3186                  throw new NoSuchElementException();
3187 <            Object k = nextKey;
3188 <            nextVal = null;
3189 <            return (K) k;
3187 >            K k = p.key;
3188 >            lastReturned = p;
3189 >            advance();
3190 >            return k;
3191          }
3192  
3193          public final K nextElement() { return next(); }
3194      }
3195  
3196 <    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3197 <        extends Traverser<K,V,Object>
3198 <        implements Spliterator<V>, Enumeration<V> {
3199 <        ValueIterator(ConcurrentHashMapV8<K,V> map) { super(map); }
3200 <        ValueIterator(ConcurrentHashMapV8<K,V> map, Traverser<K,V,Object> it) {
3096 <            super(map, it, -1);
3097 <        }
3098 <        public ValueIterator<K,V> split() {
3099 <            if (nextKey != null)
3100 <                throw new IllegalStateException();
3101 <            return new ValueIterator<K,V>(map, this);
3196 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3197 >        implements Iterator<V>, Enumeration<V> {
3198 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3199 >                      ConcurrentHashMapV8<K,V> map) {
3200 >            super(tab, index, size, limit, map);
3201          }
3202  
3203          public final V next() {
3204 <            V v;
3205 <            if ((v = nextVal) == null && (v = advance()) == null)
3204 >            Node<K,V> p;
3205 >            if ((p = next) == null)
3206                  throw new NoSuchElementException();
3207 <            nextVal = null;
3207 >            V v = p.val;
3208 >            lastReturned = p;
3209 >            advance();
3210              return v;
3211          }
3212  
3213          public final V nextElement() { return next(); }
3214      }
3215  
3216 <    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3217 <        extends Traverser<K,V,Object>
3218 <        implements Spliterator<Map.Entry<K,V>> {
3219 <        EntryIterator(ConcurrentHashMapV8<K,V> map) { super(map); }
3220 <        EntryIterator(ConcurrentHashMapV8<K,V> map, Traverser<K,V,Object> it) {
3120 <            super(map, it, -1);
3121 <        }
3122 <        public EntryIterator<K,V> split() {
3123 <            if (nextKey != null)
3124 <                throw new IllegalStateException();
3125 <            return new EntryIterator<K,V>(map, this);
3216 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3217 >        implements Iterator<Map.Entry<K,V>> {
3218 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3219 >                      ConcurrentHashMapV8<K,V> map) {
3220 >            super(tab, index, size, limit, map);
3221          }
3222  
3223 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3224 <            V v;
3225 <            if ((v = nextVal) == null && (v = advance()) == null)
3223 >        public final Map.Entry<K,V> next() {
3224 >            Node<K,V> p;
3225 >            if ((p = next) == null)
3226                  throw new NoSuchElementException();
3227 <            Object k = nextKey;
3228 <            nextVal = null;
3229 <            return new MapEntry<K,V>((K)k, v, map);
3227 >            K k = p.key;
3228 >            V v = p.val;
3229 >            lastReturned = p;
3230 >            advance();
3231 >            return new MapEntry<K,V>(k, v, map);
3232          }
3233      }
3234  
3235      /**
3236 <     * Exported Entry for iterators
3236 >     * Exported Entry for EntryIterator
3237       */
3238      static final class MapEntry<K,V> implements Map.Entry<K,V> {
3239          final K key; // non-null
# Line 3147 | Line 3244 | public class ConcurrentHashMapV8<K,V>
3244              this.val = val;
3245              this.map = map;
3246          }
3247 <        public final K getKey()       { return key; }
3248 <        public final V getValue()     { return val; }
3249 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3250 <        public final String toString(){ return key + "=" + val; }
3247 >        public K getKey()        { return key; }
3248 >        public V getValue()      { return val; }
3249 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3250 >        public String toString() { return key + "=" + val; }
3251  
3252 <        public final boolean equals(Object o) {
3252 >        public boolean equals(Object o) {
3253              Object k, v; Map.Entry<?,?> e;
3254              return ((o instanceof Map.Entry) &&
3255                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3166 | Line 3263 | public class ConcurrentHashMapV8<K,V>
3263           * value to return is somewhat arbitrary here. Since we do not
3264           * necessarily track asynchronous changes, the most recent
3265           * "previous" value could be different from what we return (or
3266 <         * could even have been removed in which case the put will
3266 >         * could even have been removed, in which case the put will
3267           * re-establish). We do not and cannot guarantee more.
3268           */
3269 <        public final V setValue(V value) {
3269 >        public V setValue(V value) {
3270              if (value == null) throw new NullPointerException();
3271              V v = val;
3272              val = value;
# Line 3178 | Line 3275 | public class ConcurrentHashMapV8<K,V>
3275          }
3276      }
3277  
3278 <    /**
3279 <     * Returns exportable snapshot entry for the given key and value
3280 <     * when write-through can't or shouldn't be used.
3281 <     */
3282 <    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3283 <        return new AbstractMap.SimpleEntry<K,V>(k, v);
3284 <    }
3278 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3279 >        implements ConcurrentHashMapSpliterator<K> {
3280 >        long est;               // size estimate
3281 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3282 >                       long est) {
3283 >            super(tab, size, index, limit);
3284 >            this.est = est;
3285 >        }
3286 >
3287 >        public ConcurrentHashMapSpliterator<K> trySplit() {
3288 >            int i, f, h;
3289 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3290 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3291 >                                        f, est >>>= 1);
3292 >        }
3293  
3294 <    /* ---------------- Serialization Support -------------- */
3294 >        public void forEachRemaining(Action<? super K> action) {
3295 >            if (action == null) throw new NullPointerException();
3296 >            for (Node<K,V> p; (p = advance()) != null;)
3297 >                action.apply(p.key);
3298 >        }
3299 >
3300 >        public boolean tryAdvance(Action<? super K> action) {
3301 >            if (action == null) throw new NullPointerException();
3302 >            Node<K,V> p;
3303 >            if ((p = advance()) == null)
3304 >                return false;
3305 >            action.apply(p.key);
3306 >            return true;
3307 >        }
3308 >
3309 >        public long estimateSize() { return est; }
3310  
3191    /**
3192     * Stripped-down version of helper class used in previous version,
3193     * declared for the sake of serialization compatibility
3194     */
3195    static class Segment<K,V> implements Serializable {
3196        private static final long serialVersionUID = 2249069246763182397L;
3197        final float loadFactor;
3198        Segment(float lf) { this.loadFactor = lf; }
3311      }
3312  
3313 <    /**
3314 <     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
3315 <     * stream (i.e., serializes it).
3316 <     * @param s the stream
3317 <     * @serialData
3318 <     * the key (Object) and value (Object)
3319 <     * for each key-value mapping, followed by a null pair.
3208 <     * The key-value mappings are emitted in no particular order.
3209 <     */
3210 <    @SuppressWarnings("unchecked") private void writeObject
3211 <        (java.io.ObjectOutputStream s)
3212 <        throws java.io.IOException {
3213 <        if (segments == null) { // for serialization compatibility
3214 <            segments = (Segment<K,V>[])
3215 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3216 <            for (int i = 0; i < segments.length; ++i)
3217 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3313 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3314 >        implements ConcurrentHashMapSpliterator<V> {
3315 >        long est;               // size estimate
3316 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3317 >                         long est) {
3318 >            super(tab, size, index, limit);
3319 >            this.est = est;
3320          }
3321 <        s.defaultWriteObject();
3322 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3323 <        V v;
3324 <        while ((v = it.advance()) != null) {
3325 <            s.writeObject(it.nextKey);
3326 <            s.writeObject(v);
3321 >
3322 >        public ConcurrentHashMapSpliterator<V> trySplit() {
3323 >            int i, f, h;
3324 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3325 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3326 >                                          f, est >>>= 1);
3327          }
3328 <        s.writeObject(null);
3329 <        s.writeObject(null);
3330 <        segments = null; // throw away
3328 >
3329 >        public void forEachRemaining(Action<? super V> action) {
3330 >            if (action == null) throw new NullPointerException();
3331 >            for (Node<K,V> p; (p = advance()) != null;)
3332 >                action.apply(p.val);
3333 >        }
3334 >
3335 >        public boolean tryAdvance(Action<? super V> action) {
3336 >            if (action == null) throw new NullPointerException();
3337 >            Node<K,V> p;
3338 >            if ((p = advance()) == null)
3339 >                return false;
3340 >            action.apply(p.val);
3341 >            return true;
3342 >        }
3343 >
3344 >        public long estimateSize() { return est; }
3345 >
3346      }
3347  
3348 <    /**
3349 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3350 <     * @param s the stream
3351 <     */
3352 <    @SuppressWarnings("unchecked") private void readObject
3353 <        (java.io.ObjectInputStream s)
3354 <        throws java.io.IOException, ClassNotFoundException {
3355 <        s.defaultReadObject();
3356 <        this.segments = null; // unneeded
3348 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3349 >        implements ConcurrentHashMapSpliterator<Map.Entry<K,V>> {
3350 >        final ConcurrentHashMapV8<K,V> map; // To export MapEntry
3351 >        long est;               // size estimate
3352 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3353 >                         long est, ConcurrentHashMapV8<K,V> map) {
3354 >            super(tab, size, index, limit);
3355 >            this.map = map;
3356 >            this.est = est;
3357 >        }
3358  
3359 <        // Create all nodes, then place in table once size is known
3360 <        long size = 0L;
3361 <        Node<V> p = null;
3362 <        for (;;) {
3363 <            K k = (K) s.readObject();
3246 <            V v = (V) s.readObject();
3247 <            if (k != null && v != null) {
3248 <                int h = spread(k.hashCode());
3249 <                p = new Node<V>(h, k, v, p);
3250 <                ++size;
3251 <            }
3252 <            else
3253 <                break;
3359 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> trySplit() {
3360 >            int i, f, h;
3361 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3362 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3363 >                                          f, est >>>= 1, map);
3364          }
3365 <        if (p != null) {
3366 <            boolean init = false;
3367 <            int n;
3368 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3369 <                n = MAXIMUM_CAPACITY;
3260 <            else {
3261 <                int sz = (int)size;
3262 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3263 <            }
3264 <            int sc = sizeCtl;
3265 <            boolean collide = false;
3266 <            if (n > sc &&
3267 <                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3268 <                try {
3269 <                    if (table == null) {
3270 <                        init = true;
3271 <                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3272 <                        Node<V>[] tab = (Node<V>[])rt;
3273 <                        int mask = n - 1;
3274 <                        while (p != null) {
3275 <                            int j = p.hash & mask;
3276 <                            Node<V> next = p.next;
3277 <                            Node<V> q = p.next = tabAt(tab, j);
3278 <                            setTabAt(tab, j, p);
3279 <                            if (!collide && q != null && q.hash == p.hash)
3280 <                                collide = true;
3281 <                            p = next;
3282 <                        }
3283 <                        table = tab;
3284 <                        addCount(size, -1);
3285 <                        sc = n - (n >>> 2);
3286 <                    }
3287 <                } finally {
3288 <                    sizeCtl = sc;
3289 <                }
3290 <                if (collide) { // rescan and convert to TreeBins
3291 <                    Node<V>[] tab = table;
3292 <                    for (int i = 0; i < tab.length; ++i) {
3293 <                        int c = 0;
3294 <                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3295 <                            if (++c > TREE_THRESHOLD &&
3296 <                                (e.key instanceof Comparable)) {
3297 <                                replaceWithTreeBin(tab, i, e.key);
3298 <                                break;
3299 <                            }
3300 <                        }
3301 <                    }
3302 <                }
3303 <            }
3304 <            if (!init) { // Can only happen if unsafely published.
3305 <                while (p != null) {
3306 <                    internalPut((K)p.key, p.val, false);
3307 <                    p = p.next;
3308 <                }
3309 <            }
3365 >
3366 >        public void forEachRemaining(Action<? super Map.Entry<K,V>> action) {
3367 >            if (action == null) throw new NullPointerException();
3368 >            for (Node<K,V> p; (p = advance()) != null; )
3369 >                action.apply(new MapEntry<K,V>(p.key, p.val, map));
3370          }
3311    }
3371  
3372 <    // -------------------------------------------------------
3372 >        public boolean tryAdvance(Action<? super Map.Entry<K,V>> action) {
3373 >            if (action == null) throw new NullPointerException();
3374 >            Node<K,V> p;
3375 >            if ((p = advance()) == null)
3376 >                return false;
3377 >            action.apply(new MapEntry<K,V>(p.key, p.val, map));
3378 >            return true;
3379 >        }
3380  
3381 <    // Sams
3316 <    /** Interface describing a void action of one argument */
3317 <    public interface Action<A> { void apply(A a); }
3318 <    /** Interface describing a void action of two arguments */
3319 <    public interface BiAction<A,B> { void apply(A a, B b); }
3320 <    /** Interface describing a function of one argument */
3321 <    public interface Fun<A,T> { T apply(A a); }
3322 <    /** Interface describing a function of two arguments */
3323 <    public interface BiFun<A,B,T> { T apply(A a, B b); }
3324 <    /** Interface describing a function of no arguments */
3325 <    public interface Generator<T> { T apply(); }
3326 <    /** Interface describing a function mapping its argument to a double */
3327 <    public interface ObjectToDouble<A> { double apply(A a); }
3328 <    /** Interface describing a function mapping its argument to a long */
3329 <    public interface ObjectToLong<A> { long apply(A a); }
3330 <    /** Interface describing a function mapping its argument to an int */
3331 <    public interface ObjectToInt<A> {int apply(A a); }
3332 <    /** Interface describing a function mapping two arguments to a double */
3333 <    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
3334 <    /** Interface describing a function mapping two arguments to a long */
3335 <    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
3336 <    /** Interface describing a function mapping two arguments to an int */
3337 <    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
3338 <    /** Interface describing a function mapping a double to a double */
3339 <    public interface DoubleToDouble { double apply(double a); }
3340 <    /** Interface describing a function mapping a long to a long */
3341 <    public interface LongToLong { long apply(long a); }
3342 <    /** Interface describing a function mapping an int to an int */
3343 <    public interface IntToInt { int apply(int a); }
3344 <    /** Interface describing a function mapping two doubles to a double */
3345 <    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3346 <    /** Interface describing a function mapping two longs to a long */
3347 <    public interface LongByLongToLong { long apply(long a, long b); }
3348 <    /** Interface describing a function mapping two ints to an int */
3349 <    public interface IntByIntToInt { int apply(int a, int b); }
3381 >        public long estimateSize() { return est; }
3382  
3383 +    }
3384  
3385 <    // -------------------------------------------------------
3385 >    // Parallel bulk operations
3386  
3387 <    // Sequential bulk operations
3387 >    /**
3388 >     * Computes initial batch value for bulk tasks. The returned value
3389 >     * is approximately exp2 of the number of times (minus one) to
3390 >     * split task by two before executing leaf action. This value is
3391 >     * faster to compute and more convenient to use as a guide to
3392 >     * splitting than is the depth, since it is used while dividing by
3393 >     * two anyway.
3394 >     */
3395 >    final int batchFor(long b) {
3396 >        long n;
3397 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3398 >            return 0;
3399 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3400 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3401 >    }
3402  
3403      /**
3404       * Performs the given action for each (key, value).
3405       *
3406 +     * @param parallelismThreshold the (estimated) number of elements
3407 +     * needed for this operation to be executed in parallel
3408       * @param action the action
3409 +     * @since 1.8
3410       */
3411 <    @SuppressWarnings("unchecked") public void forEachSequentially
3412 <        (BiAction<K,V> action) {
3411 >    public void forEach(long parallelismThreshold,
3412 >                        BiAction<? super K,? super V> action) {
3413          if (action == null) throw new NullPointerException();
3414 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3415 <        V v;
3416 <        while ((v = it.advance()) != null)
3367 <            action.apply((K)it.nextKey, v);
3414 >        new ForEachMappingTask<K,V>
3415 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3416 >             action).invoke();
3417      }
3418  
3419      /**
3420       * Performs the given action for each non-null transformation
3421       * of each (key, value).
3422       *
3423 +     * @param parallelismThreshold the (estimated) number of elements
3424 +     * needed for this operation to be executed in parallel
3425       * @param transformer a function returning the transformation
3426       * for an element, or null if there is no transformation (in
3427       * which case the action is not applied)
3428       * @param action the action
3429 +     * @since 1.8
3430       */
3431 <    @SuppressWarnings("unchecked") public <U> void forEachSequentially
3432 <        (BiFun<? super K, ? super V, ? extends U> transformer,
3433 <         Action<U> action) {
3431 >    public <U> void forEach(long parallelismThreshold,
3432 >                            BiFun<? super K, ? super V, ? extends U> transformer,
3433 >                            Action<? super U> action) {
3434          if (transformer == null || action == null)
3435              throw new NullPointerException();
3436 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3437 <        V v; U u;
3438 <        while ((v = it.advance()) != null) {
3387 <            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3388 <                action.apply(u);
3389 <        }
3436 >        new ForEachTransformedMappingTask<K,V,U>
3437 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3438 >             transformer, action).invoke();
3439      }
3440  
3441      /**
3442       * Returns a non-null result from applying the given search
3443 <     * function on each (key, value), or null if none.
3443 >     * function on each (key, value), or null if none.  Upon
3444 >     * success, further element processing is suppressed and the
3445 >     * results of any other parallel invocations of the search
3446 >     * function are ignored.
3447       *
3448 +     * @param parallelismThreshold the (estimated) number of elements
3449 +     * needed for this operation to be executed in parallel
3450       * @param searchFunction a function returning a non-null
3451       * result on success, else null
3452       * @return a non-null result from applying the given search
3453       * function on each (key, value), or null if none
3454 +     * @since 1.8
3455       */
3456 <    @SuppressWarnings("unchecked") public <U> U searchSequentially
3457 <        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
3456 >    public <U> U search(long parallelismThreshold,
3457 >                        BiFun<? super K, ? super V, ? extends U> searchFunction) {
3458          if (searchFunction == null) throw new NullPointerException();
3459 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3460 <        V v; U u;
3461 <        while ((v = it.advance()) != null) {
3407 <            if ((u = searchFunction.apply((K)it.nextKey, v)) != null)
3408 <                return u;
3409 <        }
3410 <        return null;
3459 >        return new SearchMappingsTask<K,V,U>
3460 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3461 >             searchFunction, new AtomicReference<U>()).invoke();
3462      }
3463  
3464      /**
# Line 3415 | Line 3466 | public class ConcurrentHashMapV8<K,V>
3466       * of all (key, value) pairs using the given reducer to
3467       * combine values, or null if none.
3468       *
3469 +     * @param parallelismThreshold the (estimated) number of elements
3470 +     * needed for this operation to be executed in parallel
3471       * @param transformer a function returning the transformation
3472       * for an element, or null if there is no transformation (in
3473       * which case it is not combined)
3474       * @param reducer a commutative associative combining function
3475       * @return the result of accumulating the given transformation
3476       * of all (key, value) pairs
3477 +     * @since 1.8
3478       */
3479 <    @SuppressWarnings("unchecked") public <U> U reduceSequentially
3480 <        (BiFun<? super K, ? super V, ? extends U> transformer,
3481 <         BiFun<? super U, ? super U, ? extends U> reducer) {
3479 >    public <U> U reduce(long parallelismThreshold,
3480 >                        BiFun<? super K, ? super V, ? extends U> transformer,
3481 >                        BiFun<? super U, ? super U, ? extends U> reducer) {
3482          if (transformer == null || reducer == null)
3483              throw new NullPointerException();
3484 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3485 <        U r = null, u; V v;
3486 <        while ((v = it.advance()) != null) {
3433 <            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3434 <                r = (r == null) ? u : reducer.apply(r, u);
3435 <        }
3436 <        return r;
3484 >        return new MapReduceMappingsTask<K,V,U>
3485 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3486 >             null, transformer, reducer).invoke();
3487      }
3488  
3489      /**
# Line 3441 | Line 3491 | public class ConcurrentHashMapV8<K,V>
3491       * of all (key, value) pairs using the given reducer to
3492       * combine values, and the given basis as an identity value.
3493       *
3494 +     * @param parallelismThreshold the (estimated) number of elements
3495 +     * needed for this operation to be executed in parallel
3496       * @param transformer a function returning the transformation
3497       * for an element
3498       * @param basis the identity (initial default value) for the reduction
3499       * @param reducer a commutative associative combining function
3500       * @return the result of accumulating the given transformation
3501       * of all (key, value) pairs
3502 +     * @since 1.8
3503       */
3504 <    @SuppressWarnings("unchecked") public double reduceToDoubleSequentially
3505 <        (ObjectByObjectToDouble<? super K, ? super V> transformer,
3506 <         double basis,
3507 <         DoubleByDoubleToDouble reducer) {
3504 >    public double reduceToDouble(long parallelismThreshold,
3505 >                                 ObjectByObjectToDouble<? super K, ? super V> transformer,
3506 >                                 double basis,
3507 >                                 DoubleByDoubleToDouble reducer) {
3508          if (transformer == null || reducer == null)
3509              throw new NullPointerException();
3510 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3511 <        double r = basis; V v;
3512 <        while ((v = it.advance()) != null)
3460 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3461 <        return r;
3510 >        return new MapReduceMappingsToDoubleTask<K,V>
3511 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3512 >             null, transformer, basis, reducer).invoke();
3513      }
3514  
3515      /**
# Line 3466 | Line 3517 | public class ConcurrentHashMapV8<K,V>
3517       * of all (key, value) pairs using the given reducer to
3518       * combine values, and the given basis as an identity value.
3519       *
3520 +     * @param parallelismThreshold the (estimated) number of elements
3521 +     * needed for this operation to be executed in parallel
3522       * @param transformer a function returning the transformation
3523       * for an element
3524       * @param basis the identity (initial default value) for the reduction
3525       * @param reducer a commutative associative combining function
3526       * @return the result of accumulating the given transformation
3527       * of all (key, value) pairs
3528 +     * @since 1.8
3529       */
3530 <    @SuppressWarnings("unchecked") public long reduceToLongSequentially
3531 <        (ObjectByObjectToLong<? super K, ? super V> transformer,
3532 <         long basis,
3533 <         LongByLongToLong reducer) {
3530 >    public long reduceToLong(long parallelismThreshold,
3531 >                             ObjectByObjectToLong<? super K, ? super V> transformer,
3532 >                             long basis,
3533 >                             LongByLongToLong reducer) {
3534          if (transformer == null || reducer == null)
3535              throw new NullPointerException();
3536 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3537 <        long r = basis; V v;
3538 <        while ((v = it.advance()) != null)
3485 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3486 <        return r;
3536 >        return new MapReduceMappingsToLongTask<K,V>
3537 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3538 >             null, transformer, basis, reducer).invoke();
3539      }
3540  
3541      /**
# Line 3491 | Line 3543 | public class ConcurrentHashMapV8<K,V>
3543       * of all (key, value) pairs using the given reducer to
3544       * combine values, and the given basis as an identity value.
3545       *
3546 +     * @param parallelismThreshold the (estimated) number of elements
3547 +     * needed for this operation to be executed in parallel
3548       * @param transformer a function returning the transformation
3549       * for an element
3550       * @param basis the identity (initial default value) for the reduction
3551       * @param reducer a commutative associative combining function
3552       * @return the result of accumulating the given transformation
3553       * of all (key, value) pairs
3554 +     * @since 1.8
3555       */
3556 <    @SuppressWarnings("unchecked") public int reduceToIntSequentially
3557 <        (ObjectByObjectToInt<? super K, ? super V> transformer,
3558 <         int basis,
3559 <         IntByIntToInt reducer) {
3556 >    public int reduceToInt(long parallelismThreshold,
3557 >                           ObjectByObjectToInt<? super K, ? super V> transformer,
3558 >                           int basis,
3559 >                           IntByIntToInt reducer) {
3560          if (transformer == null || reducer == null)
3561              throw new NullPointerException();
3562 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3563 <        int r = basis; V v;
3564 <        while ((v = it.advance()) != null)
3510 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3511 <        return r;
3562 >        return new MapReduceMappingsToIntTask<K,V>
3563 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3564 >             null, transformer, basis, reducer).invoke();
3565      }
3566  
3567      /**
3568       * Performs the given action for each key.
3569       *
3570 +     * @param parallelismThreshold the (estimated) number of elements
3571 +     * needed for this operation to be executed in parallel
3572       * @param action the action
3573 +     * @since 1.8
3574       */
3575 <    @SuppressWarnings("unchecked") public void forEachKeySequentially
3576 <        (Action<K> action) {
3575 >    public void forEachKey(long parallelismThreshold,
3576 >                           Action<? super K> action) {
3577          if (action == null) throw new NullPointerException();
3578 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3579 <        while (it.advance() != null)
3580 <            action.apply((K)it.nextKey);
3578 >        new ForEachKeyTask<K,V>
3579 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3580 >             action).invoke();
3581      }
3582  
3583      /**
3584       * Performs the given action for each non-null transformation
3585       * of each key.
3586       *
3587 +     * @param parallelismThreshold the (estimated) number of elements
3588 +     * needed for this operation to be executed in parallel
3589       * @param transformer a function returning the transformation
3590       * for an element, or null if there is no transformation (in
3591       * which case the action is not applied)
3592       * @param action the action
3593 +     * @since 1.8
3594       */
3595 <    @SuppressWarnings("unchecked") public <U> void forEachKeySequentially
3596 <        (Fun<? super K, ? extends U> transformer,
3597 <         Action<U> action) {
3595 >    public <U> void forEachKey(long parallelismThreshold,
3596 >                               Fun<? super K, ? extends U> transformer,
3597 >                               Action<? super U> action) {
3598          if (transformer == null || action == null)
3599              throw new NullPointerException();
3600 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3601 <        U u;
3602 <        while (it.advance() != null) {
3544 <            if ((u = transformer.apply((K)it.nextKey)) != null)
3545 <                action.apply(u);
3546 <        }
3547 <        ForkJoinTasks.forEachKey
3548 <            (this, transformer, action).invoke();
3600 >        new ForEachTransformedKeyTask<K,V,U>
3601 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3602 >             transformer, action).invoke();
3603      }
3604  
3605      /**
3606       * Returns a non-null result from applying the given search
3607 <     * function on each key, or null if none.
3607 >     * function on each key, or null if none. Upon success,
3608 >     * further element processing is suppressed and the results of
3609 >     * any other parallel invocations of the search function are
3610 >     * ignored.
3611       *
3612 +     * @param parallelismThreshold the (estimated) number of elements
3613 +     * needed for this operation to be executed in parallel
3614       * @param searchFunction a function returning a non-null
3615       * result on success, else null
3616       * @return a non-null result from applying the given search
3617       * function on each key, or null if none
3618 +     * @since 1.8
3619       */
3620 <    @SuppressWarnings("unchecked") public <U> U searchKeysSequentially
3621 <        (Fun<? super K, ? extends U> searchFunction) {
3622 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3623 <        U u;
3624 <        while (it.advance() != null) {
3625 <            if ((u = searchFunction.apply((K)it.nextKey)) != null)
3566 <                return u;
3567 <        }
3568 <        return null;
3620 >    public <U> U searchKeys(long parallelismThreshold,
3621 >                            Fun<? super K, ? extends U> searchFunction) {
3622 >        if (searchFunction == null) throw new NullPointerException();
3623 >        return new SearchKeysTask<K,V,U>
3624 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3625 >             searchFunction, new AtomicReference<U>()).invoke();
3626      }
3627  
3628      /**
3629       * Returns the result of accumulating all keys using the given
3630       * reducer to combine values, or null if none.
3631       *
3632 +     * @param parallelismThreshold the (estimated) number of elements
3633 +     * needed for this operation to be executed in parallel
3634       * @param reducer a commutative associative combining function
3635       * @return the result of accumulating all keys using the given
3636       * reducer to combine values, or null if none
3637 +     * @since 1.8
3638       */
3639 <    @SuppressWarnings("unchecked") public K reduceKeysSequentially
3640 <        (BiFun<? super K, ? super K, ? extends K> reducer) {
3639 >    public K reduceKeys(long parallelismThreshold,
3640 >                        BiFun<? super K, ? super K, ? extends K> reducer) {
3641          if (reducer == null) throw new NullPointerException();
3642 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3643 <        K r = null;
3644 <        while (it.advance() != null) {
3585 <            K u = (K)it.nextKey;
3586 <            r = (r == null) ? u : reducer.apply(r, u);
3587 <        }
3588 <        return r;
3642 >        return new ReduceKeysTask<K,V>
3643 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3644 >             null, reducer).invoke();
3645      }
3646  
3647      /**
# Line 3593 | Line 3649 | public class ConcurrentHashMapV8<K,V>
3649       * of all keys using the given reducer to combine values, or
3650       * null if none.
3651       *
3652 +     * @param parallelismThreshold the (estimated) number of elements
3653 +     * needed for this operation to be executed in parallel
3654       * @param transformer a function returning the transformation
3655       * for an element, or null if there is no transformation (in
3656       * which case it is not combined)
3657       * @param reducer a commutative associative combining function
3658       * @return the result of accumulating the given transformation
3659       * of all keys
3660 +     * @since 1.8
3661       */
3662 <    @SuppressWarnings("unchecked") public <U> U reduceKeysSequentially
3663 <        (Fun<? super K, ? extends U> transformer,
3662 >    public <U> U reduceKeys(long parallelismThreshold,
3663 >                            Fun<? super K, ? extends U> transformer,
3664           BiFun<? super U, ? super U, ? extends U> reducer) {
3665          if (transformer == null || reducer == null)
3666              throw new NullPointerException();
3667 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3668 <        U r = null, u;
3669 <        while (it.advance() != null) {
3611 <            if ((u = transformer.apply((K)it.nextKey)) != null)
3612 <                r = (r == null) ? u : reducer.apply(r, u);
3613 <        }
3614 <        return r;
3667 >        return new MapReduceKeysTask<K,V,U>
3668 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3669 >             null, transformer, reducer).invoke();
3670      }
3671  
3672      /**
# Line 3619 | Line 3674 | public class ConcurrentHashMapV8<K,V>
3674       * of all keys using the given reducer to combine values, and
3675       * the given basis as an identity value.
3676       *
3677 +     * @param parallelismThreshold the (estimated) number of elements
3678 +     * needed for this operation to be executed in parallel
3679       * @param transformer a function returning the transformation
3680       * for an element
3681       * @param basis the identity (initial default value) for the reduction
3682       * @param reducer a commutative associative combining function
3683 <     * @return  the result of accumulating the given transformation
3683 >     * @return the result of accumulating the given transformation
3684       * of all keys
3685 +     * @since 1.8
3686       */
3687 <    @SuppressWarnings("unchecked") public double reduceKeysToDoubleSequentially
3688 <        (ObjectToDouble<? super K> transformer,
3689 <         double basis,
3690 <         DoubleByDoubleToDouble reducer) {
3687 >    public double reduceKeysToDouble(long parallelismThreshold,
3688 >                                     ObjectToDouble<? super K> transformer,
3689 >                                     double basis,
3690 >                                     DoubleByDoubleToDouble reducer) {
3691          if (transformer == null || reducer == null)
3692              throw new NullPointerException();
3693 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3694 <        double r = basis;
3695 <        while (it.advance() != null)
3638 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3639 <        return r;
3693 >        return new MapReduceKeysToDoubleTask<K,V>
3694 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3695 >             null, transformer, basis, reducer).invoke();
3696      }
3697  
3698      /**
# Line 3644 | Line 3700 | public class ConcurrentHashMapV8<K,V>
3700       * of all keys using the given reducer to combine values, and
3701       * the given basis as an identity value.
3702       *
3703 +     * @param parallelismThreshold the (estimated) number of elements
3704 +     * needed for this operation to be executed in parallel
3705       * @param transformer a function returning the transformation
3706       * for an element
3707       * @param basis the identity (initial default value) for the reduction
3708       * @param reducer a commutative associative combining function
3709       * @return the result of accumulating the given transformation
3710       * of all keys
3711 +     * @since 1.8
3712       */
3713 <    @SuppressWarnings("unchecked") public long reduceKeysToLongSequentially
3714 <        (ObjectToLong<? super K> transformer,
3715 <         long basis,
3716 <         LongByLongToLong reducer) {
3713 >    public long reduceKeysToLong(long parallelismThreshold,
3714 >                                 ObjectToLong<? super K> transformer,
3715 >                                 long basis,
3716 >                                 LongByLongToLong reducer) {
3717          if (transformer == null || reducer == null)
3718              throw new NullPointerException();
3719 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3720 <        long r = basis;
3721 <        while (it.advance() != null)
3663 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3664 <        return r;
3719 >        return new MapReduceKeysToLongTask<K,V>
3720 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3721 >             null, transformer, basis, reducer).invoke();
3722      }
3723  
3724      /**
# Line 3669 | Line 3726 | public class ConcurrentHashMapV8<K,V>
3726       * of all keys using the given reducer to combine values, and
3727       * the given basis as an identity value.
3728       *
3729 +     * @param parallelismThreshold the (estimated) number of elements
3730 +     * needed for this operation to be executed in parallel
3731       * @param transformer a function returning the transformation
3732       * for an element
3733       * @param basis the identity (initial default value) for the reduction
3734       * @param reducer a commutative associative combining function
3735       * @return the result of accumulating the given transformation
3736       * of all keys
3737 +     * @since 1.8
3738       */
3739 <    @SuppressWarnings("unchecked") public int reduceKeysToIntSequentially
3740 <        (ObjectToInt<? super K> transformer,
3741 <         int basis,
3742 <         IntByIntToInt reducer) {
3739 >    public int reduceKeysToInt(long parallelismThreshold,
3740 >                               ObjectToInt<? super K> transformer,
3741 >                               int basis,
3742 >                               IntByIntToInt reducer) {
3743          if (transformer == null || reducer == null)
3744              throw new NullPointerException();
3745 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3746 <        int r = basis;
3747 <        while (it.advance() != null)
3688 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3689 <        return r;
3745 >        return new MapReduceKeysToIntTask<K,V>
3746 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3747 >             null, transformer, basis, reducer).invoke();
3748      }
3749  
3750      /**
3751       * Performs the given action for each value.
3752       *
3753 +     * @param parallelismThreshold the (estimated) number of elements
3754 +     * needed for this operation to be executed in parallel
3755       * @param action the action
3756 +     * @since 1.8
3757       */
3758 <    public void forEachValueSequentially(Action<V> action) {
3759 <        if (action == null) throw new NullPointerException();
3760 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3761 <        V v;
3762 <        while ((v = it.advance()) != null)
3763 <            action.apply(v);
3758 >    public void forEachValue(long parallelismThreshold,
3759 >                             Action<? super V> action) {
3760 >        if (action == null)
3761 >            throw new NullPointerException();
3762 >        new ForEachValueTask<K,V>
3763 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3764 >             action).invoke();
3765      }
3766  
3767      /**
3768       * Performs the given action for each non-null transformation
3769       * of each value.
3770       *
3771 +     * @param parallelismThreshold the (estimated) number of elements
3772 +     * needed for this operation to be executed in parallel
3773       * @param transformer a function returning the transformation
3774       * for an element, or null if there is no transformation (in
3775       * which case the action is not applied)
3776 +     * @param action the action
3777 +     * @since 1.8
3778       */
3779 <    public <U> void forEachValueSequentially
3780 <        (Fun<? super V, ? extends U> transformer,
3781 <         Action<U> action) {
3779 >    public <U> void forEachValue(long parallelismThreshold,
3780 >                                 Fun<? super V, ? extends U> transformer,
3781 >                                 Action<? super U> action) {
3782          if (transformer == null || action == null)
3783              throw new NullPointerException();
3784 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3785 <        V v; U u;
3786 <        while ((v = it.advance()) != null) {
3721 <            if ((u = transformer.apply(v)) != null)
3722 <                action.apply(u);
3723 <        }
3784 >        new ForEachTransformedValueTask<K,V,U>
3785 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3786 >             transformer, action).invoke();
3787      }
3788  
3789      /**
3790       * Returns a non-null result from applying the given search
3791 <     * function on each value, or null if none.
3791 >     * function on each value, or null if none.  Upon success,
3792 >     * further element processing is suppressed and the results of
3793 >     * any other parallel invocations of the search function are
3794 >     * ignored.
3795       *
3796 +     * @param parallelismThreshold the (estimated) number of elements
3797 +     * needed for this operation to be executed in parallel
3798       * @param searchFunction a function returning a non-null
3799       * result on success, else null
3800       * @return a non-null result from applying the given search
3801       * function on each value, or null if none
3802 +     * @since 1.8
3803       */
3804 <    public <U> U searchValuesSequentially
3805 <        (Fun<? super V, ? extends U> searchFunction) {
3804 >    public <U> U searchValues(long parallelismThreshold,
3805 >                              Fun<? super V, ? extends U> searchFunction) {
3806          if (searchFunction == null) throw new NullPointerException();
3807 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3808 <        V v; U u;
3809 <        while ((v = it.advance()) != null) {
3741 <            if ((u = searchFunction.apply(v)) != null)
3742 <                return u;
3743 <        }
3744 <        return null;
3807 >        return new SearchValuesTask<K,V,U>
3808 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3809 >             searchFunction, new AtomicReference<U>()).invoke();
3810      }
3811  
3812      /**
3813       * Returns the result of accumulating all values using the
3814       * given reducer to combine values, or null if none.
3815       *
3816 +     * @param parallelismThreshold the (estimated) number of elements
3817 +     * needed for this operation to be executed in parallel
3818       * @param reducer a commutative associative combining function
3819 <     * @return  the result of accumulating all values
3819 >     * @return the result of accumulating all values
3820 >     * @since 1.8
3821       */
3822 <    public V reduceValuesSequentially
3823 <        (BiFun<? super V, ? super V, ? extends V> reducer) {
3822 >    public V reduceValues(long parallelismThreshold,
3823 >                          BiFun<? super V, ? super V, ? extends V> reducer) {
3824          if (reducer == null) throw new NullPointerException();
3825 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3826 <        V r = null; V v;
3827 <        while ((v = it.advance()) != null)
3760 <            r = (r == null) ? v : reducer.apply(r, v);
3761 <        return r;
3825 >        return new ReduceValuesTask<K,V>
3826 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3827 >             null, reducer).invoke();
3828      }
3829  
3830      /**
# Line 3766 | Line 3832 | public class ConcurrentHashMapV8<K,V>
3832       * of all values using the given reducer to combine values, or
3833       * null if none.
3834       *
3835 +     * @param parallelismThreshold the (estimated) number of elements
3836 +     * needed for this operation to be executed in parallel
3837       * @param transformer a function returning the transformation
3838       * for an element, or null if there is no transformation (in
3839       * which case it is not combined)
3840       * @param reducer a commutative associative combining function
3841       * @return the result of accumulating the given transformation
3842       * of all values
3843 +     * @since 1.8
3844       */
3845 <    public <U> U reduceValuesSequentially
3846 <        (Fun<? super V, ? extends U> transformer,
3847 <         BiFun<? super U, ? super U, ? extends U> reducer) {
3845 >    public <U> U reduceValues(long parallelismThreshold,
3846 >                              Fun<? super V, ? extends U> transformer,
3847 >                              BiFun<? super U, ? super U, ? extends U> reducer) {
3848          if (transformer == null || reducer == null)
3849              throw new NullPointerException();
3850 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3851 <        U r = null, u; V v;
3852 <        while ((v = it.advance()) != null) {
3784 <            if ((u = transformer.apply(v)) != null)
3785 <                r = (r == null) ? u : reducer.apply(r, u);
3786 <        }
3787 <        return r;
3850 >        return new MapReduceValuesTask<K,V,U>
3851 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3852 >             null, transformer, reducer).invoke();
3853      }
3854  
3855      /**
# Line 3792 | Line 3857 | public class ConcurrentHashMapV8<K,V>
3857       * of all values using the given reducer to combine values,
3858       * and the given basis as an identity value.
3859       *
3860 +     * @param parallelismThreshold the (estimated) number of elements
3861 +     * needed for this operation to be executed in parallel
3862       * @param transformer a function returning the transformation
3863       * for an element
3864       * @param basis the identity (initial default value) for the reduction
3865       * @param reducer a commutative associative combining function
3866       * @return the result of accumulating the given transformation
3867       * of all values
3868 +     * @since 1.8
3869       */
3870 <    public double reduceValuesToDoubleSequentially
3871 <        (ObjectToDouble<? super V> transformer,
3872 <         double basis,
3873 <         DoubleByDoubleToDouble reducer) {
3870 >    public double reduceValuesToDouble(long parallelismThreshold,
3871 >                                       ObjectToDouble<? super V> transformer,
3872 >                                       double basis,
3873 >                                       DoubleByDoubleToDouble reducer) {
3874          if (transformer == null || reducer == null)
3875              throw new NullPointerException();
3876 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3877 <        double r = basis; V v;
3878 <        while ((v = it.advance()) != null)
3811 <            r = reducer.apply(r, transformer.apply(v));
3812 <        return r;
3876 >        return new MapReduceValuesToDoubleTask<K,V>
3877 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3878 >             null, transformer, basis, reducer).invoke();
3879      }
3880  
3881      /**
# Line 3817 | Line 3883 | public class ConcurrentHashMapV8<K,V>
3883       * of all values using the given reducer to combine values,
3884       * and the given basis as an identity value.
3885       *
3886 +     * @param parallelismThreshold the (estimated) number of elements
3887 +     * needed for this operation to be executed in parallel
3888       * @param transformer a function returning the transformation
3889       * for an element
3890       * @param basis the identity (initial default value) for the reduction
3891       * @param reducer a commutative associative combining function
3892       * @return the result of accumulating the given transformation
3893       * of all values
3894 +     * @since 1.8
3895       */
3896 <    public long reduceValuesToLongSequentially
3897 <        (ObjectToLong<? super V> transformer,
3898 <         long basis,
3899 <         LongByLongToLong reducer) {
3896 >    public long reduceValuesToLong(long parallelismThreshold,
3897 >                                   ObjectToLong<? super V> transformer,
3898 >                                   long basis,
3899 >                                   LongByLongToLong reducer) {
3900          if (transformer == null || reducer == null)
3901              throw new NullPointerException();
3902 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3903 <        long r = basis; V v;
3904 <        while ((v = it.advance()) != null)
3836 <            r = reducer.apply(r, transformer.apply(v));
3837 <        return r;
3902 >        return new MapReduceValuesToLongTask<K,V>
3903 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3904 >             null, transformer, basis, reducer).invoke();
3905      }
3906  
3907      /**
# Line 3842 | Line 3909 | public class ConcurrentHashMapV8<K,V>
3909       * of all values using the given reducer to combine values,
3910       * and the given basis as an identity value.
3911       *
3912 +     * @param parallelismThreshold the (estimated) number of elements
3913 +     * needed for this operation to be executed in parallel
3914       * @param transformer a function returning the transformation
3915       * for an element
3916       * @param basis the identity (initial default value) for the reduction
3917       * @param reducer a commutative associative combining function
3918       * @return the result of accumulating the given transformation
3919       * of all values
3920 +     * @since 1.8
3921       */
3922 <    public int reduceValuesToIntSequentially
3923 <        (ObjectToInt<? super V> transformer,
3924 <         int basis,
3925 <         IntByIntToInt reducer) {
3922 >    public int reduceValuesToInt(long parallelismThreshold,
3923 >                                 ObjectToInt<? super V> transformer,
3924 >                                 int basis,
3925 >                                 IntByIntToInt reducer) {
3926          if (transformer == null || reducer == null)
3927              throw new NullPointerException();
3928 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3929 <        int r = basis; V v;
3930 <        while ((v = it.advance()) != null)
3861 <            r = reducer.apply(r, transformer.apply(v));
3862 <        return r;
3928 >        return new MapReduceValuesToIntTask<K,V>
3929 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3930 >             null, transformer, basis, reducer).invoke();
3931      }
3932  
3933      /**
3934       * Performs the given action for each entry.
3935       *
3936 +     * @param parallelismThreshold the (estimated) number of elements
3937 +     * needed for this operation to be executed in parallel
3938       * @param action the action
3939 +     * @since 1.8
3940       */
3941 <    @SuppressWarnings("unchecked") public void forEachEntrySequentially
3942 <        (Action<Map.Entry<K,V>> action) {
3941 >    public void forEachEntry(long parallelismThreshold,
3942 >                             Action<? super Map.Entry<K,V>> action) {
3943          if (action == null) throw new NullPointerException();
3944 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3945 <        V v;
3875 <        while ((v = it.advance()) != null)
3876 <            action.apply(entryFor((K)it.nextKey, v));
3944 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
3945 >                                  action).invoke();
3946      }
3947  
3948      /**
3949       * Performs the given action for each non-null transformation
3950       * of each entry.
3951       *
3952 +     * @param parallelismThreshold the (estimated) number of elements
3953 +     * needed for this operation to be executed in parallel
3954       * @param transformer a function returning the transformation
3955       * for an element, or null if there is no transformation (in
3956       * which case the action is not applied)
3957       * @param action the action
3958 +     * @since 1.8
3959       */
3960 <    @SuppressWarnings("unchecked") public <U> void forEachEntrySequentially
3961 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
3962 <         Action<U> action) {
3960 >    public <U> void forEachEntry(long parallelismThreshold,
3961 >                                 Fun<Map.Entry<K,V>, ? extends U> transformer,
3962 >                                 Action<? super U> action) {
3963          if (transformer == null || action == null)
3964              throw new NullPointerException();
3965 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3966 <        V v; U u;
3967 <        while ((v = it.advance()) != null) {
3896 <            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3897 <                action.apply(u);
3898 <        }
3965 >        new ForEachTransformedEntryTask<K,V,U>
3966 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3967 >             transformer, action).invoke();
3968      }
3969  
3970      /**
3971       * Returns a non-null result from applying the given search
3972 <     * function on each entry, or null if none.
3972 >     * function on each entry, or null if none.  Upon success,
3973 >     * further element processing is suppressed and the results of
3974 >     * any other parallel invocations of the search function are
3975 >     * ignored.
3976       *
3977 +     * @param parallelismThreshold the (estimated) number of elements
3978 +     * needed for this operation to be executed in parallel
3979       * @param searchFunction a function returning a non-null
3980       * result on success, else null
3981       * @return a non-null result from applying the given search
3982       * function on each entry, or null if none
3983 +     * @since 1.8
3984       */
3985 <    @SuppressWarnings("unchecked") public <U> U searchEntriesSequentially
3986 <        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
3985 >    public <U> U searchEntries(long parallelismThreshold,
3986 >                               Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
3987          if (searchFunction == null) throw new NullPointerException();
3988 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3989 <        V v; U u;
3990 <        while ((v = it.advance()) != null) {
3916 <            if ((u = searchFunction.apply(entryFor((K)it.nextKey, v))) != null)
3917 <                return u;
3918 <        }
3919 <        return null;
3988 >        return new SearchEntriesTask<K,V,U>
3989 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3990 >             searchFunction, new AtomicReference<U>()).invoke();
3991      }
3992  
3993      /**
3994       * Returns the result of accumulating all entries using the
3995       * given reducer to combine values, or null if none.
3996       *
3997 +     * @param parallelismThreshold the (estimated) number of elements
3998 +     * needed for this operation to be executed in parallel
3999       * @param reducer a commutative associative combining function
4000       * @return the result of accumulating all entries
4001 +     * @since 1.8
4002       */
4003 <    @SuppressWarnings("unchecked") public Map.Entry<K,V> reduceEntriesSequentially
4004 <        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4003 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4004 >                                        BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4005          if (reducer == null) throw new NullPointerException();
4006 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4007 <        Map.Entry<K,V> r = null; V v;
4008 <        while ((v = it.advance()) != null) {
3935 <            Map.Entry<K,V> u = entryFor((K)it.nextKey, v);
3936 <            r = (r == null) ? u : reducer.apply(r, u);
3937 <        }
3938 <        return r;
4006 >        return new ReduceEntriesTask<K,V>
4007 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4008 >             null, reducer).invoke();
4009      }
4010  
4011      /**
# Line 3943 | Line 4013 | public class ConcurrentHashMapV8<K,V>
4013       * of all entries using the given reducer to combine values,
4014       * or null if none.
4015       *
4016 +     * @param parallelismThreshold the (estimated) number of elements
4017 +     * needed for this operation to be executed in parallel
4018       * @param transformer a function returning the transformation
4019       * for an element, or null if there is no transformation (in
4020       * which case it is not combined)
4021       * @param reducer a commutative associative combining function
4022       * @return the result of accumulating the given transformation
4023       * of all entries
4024 +     * @since 1.8
4025       */
4026 <    @SuppressWarnings("unchecked") public <U> U reduceEntriesSequentially
4027 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4028 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4026 >    public <U> U reduceEntries(long parallelismThreshold,
4027 >                               Fun<Map.Entry<K,V>, ? extends U> transformer,
4028 >                               BiFun<? super U, ? super U, ? extends U> reducer) {
4029          if (transformer == null || reducer == null)
4030              throw new NullPointerException();
4031 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4032 <        U r = null, u; V v;
4033 <        while ((v = it.advance()) != null) {
3961 <            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3962 <                r = (r == null) ? u : reducer.apply(r, u);
3963 <        }
3964 <        return r;
4031 >        return new MapReduceEntriesTask<K,V,U>
4032 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4033 >             null, transformer, reducer).invoke();
4034      }
4035  
4036      /**
# Line 3969 | Line 4038 | public class ConcurrentHashMapV8<K,V>
4038       * of all entries using the given reducer to combine values,
4039       * and the given basis as an identity value.
4040       *
4041 +     * @param parallelismThreshold the (estimated) number of elements
4042 +     * needed for this operation to be executed in parallel
4043       * @param transformer a function returning the transformation
4044       * for an element
4045       * @param basis the identity (initial default value) for the reduction
4046       * @param reducer a commutative associative combining function
4047       * @return the result of accumulating the given transformation
4048       * of all entries
4049 +     * @since 1.8
4050       */
4051 <    @SuppressWarnings("unchecked") public double reduceEntriesToDoubleSequentially
4052 <        (ObjectToDouble<Map.Entry<K,V>> transformer,
4053 <         double basis,
4054 <         DoubleByDoubleToDouble reducer) {
4051 >    public double reduceEntriesToDouble(long parallelismThreshold,
4052 >                                        ObjectToDouble<Map.Entry<K,V>> transformer,
4053 >                                        double basis,
4054 >                                        DoubleByDoubleToDouble reducer) {
4055          if (transformer == null || reducer == null)
4056              throw new NullPointerException();
4057 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4058 <        double r = basis; V v;
4059 <        while ((v = it.advance()) != null)
3988 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
3989 <        return r;
4057 >        return new MapReduceEntriesToDoubleTask<K,V>
4058 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4059 >             null, transformer, basis, reducer).invoke();
4060      }
4061  
4062      /**
# Line 3994 | Line 4064 | public class ConcurrentHashMapV8<K,V>
4064       * of all entries using the given reducer to combine values,
4065       * and the given basis as an identity value.
4066       *
4067 +     * @param parallelismThreshold the (estimated) number of elements
4068 +     * needed for this operation to be executed in parallel
4069       * @param transformer a function returning the transformation
4070       * for an element
4071       * @param basis the identity (initial default value) for the reduction
4072       * @param reducer a commutative associative combining function
4073 <     * @return  the result of accumulating the given transformation
4073 >     * @return the result of accumulating the given transformation
4074       * of all entries
4075 +     * @since 1.8
4076       */
4077 <    @SuppressWarnings("unchecked") public long reduceEntriesToLongSequentially
4078 <        (ObjectToLong<Map.Entry<K,V>> transformer,
4079 <         long basis,
4080 <         LongByLongToLong reducer) {
4077 >    public long reduceEntriesToLong(long parallelismThreshold,
4078 >                                    ObjectToLong<Map.Entry<K,V>> transformer,
4079 >                                    long basis,
4080 >                                    LongByLongToLong reducer) {
4081          if (transformer == null || reducer == null)
4082              throw new NullPointerException();
4083 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4084 <        long r = basis; V v;
4085 <        while ((v = it.advance()) != null)
4013 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4014 <        return r;
4083 >        return new MapReduceEntriesToLongTask<K,V>
4084 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4085 >             null, transformer, basis, reducer).invoke();
4086      }
4087  
4088      /**
# Line 4019 | Line 4090 | public class ConcurrentHashMapV8<K,V>
4090       * of all entries using the given reducer to combine values,
4091       * and the given basis as an identity value.
4092       *
4093 +     * @param parallelismThreshold the (estimated) number of elements
4094 +     * needed for this operation to be executed in parallel
4095       * @param transformer a function returning the transformation
4096       * for an element
4097       * @param basis the identity (initial default value) for the reduction
4098       * @param reducer a commutative associative combining function
4099       * @return the result of accumulating the given transformation
4100       * of all entries
4101 +     * @since 1.8
4102       */
4103 <    @SuppressWarnings("unchecked") public int reduceEntriesToIntSequentially
4104 <        (ObjectToInt<Map.Entry<K,V>> transformer,
4105 <         int basis,
4106 <         IntByIntToInt reducer) {
4103 >    public int reduceEntriesToInt(long parallelismThreshold,
4104 >                                  ObjectToInt<Map.Entry<K,V>> transformer,
4105 >                                  int basis,
4106 >                                  IntByIntToInt reducer) {
4107          if (transformer == null || reducer == null)
4108              throw new NullPointerException();
4109 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4110 <        int r = basis; V v;
4111 <        while ((v = it.advance()) != null)
4038 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4039 <        return r;
4040 <    }
4041 <
4042 <    // Parallel bulk operations
4043 <
4044 <    /**
4045 <     * Performs the given action for each (key, value).
4046 <     *
4047 <     * @param action the action
4048 <     */
4049 <    public void forEachInParallel(BiAction<K,V> action) {
4050 <        ForkJoinTasks.forEach
4051 <            (this, action).invoke();
4052 <    }
4053 <
4054 <    /**
4055 <     * Performs the given action for each non-null transformation
4056 <     * of each (key, value).
4057 <     *
4058 <     * @param transformer a function returning the transformation
4059 <     * for an element, or null if there is no transformation (in
4060 <     * which case the action is not applied)
4061 <     * @param action the action
4062 <     */
4063 <    public <U> void forEachInParallel
4064 <        (BiFun<? super K, ? super V, ? extends U> transformer,
4065 <                            Action<U> action) {
4066 <        ForkJoinTasks.forEach
4067 <            (this, transformer, action).invoke();
4068 <    }
4069 <
4070 <    /**
4071 <     * Returns a non-null result from applying the given search
4072 <     * function on each (key, value), or null if none.  Upon
4073 <     * success, further element processing is suppressed and the
4074 <     * results of any other parallel invocations of the search
4075 <     * function are ignored.
4076 <     *
4077 <     * @param searchFunction a function returning a non-null
4078 <     * result on success, else null
4079 <     * @return a non-null result from applying the given search
4080 <     * function on each (key, value), or null if none
4081 <     */
4082 <    public <U> U searchInParallel
4083 <        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
4084 <        return ForkJoinTasks.search
4085 <            (this, searchFunction).invoke();
4086 <    }
4087 <
4088 <    /**
4089 <     * Returns the result of accumulating the given transformation
4090 <     * of all (key, value) pairs using the given reducer to
4091 <     * combine values, or null if none.
4092 <     *
4093 <     * @param transformer a function returning the transformation
4094 <     * for an element, or null if there is no transformation (in
4095 <     * which case it is not combined)
4096 <     * @param reducer a commutative associative combining function
4097 <     * @return the result of accumulating the given transformation
4098 <     * of all (key, value) pairs
4099 <     */
4100 <    public <U> U reduceInParallel
4101 <        (BiFun<? super K, ? super V, ? extends U> transformer,
4102 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4103 <        return ForkJoinTasks.reduce
4104 <            (this, transformer, reducer).invoke();
4105 <    }
4106 <
4107 <    /**
4108 <     * Returns the result of accumulating the given transformation
4109 <     * of all (key, value) pairs using the given reducer to
4110 <     * combine values, and the given basis as an identity value.
4111 <     *
4112 <     * @param transformer a function returning the transformation
4113 <     * for an element
4114 <     * @param basis the identity (initial default value) for the reduction
4115 <     * @param reducer a commutative associative combining function
4116 <     * @return the result of accumulating the given transformation
4117 <     * of all (key, value) pairs
4118 <     */
4119 <    public double reduceToDoubleInParallel
4120 <        (ObjectByObjectToDouble<? super K, ? super V> transformer,
4121 <         double basis,
4122 <         DoubleByDoubleToDouble reducer) {
4123 <        return ForkJoinTasks.reduceToDouble
4124 <            (this, transformer, basis, reducer).invoke();
4125 <    }
4126 <
4127 <    /**
4128 <     * Returns the result of accumulating the given transformation
4129 <     * of all (key, value) pairs using the given reducer to
4130 <     * combine values, and the given basis as an identity value.
4131 <     *
4132 <     * @param transformer a function returning the transformation
4133 <     * for an element
4134 <     * @param basis the identity (initial default value) for the reduction
4135 <     * @param reducer a commutative associative combining function
4136 <     * @return the result of accumulating the given transformation
4137 <     * of all (key, value) pairs
4138 <     */
4139 <    public long reduceToLongInParallel
4140 <        (ObjectByObjectToLong<? super K, ? super V> transformer,
4141 <         long basis,
4142 <         LongByLongToLong reducer) {
4143 <        return ForkJoinTasks.reduceToLong
4144 <            (this, transformer, basis, reducer).invoke();
4145 <    }
4146 <
4147 <    /**
4148 <     * Returns the result of accumulating the given transformation
4149 <     * of all (key, value) pairs using the given reducer to
4150 <     * combine values, and the given basis as an identity value.
4151 <     *
4152 <     * @param transformer a function returning the transformation
4153 <     * for an element
4154 <     * @param basis the identity (initial default value) for the reduction
4155 <     * @param reducer a commutative associative combining function
4156 <     * @return the result of accumulating the given transformation
4157 <     * of all (key, value) pairs
4158 <     */
4159 <    public int reduceToIntInParallel
4160 <        (ObjectByObjectToInt<? super K, ? super V> transformer,
4161 <         int basis,
4162 <         IntByIntToInt reducer) {
4163 <        return ForkJoinTasks.reduceToInt
4164 <            (this, transformer, basis, reducer).invoke();
4165 <    }
4166 <
4167 <    /**
4168 <     * Performs the given action for each key.
4169 <     *
4170 <     * @param action the action
4171 <     */
4172 <    public void forEachKeyInParallel(Action<K> action) {
4173 <        ForkJoinTasks.forEachKey
4174 <            (this, action).invoke();
4175 <    }
4176 <
4177 <    /**
4178 <     * Performs the given action for each non-null transformation
4179 <     * of each key.
4180 <     *
4181 <     * @param transformer a function returning the transformation
4182 <     * for an element, or null if there is no transformation (in
4183 <     * which case the action is not applied)
4184 <     * @param action the action
4185 <     */
4186 <    public <U> void forEachKeyInParallel
4187 <        (Fun<? super K, ? extends U> transformer,
4188 <         Action<U> action) {
4189 <        ForkJoinTasks.forEachKey
4190 <            (this, transformer, action).invoke();
4191 <    }
4192 <
4193 <    /**
4194 <     * Returns a non-null result from applying the given search
4195 <     * function on each key, or null if none. Upon success,
4196 <     * further element processing is suppressed and the results of
4197 <     * any other parallel invocations of the search function are
4198 <     * ignored.
4199 <     *
4200 <     * @param searchFunction a function returning a non-null
4201 <     * result on success, else null
4202 <     * @return a non-null result from applying the given search
4203 <     * function on each key, or null if none
4204 <     */
4205 <    public <U> U searchKeysInParallel
4206 <        (Fun<? super K, ? extends U> searchFunction) {
4207 <        return ForkJoinTasks.searchKeys
4208 <            (this, searchFunction).invoke();
4209 <    }
4210 <
4211 <    /**
4212 <     * Returns the result of accumulating all keys using the given
4213 <     * reducer to combine values, or null if none.
4214 <     *
4215 <     * @param reducer a commutative associative combining function
4216 <     * @return the result of accumulating all keys using the given
4217 <     * reducer to combine values, or null if none
4218 <     */
4219 <    public K reduceKeysInParallel
4220 <        (BiFun<? super K, ? super K, ? extends K> reducer) {
4221 <        return ForkJoinTasks.reduceKeys
4222 <            (this, reducer).invoke();
4223 <    }
4224 <
4225 <    /**
4226 <     * Returns the result of accumulating the given transformation
4227 <     * of all keys using the given reducer to combine values, or
4228 <     * null if none.
4229 <     *
4230 <     * @param transformer a function returning the transformation
4231 <     * for an element, or null if there is no transformation (in
4232 <     * which case it is not combined)
4233 <     * @param reducer a commutative associative combining function
4234 <     * @return the result of accumulating the given transformation
4235 <     * of all keys
4236 <     */
4237 <    public <U> U reduceKeysInParallel
4238 <        (Fun<? super K, ? extends U> transformer,
4239 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4240 <        return ForkJoinTasks.reduceKeys
4241 <            (this, transformer, reducer).invoke();
4242 <    }
4243 <
4244 <    /**
4245 <     * Returns the result of accumulating the given transformation
4246 <     * of all keys using the given reducer to combine values, and
4247 <     * the given basis as an identity value.
4248 <     *
4249 <     * @param transformer a function returning the transformation
4250 <     * for an element
4251 <     * @param basis the identity (initial default value) for the reduction
4252 <     * @param reducer a commutative associative combining function
4253 <     * @return  the result of accumulating the given transformation
4254 <     * of all keys
4255 <     */
4256 <    public double reduceKeysToDoubleInParallel
4257 <        (ObjectToDouble<? super K> transformer,
4258 <         double basis,
4259 <         DoubleByDoubleToDouble reducer) {
4260 <        return ForkJoinTasks.reduceKeysToDouble
4261 <            (this, transformer, basis, reducer).invoke();
4262 <    }
4263 <
4264 <    /**
4265 <     * Returns the result of accumulating the given transformation
4266 <     * of all keys using the given reducer to combine values, and
4267 <     * the given basis as an identity value.
4268 <     *
4269 <     * @param transformer a function returning the transformation
4270 <     * for an element
4271 <     * @param basis the identity (initial default value) for the reduction
4272 <     * @param reducer a commutative associative combining function
4273 <     * @return the result of accumulating the given transformation
4274 <     * of all keys
4275 <     */
4276 <    public long reduceKeysToLongInParallel
4277 <        (ObjectToLong<? super K> transformer,
4278 <         long basis,
4279 <         LongByLongToLong reducer) {
4280 <        return ForkJoinTasks.reduceKeysToLong
4281 <            (this, transformer, basis, reducer).invoke();
4282 <    }
4283 <
4284 <    /**
4285 <     * Returns the result of accumulating the given transformation
4286 <     * of all keys using the given reducer to combine values, and
4287 <     * the given basis as an identity value.
4288 <     *
4289 <     * @param transformer a function returning the transformation
4290 <     * for an element
4291 <     * @param basis the identity (initial default value) for the reduction
4292 <     * @param reducer a commutative associative combining function
4293 <     * @return the result of accumulating the given transformation
4294 <     * of all keys
4295 <     */
4296 <    public int reduceKeysToIntInParallel
4297 <        (ObjectToInt<? super K> transformer,
4298 <         int basis,
4299 <         IntByIntToInt reducer) {
4300 <        return ForkJoinTasks.reduceKeysToInt
4301 <            (this, transformer, basis, reducer).invoke();
4302 <    }
4303 <
4304 <    /**
4305 <     * Performs the given action for each value.
4306 <     *
4307 <     * @param action the action
4308 <     */
4309 <    public void forEachValueInParallel(Action<V> action) {
4310 <        ForkJoinTasks.forEachValue
4311 <            (this, action).invoke();
4312 <    }
4313 <
4314 <    /**
4315 <     * Performs the given action for each non-null transformation
4316 <     * of each value.
4317 <     *
4318 <     * @param transformer a function returning the transformation
4319 <     * for an element, or null if there is no transformation (in
4320 <     * which case the action is not applied)
4321 <     */
4322 <    public <U> void forEachValueInParallel
4323 <        (Fun<? super V, ? extends U> transformer,
4324 <         Action<U> action) {
4325 <        ForkJoinTasks.forEachValue
4326 <            (this, transformer, action).invoke();
4327 <    }
4328 <
4329 <    /**
4330 <     * Returns a non-null result from applying the given search
4331 <     * function on each value, or null if none.  Upon success,
4332 <     * further element processing is suppressed and the results of
4333 <     * any other parallel invocations of the search function are
4334 <     * ignored.
4335 <     *
4336 <     * @param searchFunction a function returning a non-null
4337 <     * result on success, else null
4338 <     * @return a non-null result from applying the given search
4339 <     * function on each value, or null if none
4340 <     */
4341 <    public <U> U searchValuesInParallel
4342 <        (Fun<? super V, ? extends U> searchFunction) {
4343 <        return ForkJoinTasks.searchValues
4344 <            (this, searchFunction).invoke();
4345 <    }
4346 <
4347 <    /**
4348 <     * Returns the result of accumulating all values using the
4349 <     * given reducer to combine values, or null if none.
4350 <     *
4351 <     * @param reducer a commutative associative combining function
4352 <     * @return  the result of accumulating all values
4353 <     */
4354 <    public V reduceValuesInParallel
4355 <        (BiFun<? super V, ? super V, ? extends V> reducer) {
4356 <        return ForkJoinTasks.reduceValues
4357 <            (this, reducer).invoke();
4358 <    }
4359 <
4360 <    /**
4361 <     * Returns the result of accumulating the given transformation
4362 <     * of all values using the given reducer to combine values, or
4363 <     * null if none.
4364 <     *
4365 <     * @param transformer a function returning the transformation
4366 <     * for an element, or null if there is no transformation (in
4367 <     * which case it is not combined)
4368 <     * @param reducer a commutative associative combining function
4369 <     * @return the result of accumulating the given transformation
4370 <     * of all values
4371 <     */
4372 <    public <U> U reduceValuesInParallel
4373 <        (Fun<? super V, ? extends U> transformer,
4374 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4375 <        return ForkJoinTasks.reduceValues
4376 <            (this, transformer, reducer).invoke();
4377 <    }
4378 <
4379 <    /**
4380 <     * Returns the result of accumulating the given transformation
4381 <     * of all values using the given reducer to combine values,
4382 <     * and the given basis as an identity value.
4383 <     *
4384 <     * @param transformer a function returning the transformation
4385 <     * for an element
4386 <     * @param basis the identity (initial default value) for the reduction
4387 <     * @param reducer a commutative associative combining function
4388 <     * @return the result of accumulating the given transformation
4389 <     * of all values
4390 <     */
4391 <    public double reduceValuesToDoubleInParallel
4392 <        (ObjectToDouble<? super V> transformer,
4393 <         double basis,
4394 <         DoubleByDoubleToDouble reducer) {
4395 <        return ForkJoinTasks.reduceValuesToDouble
4396 <            (this, transformer, basis, reducer).invoke();
4397 <    }
4398 <
4399 <    /**
4400 <     * Returns the result of accumulating the given transformation
4401 <     * of all values using the given reducer to combine values,
4402 <     * and the given basis as an identity value.
4403 <     *
4404 <     * @param transformer a function returning the transformation
4405 <     * for an element
4406 <     * @param basis the identity (initial default value) for the reduction
4407 <     * @param reducer a commutative associative combining function
4408 <     * @return the result of accumulating the given transformation
4409 <     * of all values
4410 <     */
4411 <    public long reduceValuesToLongInParallel
4412 <        (ObjectToLong<? super V> transformer,
4413 <         long basis,
4414 <         LongByLongToLong reducer) {
4415 <        return ForkJoinTasks.reduceValuesToLong
4416 <            (this, transformer, basis, reducer).invoke();
4417 <    }
4418 <
4419 <    /**
4420 <     * Returns the result of accumulating the given transformation
4421 <     * of all values using the given reducer to combine values,
4422 <     * and the given basis as an identity value.
4423 <     *
4424 <     * @param transformer a function returning the transformation
4425 <     * for an element
4426 <     * @param basis the identity (initial default value) for the reduction
4427 <     * @param reducer a commutative associative combining function
4428 <     * @return the result of accumulating the given transformation
4429 <     * of all values
4430 <     */
4431 <    public int reduceValuesToIntInParallel
4432 <        (ObjectToInt<? super V> transformer,
4433 <         int basis,
4434 <         IntByIntToInt reducer) {
4435 <        return ForkJoinTasks.reduceValuesToInt
4436 <            (this, transformer, basis, reducer).invoke();
4437 <    }
4438 <
4439 <    /**
4440 <     * Performs the given action for each entry.
4441 <     *
4442 <     * @param action the action
4443 <     */
4444 <    public void forEachEntryInParallel(Action<Map.Entry<K,V>> action) {
4445 <        ForkJoinTasks.forEachEntry
4446 <            (this, action).invoke();
4447 <    }
4448 <
4449 <    /**
4450 <     * Performs the given action for each non-null transformation
4451 <     * of each entry.
4452 <     *
4453 <     * @param transformer a function returning the transformation
4454 <     * for an element, or null if there is no transformation (in
4455 <     * which case the action is not applied)
4456 <     * @param action the action
4457 <     */
4458 <    public <U> void forEachEntryInParallel
4459 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4460 <         Action<U> action) {
4461 <        ForkJoinTasks.forEachEntry
4462 <            (this, transformer, action).invoke();
4463 <    }
4464 <
4465 <    /**
4466 <     * Returns a non-null result from applying the given search
4467 <     * function on each entry, or null if none.  Upon success,
4468 <     * further element processing is suppressed and the results of
4469 <     * any other parallel invocations of the search function are
4470 <     * ignored.
4471 <     *
4472 <     * @param searchFunction a function returning a non-null
4473 <     * result on success, else null
4474 <     * @return a non-null result from applying the given search
4475 <     * function on each entry, or null if none
4476 <     */
4477 <    public <U> U searchEntriesInParallel
4478 <        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4479 <        return ForkJoinTasks.searchEntries
4480 <            (this, searchFunction).invoke();
4481 <    }
4482 <
4483 <    /**
4484 <     * Returns the result of accumulating all entries using the
4485 <     * given reducer to combine values, or null if none.
4486 <     *
4487 <     * @param reducer a commutative associative combining function
4488 <     * @return the result of accumulating all entries
4489 <     */
4490 <    public Map.Entry<K,V> reduceEntriesInParallel
4491 <        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4492 <        return ForkJoinTasks.reduceEntries
4493 <            (this, reducer).invoke();
4494 <    }
4495 <
4496 <    /**
4497 <     * Returns the result of accumulating the given transformation
4498 <     * of all entries using the given reducer to combine values,
4499 <     * or null if none.
4500 <     *
4501 <     * @param transformer a function returning the transformation
4502 <     * for an element, or null if there is no transformation (in
4503 <     * which case it is not combined)
4504 <     * @param reducer a commutative associative combining function
4505 <     * @return the result of accumulating the given transformation
4506 <     * of all entries
4507 <     */
4508 <    public <U> U reduceEntriesInParallel
4509 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4510 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4511 <        return ForkJoinTasks.reduceEntries
4512 <            (this, transformer, reducer).invoke();
4513 <    }
4514 <
4515 <    /**
4516 <     * Returns the result of accumulating the given transformation
4517 <     * of all entries using the given reducer to combine values,
4518 <     * and the given basis as an identity value.
4519 <     *
4520 <     * @param transformer a function returning the transformation
4521 <     * for an element
4522 <     * @param basis the identity (initial default value) for the reduction
4523 <     * @param reducer a commutative associative combining function
4524 <     * @return the result of accumulating the given transformation
4525 <     * of all entries
4526 <     */
4527 <    public double reduceEntriesToDoubleInParallel
4528 <        (ObjectToDouble<Map.Entry<K,V>> transformer,
4529 <         double basis,
4530 <         DoubleByDoubleToDouble reducer) {
4531 <        return ForkJoinTasks.reduceEntriesToDouble
4532 <            (this, transformer, basis, reducer).invoke();
4533 <    }
4534 <
4535 <    /**
4536 <     * Returns the result of accumulating the given transformation
4537 <     * of all entries using the given reducer to combine values,
4538 <     * and the given basis as an identity value.
4539 <     *
4540 <     * @param transformer a function returning the transformation
4541 <     * for an element
4542 <     * @param basis the identity (initial default value) for the reduction
4543 <     * @param reducer a commutative associative combining function
4544 <     * @return  the result of accumulating the given transformation
4545 <     * of all entries
4546 <     */
4547 <    public long reduceEntriesToLongInParallel
4548 <        (ObjectToLong<Map.Entry<K,V>> transformer,
4549 <         long basis,
4550 <         LongByLongToLong reducer) {
4551 <        return ForkJoinTasks.reduceEntriesToLong
4552 <            (this, transformer, basis, reducer).invoke();
4553 <    }
4554 <
4555 <    /**
4556 <     * Returns the result of accumulating the given transformation
4557 <     * of all entries using the given reducer to combine values,
4558 <     * and the given basis as an identity value.
4559 <     *
4560 <     * @param transformer a function returning the transformation
4561 <     * for an element
4562 <     * @param basis the identity (initial default value) for the reduction
4563 <     * @param reducer a commutative associative combining function
4564 <     * @return the result of accumulating the given transformation
4565 <     * of all entries
4566 <     */
4567 <    public int reduceEntriesToIntInParallel
4568 <        (ObjectToInt<Map.Entry<K,V>> transformer,
4569 <         int basis,
4570 <         IntByIntToInt reducer) {
4571 <        return ForkJoinTasks.reduceEntriesToInt
4572 <            (this, transformer, basis, reducer).invoke();
4109 >        return new MapReduceEntriesToIntTask<K,V>
4110 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4111 >             null, transformer, basis, reducer).invoke();
4112      }
4113  
4114  
# Line 4578 | Line 4117 | public class ConcurrentHashMapV8<K,V>
4117      /**
4118       * Base class for views.
4119       */
4120 <    abstract static class CHMView<K,V> {
4120 >    abstract static class CollectionView<K,V,E>
4121 >        implements Collection<E>, java.io.Serializable {
4122 >        private static final long serialVersionUID = 7249069246763182397L;
4123          final ConcurrentHashMapV8<K,V> map;
4124 <        CHMView(ConcurrentHashMapV8<K,V> map)  { this.map = map; }
4124 >        CollectionView(ConcurrentHashMapV8<K,V> map)  { this.map = map; }
4125  
4126          /**
4127           * Returns the map backing this view.
# Line 4589 | Line 4130 | public class ConcurrentHashMapV8<K,V>
4130           */
4131          public ConcurrentHashMapV8<K,V> getMap() { return map; }
4132  
4133 <        public final int size()                 { return map.size(); }
4134 <        public final boolean isEmpty()          { return map.isEmpty(); }
4135 <        public final void clear()               { map.clear(); }
4133 >        /**
4134 >         * Removes all of the elements from this view, by removing all
4135 >         * the mappings from the map backing this view.
4136 >         */
4137 >        public final void clear()      { map.clear(); }
4138 >        public final int size()        { return map.size(); }
4139 >        public final boolean isEmpty() { return map.isEmpty(); }
4140  
4141          // implementations below rely on concrete classes supplying these
4142 <        public abstract Iterator<?> iterator();
4142 >        // abstract methods
4143 >        /**
4144 >         * Returns a "weakly consistent" iterator that will never
4145 >         * throw {@link ConcurrentModificationException}, and
4146 >         * guarantees to traverse elements as they existed upon
4147 >         * construction of the iterator, and may (but is not
4148 >         * guaranteed to) reflect any modifications subsequent to
4149 >         * construction.
4150 >         */
4151 >        public abstract Iterator<E> iterator();
4152          public abstract boolean contains(Object o);
4153          public abstract boolean remove(Object o);
4154  
# Line 4602 | Line 4156 | public class ConcurrentHashMapV8<K,V>
4156  
4157          public final Object[] toArray() {
4158              long sz = map.mappingCount();
4159 <            if (sz > (long)(MAX_ARRAY_SIZE))
4159 >            if (sz > MAX_ARRAY_SIZE)
4160                  throw new OutOfMemoryError(oomeMsg);
4161              int n = (int)sz;
4162              Object[] r = new Object[n];
4163              int i = 0;
4164 <            Iterator<?> it = iterator();
4611 <            while (it.hasNext()) {
4164 >            for (E e : this) {
4165                  if (i == n) {
4166                      if (n >= MAX_ARRAY_SIZE)
4167                          throw new OutOfMemoryError(oomeMsg);
# Line 4618 | Line 4171 | public class ConcurrentHashMapV8<K,V>
4171                          n += (n >>> 1) + 1;
4172                      r = Arrays.copyOf(r, n);
4173                  }
4174 <                r[i++] = it.next();
4174 >                r[i++] = e;
4175              }
4176              return (i == n) ? r : Arrays.copyOf(r, i);
4177          }
4178  
4179 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4179 >        @SuppressWarnings("unchecked")
4180 >        public final <T> T[] toArray(T[] a) {
4181              long sz = map.mappingCount();
4182 <            if (sz > (long)(MAX_ARRAY_SIZE))
4182 >            if (sz > MAX_ARRAY_SIZE)
4183                  throw new OutOfMemoryError(oomeMsg);
4184              int m = (int)sz;
4185              T[] r = (a.length >= m) ? a :
# Line 4633 | Line 4187 | public class ConcurrentHashMapV8<K,V>
4187                  .newInstance(a.getClass().getComponentType(), m);
4188              int n = r.length;
4189              int i = 0;
4190 <            Iterator<?> it = iterator();
4637 <            while (it.hasNext()) {
4190 >            for (E e : this) {
4191                  if (i == n) {
4192                      if (n >= MAX_ARRAY_SIZE)
4193                          throw new OutOfMemoryError(oomeMsg);
# Line 4644 | Line 4197 | public class ConcurrentHashMapV8<K,V>
4197                          n += (n >>> 1) + 1;
4198                      r = Arrays.copyOf(r, n);
4199                  }
4200 <                r[i++] = (T)it.next();
4200 >                r[i++] = (T)e;
4201              }
4202              if (a == r && i < n) {
4203                  r[i] = null; // null-terminate
# Line 4653 | Line 4206 | public class ConcurrentHashMapV8<K,V>
4206              return (i == n) ? r : Arrays.copyOf(r, i);
4207          }
4208  
4209 <        public final int hashCode() {
4210 <            int h = 0;
4211 <            for (Iterator<?> it = iterator(); it.hasNext();)
4212 <                h += it.next().hashCode();
4213 <            return h;
4214 <        }
4215 <
4209 >        /**
4210 >         * Returns a string representation of this collection.
4211 >         * The string representation consists of the string representations
4212 >         * of the collection's elements in the order they are returned by
4213 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4214 >         * Adjacent elements are separated by the characters {@code ", "}
4215 >         * (comma and space).  Elements are converted to strings as by
4216 >         * {@link String#valueOf(Object)}.
4217 >         *
4218 >         * @return a string representation of this collection
4219 >         */
4220          public final String toString() {
4221              StringBuilder sb = new StringBuilder();
4222              sb.append('[');
4223 <            Iterator<?> it = iterator();
4223 >            Iterator<E> it = iterator();
4224              if (it.hasNext()) {
4225                  for (;;) {
4226                      Object e = it.next();
# Line 4678 | Line 4235 | public class ConcurrentHashMapV8<K,V>
4235  
4236          public final boolean containsAll(Collection<?> c) {
4237              if (c != this) {
4238 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4682 <                    Object e = it.next();
4238 >                for (Object e : c) {
4239                      if (e == null || !contains(e))
4240                          return false;
4241                  }
# Line 4689 | Line 4245 | public class ConcurrentHashMapV8<K,V>
4245  
4246          public final boolean removeAll(Collection<?> c) {
4247              boolean modified = false;
4248 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4248 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4249                  if (c.contains(it.next())) {
4250                      it.remove();
4251                      modified = true;
# Line 4700 | Line 4256 | public class ConcurrentHashMapV8<K,V>
4256  
4257          public final boolean retainAll(Collection<?> c) {
4258              boolean modified = false;
4259 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4259 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4260                  if (!c.contains(it.next())) {
4261                      it.remove();
4262                      modified = true;
# Line 4714 | Line 4270 | public class ConcurrentHashMapV8<K,V>
4270      /**
4271       * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4272       * which additions may optionally be enabled by mapping to a
4273 <     * common value.  This class cannot be directly instantiated. See
4274 <     * {@link #keySet()}, {@link #keySet(Object)}, {@link #newKeySet()},
4275 <     * {@link #newKeySet(int)}.
4273 >     * common value.  This class cannot be directly instantiated.
4274 >     * See {@link #keySet() keySet()},
4275 >     * {@link #keySet(Object) keySet(V)},
4276 >     * {@link #newKeySet() newKeySet()},
4277 >     * {@link #newKeySet(int) newKeySet(int)}.
4278 >     *
4279 >     * @since 1.8
4280       */
4281 <    public static class KeySetView<K,V> extends CHMView<K,V>
4281 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4282          implements Set<K>, java.io.Serializable {
4283          private static final long serialVersionUID = 7249069246763182397L;
4284          private final V value;
# Line 4736 | Line 4296 | public class ConcurrentHashMapV8<K,V>
4296           */
4297          public V getMappedValue() { return value; }
4298  
4299 <        // implement Set API
4300 <
4299 >        /**
4300 >         * {@inheritDoc}
4301 >         * @throws NullPointerException if the specified key is null
4302 >         */
4303          public boolean contains(Object o) { return map.containsKey(o); }
4742        public boolean remove(Object o)   { return map.remove(o) != null; }
4304  
4305          /**
4306 <         * Returns a "weakly consistent" iterator that will never
4307 <         * throw {@link ConcurrentModificationException}, and
4308 <         * guarantees to traverse elements as they existed upon
4748 <         * construction of the iterator, and may (but is not
4749 <         * guaranteed to) reflect any modifications subsequent to
4750 <         * construction.
4306 >         * Removes the key from this map view, by removing the key (and its
4307 >         * corresponding value) from the backing map.  This method does
4308 >         * nothing if the key is not in the map.
4309           *
4310 <         * @return an iterator over the keys of this map
4310 >         * @param  o the key to be removed from the backing map
4311 >         * @return {@code true} if the backing map contained the specified key
4312 >         * @throws NullPointerException if the specified key is null
4313 >         */
4314 >        public boolean remove(Object o) { return map.remove(o) != null; }
4315 >
4316 >        /**
4317 >         * @return an iterator over the keys of the backing map
4318 >         */
4319 >        public Iterator<K> iterator() {
4320 >            Node<K,V>[] t;
4321 >            ConcurrentHashMapV8<K,V> m = map;
4322 >            int f = (t = m.table) == null ? 0 : t.length;
4323 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4324 >        }
4325 >
4326 >        /**
4327 >         * Adds the specified key to this set view by mapping the key to
4328 >         * the default mapped value in the backing map, if defined.
4329 >         *
4330 >         * @param e key to be added
4331 >         * @return {@code true} if this set changed as a result of the call
4332 >         * @throws NullPointerException if the specified key is null
4333 >         * @throws UnsupportedOperationException if no default mapped value
4334 >         * for additions was provided
4335           */
4754        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4336          public boolean add(K e) {
4337              V v;
4338              if ((v = value) == null)
4339                  throw new UnsupportedOperationException();
4340 <            return map.internalPut(e, v, true) == null;
4340 >            return map.putVal(e, v, true) == null;
4341          }
4342 +
4343 +        /**
4344 +         * Adds all of the elements in the specified collection to this set,
4345 +         * as if by calling {@link #add} on each one.
4346 +         *
4347 +         * @param c the elements to be inserted into this set
4348 +         * @return {@code true} if this set changed as a result of the call
4349 +         * @throws NullPointerException if the collection or any of its
4350 +         * elements are {@code null}
4351 +         * @throws UnsupportedOperationException if no default mapped value
4352 +         * for additions was provided
4353 +         */
4354          public boolean addAll(Collection<? extends K> c) {
4355              boolean added = false;
4356              V v;
4357              if ((v = value) == null)
4358                  throw new UnsupportedOperationException();
4359              for (K e : c) {
4360 <                if (map.internalPut(e, v, true) == null)
4360 >                if (map.putVal(e, v, true) == null)
4361                      added = true;
4362              }
4363              return added;
4364          }
4365 +
4366 +        public int hashCode() {
4367 +            int h = 0;
4368 +            for (K e : this)
4369 +                h += e.hashCode();
4370 +            return h;
4371 +        }
4372 +
4373          public boolean equals(Object o) {
4374              Set<?> c;
4375              return ((o instanceof Set) &&
4376                      ((c = (Set<?>)o) == this ||
4377                       (containsAll(c) && c.containsAll(this))));
4378          }
4379 +
4380 +        public ConcurrentHashMapSpliterator<K> spliterator() {
4381 +            Node<K,V>[] t;
4382 +            ConcurrentHashMapV8<K,V> m = map;
4383 +            long n = m.sumCount();
4384 +            int f = (t = m.table) == null ? 0 : t.length;
4385 +            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4386 +        }
4387 +
4388 +        public void forEach(Action<? super K> action) {
4389 +            if (action == null) throw new NullPointerException();
4390 +            Node<K,V>[] t;
4391 +            if ((t = map.table) != null) {
4392 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4393 +                for (Node<K,V> p; (p = it.advance()) != null; )
4394 +                    action.apply(p.key);
4395 +            }
4396 +        }
4397      }
4398  
4399      /**
4400       * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4401       * values, in which additions are disabled. This class cannot be
4402       * directly instantiated. See {@link #values()}.
4784     *
4785     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4786     * that will never throw {@link ConcurrentModificationException},
4787     * and guarantees to traverse elements as they existed upon
4788     * construction of the iterator, and may (but is not guaranteed to)
4789     * reflect any modifications subsequent to construction.
4403       */
4404 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4405 <        implements Collection<V> {
4406 <        ValuesView(ConcurrentHashMapV8<K,V> map)   { super(map); }
4407 <        public final boolean contains(Object o) { return map.containsValue(o); }
4404 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4405 >        implements Collection<V>, java.io.Serializable {
4406 >        private static final long serialVersionUID = 2249069246763182397L;
4407 >        ValuesView(ConcurrentHashMapV8<K,V> map) { super(map); }
4408 >        public final boolean contains(Object o) {
4409 >            return map.containsValue(o);
4410 >        }
4411 >
4412          public final boolean remove(Object o) {
4413              if (o != null) {
4414 <                Iterator<V> it = new ValueIterator<K,V>(map);
4798 <                while (it.hasNext()) {
4414 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4415                      if (o.equals(it.next())) {
4416                          it.remove();
4417                          return true;
# Line 4805 | Line 4421 | public class ConcurrentHashMapV8<K,V>
4421              return false;
4422          }
4423  
4808        /**
4809         * Returns a "weakly consistent" iterator that will never
4810         * throw {@link ConcurrentModificationException}, and
4811         * guarantees to traverse elements as they existed upon
4812         * construction of the iterator, and may (but is not
4813         * guaranteed to) reflect any modifications subsequent to
4814         * construction.
4815         *
4816         * @return an iterator over the values of this map
4817         */
4424          public final Iterator<V> iterator() {
4425 <            return new ValueIterator<K,V>(map);
4425 >            ConcurrentHashMapV8<K,V> m = map;
4426 >            Node<K,V>[] t;
4427 >            int f = (t = m.table) == null ? 0 : t.length;
4428 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4429          }
4430 +
4431          public final boolean add(V e) {
4432              throw new UnsupportedOperationException();
4433          }
# Line 4825 | Line 4435 | public class ConcurrentHashMapV8<K,V>
4435              throw new UnsupportedOperationException();
4436          }
4437  
4438 +        public ConcurrentHashMapSpliterator<V> spliterator() {
4439 +            Node<K,V>[] t;
4440 +            ConcurrentHashMapV8<K,V> m = map;
4441 +            long n = m.sumCount();
4442 +            int f = (t = m.table) == null ? 0 : t.length;
4443 +            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4444 +        }
4445 +
4446 +        public void forEach(Action<? super V> action) {
4447 +            if (action == null) throw new NullPointerException();
4448 +            Node<K,V>[] t;
4449 +            if ((t = map.table) != null) {
4450 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4451 +                for (Node<K,V> p; (p = it.advance()) != null; )
4452 +                    action.apply(p.val);
4453 +            }
4454 +        }
4455      }
4456  
4457      /**
# Line 4832 | Line 4459 | public class ConcurrentHashMapV8<K,V>
4459       * entries.  This class cannot be directly instantiated. See
4460       * {@link #entrySet()}.
4461       */
4462 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4463 <        implements Set<Map.Entry<K,V>> {
4462 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4463 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4464 >        private static final long serialVersionUID = 2249069246763182397L;
4465          EntrySetView(ConcurrentHashMapV8<K,V> map) { super(map); }
4466 <        public final boolean contains(Object o) {
4466 >
4467 >        public boolean contains(Object o) {
4468              Object k, v, r; Map.Entry<?,?> e;
4469              return ((o instanceof Map.Entry) &&
4470                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4843 | Line 4472 | public class ConcurrentHashMapV8<K,V>
4472                      (v = e.getValue()) != null &&
4473                      (v == r || v.equals(r)));
4474          }
4475 <        public final boolean remove(Object o) {
4475 >
4476 >        public boolean remove(Object o) {
4477              Object k, v; Map.Entry<?,?> e;
4478              return ((o instanceof Map.Entry) &&
4479                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4852 | Line 4482 | public class ConcurrentHashMapV8<K,V>
4482          }
4483  
4484          /**
4485 <         * Returns a "weakly consistent" iterator that will never
4856 <         * throw {@link ConcurrentModificationException}, and
4857 <         * guarantees to traverse elements as they existed upon
4858 <         * construction of the iterator, and may (but is not
4859 <         * guaranteed to) reflect any modifications subsequent to
4860 <         * construction.
4861 <         *
4862 <         * @return an iterator over the entries of this map
4485 >         * @return an iterator over the entries of the backing map
4486           */
4487 <        public final Iterator<Map.Entry<K,V>> iterator() {
4488 <            return new EntryIterator<K,V>(map);
4487 >        public Iterator<Map.Entry<K,V>> iterator() {
4488 >            ConcurrentHashMapV8<K,V> m = map;
4489 >            Node<K,V>[] t;
4490 >            int f = (t = m.table) == null ? 0 : t.length;
4491 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4492          }
4493  
4494 <        public final boolean add(Entry<K,V> e) {
4495 <            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4494 >        public boolean add(Entry<K,V> e) {
4495 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4496          }
4497 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4497 >
4498 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4499              boolean added = false;
4500              for (Entry<K,V> e : c) {
4501                  if (add(e))
# Line 4876 | Line 4503 | public class ConcurrentHashMapV8<K,V>
4503              }
4504              return added;
4505          }
4506 <        public boolean equals(Object o) {
4506 >
4507 >        public final int hashCode() {
4508 >            int h = 0;
4509 >            Node<K,V>[] t;
4510 >            if ((t = map.table) != null) {
4511 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4512 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4513 >                    h += p.hashCode();
4514 >                }
4515 >            }
4516 >            return h;
4517 >        }
4518 >
4519 >        public final boolean equals(Object o) {
4520              Set<?> c;
4521              return ((o instanceof Set) &&
4522                      ((c = (Set<?>)o) == this ||
4523                       (containsAll(c) && c.containsAll(this))));
4524          }
4885    }
4886
4887    // ---------------------------------------------------------------------
4888
4889    /**
4890     * Predefined tasks for performing bulk parallel operations on
4891     * ConcurrentHashMapV8s. These tasks follow the forms and rules used
4892     * for bulk operations. Each method has the same name, but returns
4893     * a task rather than invoking it. These methods may be useful in
4894     * custom applications such as submitting a task without waiting
4895     * for completion, using a custom pool, or combining with other
4896     * tasks.
4897     */
4898    public static class ForkJoinTasks {
4899        private ForkJoinTasks() {}
4525  
4526 <        /**
4527 <         * Returns a task that when invoked, performs the given
4528 <         * action for each (key, value)
4529 <         *
4530 <         * @param map the map
4531 <         * @param action the action
4907 <         * @return the task
4908 <         */
4909 <        public static <K,V> ForkJoinTask<Void> forEach
4910 <            (ConcurrentHashMapV8<K,V> map,
4911 <             BiAction<K,V> action) {
4912 <            if (action == null) throw new NullPointerException();
4913 <            return new ForEachMappingTask<K,V>(map, null, -1, action);
4914 <        }
4915 <
4916 <        /**
4917 <         * Returns a task that when invoked, performs the given
4918 <         * action for each non-null transformation of each (key, value)
4919 <         *
4920 <         * @param map the map
4921 <         * @param transformer a function returning the transformation
4922 <         * for an element, or null if there is no transformation (in
4923 <         * which case the action is not applied)
4924 <         * @param action the action
4925 <         * @return the task
4926 <         */
4927 <        public static <K,V,U> ForkJoinTask<Void> forEach
4928 <            (ConcurrentHashMapV8<K,V> map,
4929 <             BiFun<? super K, ? super V, ? extends U> transformer,
4930 <             Action<U> action) {
4931 <            if (transformer == null || action == null)
4932 <                throw new NullPointerException();
4933 <            return new ForEachTransformedMappingTask<K,V,U>
4934 <                (map, null, -1, transformer, action);
4526 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> spliterator() {
4527 >            Node<K,V>[] t;
4528 >            ConcurrentHashMapV8<K,V> m = map;
4529 >            long n = m.sumCount();
4530 >            int f = (t = m.table) == null ? 0 : t.length;
4531 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4532          }
4533  
4534 <        /**
4938 <         * Returns a task that when invoked, returns a non-null result
4939 <         * from applying the given search function on each (key,
4940 <         * value), or null if none. Upon success, further element
4941 <         * processing is suppressed and the results of any other
4942 <         * parallel invocations of the search function are ignored.
4943 <         *
4944 <         * @param map the map
4945 <         * @param searchFunction a function returning a non-null
4946 <         * result on success, else null
4947 <         * @return the task
4948 <         */
4949 <        public static <K,V,U> ForkJoinTask<U> search
4950 <            (ConcurrentHashMapV8<K,V> map,
4951 <             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4952 <            if (searchFunction == null) throw new NullPointerException();
4953 <            return new SearchMappingsTask<K,V,U>
4954 <                (map, null, -1, searchFunction,
4955 <                 new AtomicReference<U>());
4956 <        }
4957 <
4958 <        /**
4959 <         * Returns a task that when invoked, returns the result of
4960 <         * accumulating the given transformation of all (key, value) pairs
4961 <         * using the given reducer to combine values, or null if none.
4962 <         *
4963 <         * @param map the map
4964 <         * @param transformer a function returning the transformation
4965 <         * for an element, or null if there is no transformation (in
4966 <         * which case it is not combined)
4967 <         * @param reducer a commutative associative combining function
4968 <         * @return the task
4969 <         */
4970 <        public static <K,V,U> ForkJoinTask<U> reduce
4971 <            (ConcurrentHashMapV8<K,V> map,
4972 <             BiFun<? super K, ? super V, ? extends U> transformer,
4973 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4974 <            if (transformer == null || reducer == null)
4975 <                throw new NullPointerException();
4976 <            return new MapReduceMappingsTask<K,V,U>
4977 <                (map, null, -1, null, transformer, reducer);
4978 <        }
4979 <
4980 <        /**
4981 <         * Returns a task that when invoked, returns the result of
4982 <         * accumulating the given transformation of all (key, value) pairs
4983 <         * using the given reducer to combine values, and the given
4984 <         * basis as an identity value.
4985 <         *
4986 <         * @param map the map
4987 <         * @param transformer a function returning the transformation
4988 <         * for an element
4989 <         * @param basis the identity (initial default value) for the reduction
4990 <         * @param reducer a commutative associative combining function
4991 <         * @return the task
4992 <         */
4993 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4994 <            (ConcurrentHashMapV8<K,V> map,
4995 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
4996 <             double basis,
4997 <             DoubleByDoubleToDouble reducer) {
4998 <            if (transformer == null || reducer == null)
4999 <                throw new NullPointerException();
5000 <            return new MapReduceMappingsToDoubleTask<K,V>
5001 <                (map, null, -1, null, transformer, basis, reducer);
5002 <        }
5003 <
5004 <        /**
5005 <         * Returns a task that when invoked, returns the result of
5006 <         * accumulating the given transformation of all (key, value) pairs
5007 <         * using the given reducer to combine values, and the given
5008 <         * basis as an identity value.
5009 <         *
5010 <         * @param map the map
5011 <         * @param transformer a function returning the transformation
5012 <         * for an element
5013 <         * @param basis the identity (initial default value) for the reduction
5014 <         * @param reducer a commutative associative combining function
5015 <         * @return the task
5016 <         */
5017 <        public static <K,V> ForkJoinTask<Long> reduceToLong
5018 <            (ConcurrentHashMapV8<K,V> map,
5019 <             ObjectByObjectToLong<? super K, ? super V> transformer,
5020 <             long basis,
5021 <             LongByLongToLong reducer) {
5022 <            if (transformer == null || reducer == null)
5023 <                throw new NullPointerException();
5024 <            return new MapReduceMappingsToLongTask<K,V>
5025 <                (map, null, -1, null, transformer, basis, reducer);
5026 <        }
5027 <
5028 <        /**
5029 <         * Returns a task that when invoked, returns the result of
5030 <         * accumulating the given transformation of all (key, value) pairs
5031 <         * using the given reducer to combine values, and the given
5032 <         * basis as an identity value.
5033 <         *
5034 <         * @param transformer a function returning the transformation
5035 <         * for an element
5036 <         * @param basis the identity (initial default value) for the reduction
5037 <         * @param reducer a commutative associative combining function
5038 <         * @return the task
5039 <         */
5040 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
5041 <            (ConcurrentHashMapV8<K,V> map,
5042 <             ObjectByObjectToInt<? super K, ? super V> transformer,
5043 <             int basis,
5044 <             IntByIntToInt reducer) {
5045 <            if (transformer == null || reducer == null)
5046 <                throw new NullPointerException();
5047 <            return new MapReduceMappingsToIntTask<K,V>
5048 <                (map, null, -1, null, transformer, basis, reducer);
5049 <        }
5050 <
5051 <        /**
5052 <         * Returns a task that when invoked, performs the given action
5053 <         * for each key.
5054 <         *
5055 <         * @param map the map
5056 <         * @param action the action
5057 <         * @return the task
5058 <         */
5059 <        public static <K,V> ForkJoinTask<Void> forEachKey
5060 <            (ConcurrentHashMapV8<K,V> map,
5061 <             Action<K> action) {
4534 >        public void forEach(Action<? super Map.Entry<K,V>> action) {
4535              if (action == null) throw new NullPointerException();
4536 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
4537 <        }
4538 <
4539 <        /**
4540 <         * Returns a task that when invoked, performs the given action
4541 <         * for each non-null transformation of each key.
5069 <         *
5070 <         * @param map the map
5071 <         * @param transformer a function returning the transformation
5072 <         * for an element, or null if there is no transformation (in
5073 <         * which case the action is not applied)
5074 <         * @param action the action
5075 <         * @return the task
5076 <         */
5077 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
5078 <            (ConcurrentHashMapV8<K,V> map,
5079 <             Fun<? super K, ? extends U> transformer,
5080 <             Action<U> action) {
5081 <            if (transformer == null || action == null)
5082 <                throw new NullPointerException();
5083 <            return new ForEachTransformedKeyTask<K,V,U>
5084 <                (map, null, -1, transformer, action);
5085 <        }
5086 <
5087 <        /**
5088 <         * Returns a task that when invoked, returns a non-null result
5089 <         * from applying the given search function on each key, or
5090 <         * null if none.  Upon success, further element processing is
5091 <         * suppressed and the results of any other parallel
5092 <         * invocations of the search function are ignored.
5093 <         *
5094 <         * @param map the map
5095 <         * @param searchFunction a function returning a non-null
5096 <         * result on success, else null
5097 <         * @return the task
5098 <         */
5099 <        public static <K,V,U> ForkJoinTask<U> searchKeys
5100 <            (ConcurrentHashMapV8<K,V> map,
5101 <             Fun<? super K, ? extends U> searchFunction) {
5102 <            if (searchFunction == null) throw new NullPointerException();
5103 <            return new SearchKeysTask<K,V,U>
5104 <                (map, null, -1, searchFunction,
5105 <                 new AtomicReference<U>());
5106 <        }
5107 <
5108 <        /**
5109 <         * Returns a task that when invoked, returns the result of
5110 <         * accumulating all keys using the given reducer to combine
5111 <         * values, or null if none.
5112 <         *
5113 <         * @param map the map
5114 <         * @param reducer a commutative associative combining function
5115 <         * @return the task
5116 <         */
5117 <        public static <K,V> ForkJoinTask<K> reduceKeys
5118 <            (ConcurrentHashMapV8<K,V> map,
5119 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5120 <            if (reducer == null) throw new NullPointerException();
5121 <            return new ReduceKeysTask<K,V>
5122 <                (map, null, -1, null, reducer);
5123 <        }
5124 <
5125 <        /**
5126 <         * Returns a task that when invoked, returns the result of
5127 <         * accumulating the given transformation of all keys using the given
5128 <         * reducer to combine values, or null if none.
5129 <         *
5130 <         * @param map the map
5131 <         * @param transformer a function returning the transformation
5132 <         * for an element, or null if there is no transformation (in
5133 <         * which case it is not combined)
5134 <         * @param reducer a commutative associative combining function
5135 <         * @return the task
5136 <         */
5137 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
5138 <            (ConcurrentHashMapV8<K,V> map,
5139 <             Fun<? super K, ? extends U> transformer,
5140 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5141 <            if (transformer == null || reducer == null)
5142 <                throw new NullPointerException();
5143 <            return new MapReduceKeysTask<K,V,U>
5144 <                (map, null, -1, null, transformer, reducer);
5145 <        }
5146 <
5147 <        /**
5148 <         * Returns a task that when invoked, returns the result of
5149 <         * accumulating the given transformation of all keys using the given
5150 <         * reducer to combine values, and the given basis as an
5151 <         * identity value.
5152 <         *
5153 <         * @param map the map
5154 <         * @param transformer a function returning the transformation
5155 <         * for an element
5156 <         * @param basis the identity (initial default value) for the reduction
5157 <         * @param reducer a commutative associative combining function
5158 <         * @return the task
5159 <         */
5160 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5161 <            (ConcurrentHashMapV8<K,V> map,
5162 <             ObjectToDouble<? super K> transformer,
5163 <             double basis,
5164 <             DoubleByDoubleToDouble reducer) {
5165 <            if (transformer == null || reducer == null)
5166 <                throw new NullPointerException();
5167 <            return new MapReduceKeysToDoubleTask<K,V>
5168 <                (map, null, -1, null, transformer, basis, reducer);
5169 <        }
5170 <
5171 <        /**
5172 <         * Returns a task that when invoked, returns the result of
5173 <         * accumulating the given transformation of all keys using the given
5174 <         * reducer to combine values, and the given basis as an
5175 <         * identity value.
5176 <         *
5177 <         * @param map the map
5178 <         * @param transformer a function returning the transformation
5179 <         * for an element
5180 <         * @param basis the identity (initial default value) for the reduction
5181 <         * @param reducer a commutative associative combining function
5182 <         * @return the task
5183 <         */
5184 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5185 <            (ConcurrentHashMapV8<K,V> map,
5186 <             ObjectToLong<? super K> transformer,
5187 <             long basis,
5188 <             LongByLongToLong reducer) {
5189 <            if (transformer == null || reducer == null)
5190 <                throw new NullPointerException();
5191 <            return new MapReduceKeysToLongTask<K,V>
5192 <                (map, null, -1, null, transformer, basis, reducer);
5193 <        }
5194 <
5195 <        /**
5196 <         * Returns a task that when invoked, returns the result of
5197 <         * accumulating the given transformation of all keys using the given
5198 <         * reducer to combine values, and the given basis as an
5199 <         * identity value.
5200 <         *
5201 <         * @param map the map
5202 <         * @param transformer a function returning the transformation
5203 <         * for an element
5204 <         * @param basis the identity (initial default value) for the reduction
5205 <         * @param reducer a commutative associative combining function
5206 <         * @return the task
5207 <         */
5208 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5209 <            (ConcurrentHashMapV8<K,V> map,
5210 <             ObjectToInt<? super K> transformer,
5211 <             int basis,
5212 <             IntByIntToInt reducer) {
5213 <            if (transformer == null || reducer == null)
5214 <                throw new NullPointerException();
5215 <            return new MapReduceKeysToIntTask<K,V>
5216 <                (map, null, -1, null, transformer, basis, reducer);
5217 <        }
5218 <
5219 <        /**
5220 <         * Returns a task that when invoked, performs the given action
5221 <         * for each value.
5222 <         *
5223 <         * @param map the map
5224 <         * @param action the action
5225 <         */
5226 <        public static <K,V> ForkJoinTask<Void> forEachValue
5227 <            (ConcurrentHashMapV8<K,V> map,
5228 <             Action<V> action) {
5229 <            if (action == null) throw new NullPointerException();
5230 <            return new ForEachValueTask<K,V>(map, null, -1, action);
5231 <        }
5232 <
5233 <        /**
5234 <         * Returns a task that when invoked, performs the given action
5235 <         * for each non-null transformation of each value.
5236 <         *
5237 <         * @param map the map
5238 <         * @param transformer a function returning the transformation
5239 <         * for an element, or null if there is no transformation (in
5240 <         * which case the action is not applied)
5241 <         * @param action the action
5242 <         */
5243 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
5244 <            (ConcurrentHashMapV8<K,V> map,
5245 <             Fun<? super V, ? extends U> transformer,
5246 <             Action<U> action) {
5247 <            if (transformer == null || action == null)
5248 <                throw new NullPointerException();
5249 <            return new ForEachTransformedValueTask<K,V,U>
5250 <                (map, null, -1, transformer, action);
5251 <        }
5252 <
5253 <        /**
5254 <         * Returns a task that when invoked, returns a non-null result
5255 <         * from applying the given search function on each value, or
5256 <         * null if none.  Upon success, further element processing is
5257 <         * suppressed and the results of any other parallel
5258 <         * invocations of the search function are ignored.
5259 <         *
5260 <         * @param map the map
5261 <         * @param searchFunction a function returning a non-null
5262 <         * result on success, else null
5263 <         * @return the task
5264 <         */
5265 <        public static <K,V,U> ForkJoinTask<U> searchValues
5266 <            (ConcurrentHashMapV8<K,V> map,
5267 <             Fun<? super V, ? extends U> searchFunction) {
5268 <            if (searchFunction == null) throw new NullPointerException();
5269 <            return new SearchValuesTask<K,V,U>
5270 <                (map, null, -1, searchFunction,
5271 <                 new AtomicReference<U>());
5272 <        }
5273 <
5274 <        /**
5275 <         * Returns a task that when invoked, returns the result of
5276 <         * accumulating all values using the given reducer to combine
5277 <         * values, or null if none.
5278 <         *
5279 <         * @param map the map
5280 <         * @param reducer a commutative associative combining function
5281 <         * @return the task
5282 <         */
5283 <        public static <K,V> ForkJoinTask<V> reduceValues
5284 <            (ConcurrentHashMapV8<K,V> map,
5285 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5286 <            if (reducer == null) throw new NullPointerException();
5287 <            return new ReduceValuesTask<K,V>
5288 <                (map, null, -1, null, reducer);
5289 <        }
5290 <
5291 <        /**
5292 <         * Returns a task that when invoked, returns the result of
5293 <         * accumulating the given transformation of all values using the
5294 <         * given reducer to combine values, or null if none.
5295 <         *
5296 <         * @param map the map
5297 <         * @param transformer a function returning the transformation
5298 <         * for an element, or null if there is no transformation (in
5299 <         * which case it is not combined)
5300 <         * @param reducer a commutative associative combining function
5301 <         * @return the task
5302 <         */
5303 <        public static <K,V,U> ForkJoinTask<U> reduceValues
5304 <            (ConcurrentHashMapV8<K,V> map,
5305 <             Fun<? super V, ? extends U> transformer,
5306 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5307 <            if (transformer == null || reducer == null)
5308 <                throw new NullPointerException();
5309 <            return new MapReduceValuesTask<K,V,U>
5310 <                (map, null, -1, null, transformer, reducer);
5311 <        }
5312 <
5313 <        /**
5314 <         * Returns a task that when invoked, returns the result of
5315 <         * accumulating the given transformation of all values using the
5316 <         * given reducer to combine values, and the given basis as an
5317 <         * identity value.
5318 <         *
5319 <         * @param map the map
5320 <         * @param transformer a function returning the transformation
5321 <         * for an element
5322 <         * @param basis the identity (initial default value) for the reduction
5323 <         * @param reducer a commutative associative combining function
5324 <         * @return the task
5325 <         */
5326 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5327 <            (ConcurrentHashMapV8<K,V> map,
5328 <             ObjectToDouble<? super V> transformer,
5329 <             double basis,
5330 <             DoubleByDoubleToDouble reducer) {
5331 <            if (transformer == null || reducer == null)
5332 <                throw new NullPointerException();
5333 <            return new MapReduceValuesToDoubleTask<K,V>
5334 <                (map, null, -1, null, transformer, basis, reducer);
5335 <        }
5336 <
5337 <        /**
5338 <         * Returns a task that when invoked, returns the result of
5339 <         * accumulating the given transformation of all values using the
5340 <         * given reducer to combine values, and the given basis as an
5341 <         * identity value.
5342 <         *
5343 <         * @param map the map
5344 <         * @param transformer a function returning the transformation
5345 <         * for an element
5346 <         * @param basis the identity (initial default value) for the reduction
5347 <         * @param reducer a commutative associative combining function
5348 <         * @return the task
5349 <         */
5350 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5351 <            (ConcurrentHashMapV8<K,V> map,
5352 <             ObjectToLong<? super V> transformer,
5353 <             long basis,
5354 <             LongByLongToLong reducer) {
5355 <            if (transformer == null || reducer == null)
5356 <                throw new NullPointerException();
5357 <            return new MapReduceValuesToLongTask<K,V>
5358 <                (map, null, -1, null, transformer, basis, reducer);
5359 <        }
5360 <
5361 <        /**
5362 <         * Returns a task that when invoked, returns the result of
5363 <         * accumulating the given transformation of all values using the
5364 <         * given reducer to combine values, and the given basis as an
5365 <         * identity value.
5366 <         *
5367 <         * @param map the map
5368 <         * @param transformer a function returning the transformation
5369 <         * for an element
5370 <         * @param basis the identity (initial default value) for the reduction
5371 <         * @param reducer a commutative associative combining function
5372 <         * @return the task
5373 <         */
5374 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5375 <            (ConcurrentHashMapV8<K,V> map,
5376 <             ObjectToInt<? super V> transformer,
5377 <             int basis,
5378 <             IntByIntToInt reducer) {
5379 <            if (transformer == null || reducer == null)
5380 <                throw new NullPointerException();
5381 <            return new MapReduceValuesToIntTask<K,V>
5382 <                (map, null, -1, null, transformer, basis, reducer);
5383 <        }
5384 <
5385 <        /**
5386 <         * Returns a task that when invoked, perform the given action
5387 <         * for each entry.
5388 <         *
5389 <         * @param map the map
5390 <         * @param action the action
5391 <         */
5392 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5393 <            (ConcurrentHashMapV8<K,V> map,
5394 <             Action<Map.Entry<K,V>> action) {
5395 <            if (action == null) throw new NullPointerException();
5396 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
5397 <        }
5398 <
5399 <        /**
5400 <         * Returns a task that when invoked, perform the given action
5401 <         * for each non-null transformation of each entry.
5402 <         *
5403 <         * @param map the map
5404 <         * @param transformer a function returning the transformation
5405 <         * for an element, or null if there is no transformation (in
5406 <         * which case the action is not applied)
5407 <         * @param action the action
5408 <         */
5409 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5410 <            (ConcurrentHashMapV8<K,V> map,
5411 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5412 <             Action<U> action) {
5413 <            if (transformer == null || action == null)
5414 <                throw new NullPointerException();
5415 <            return new ForEachTransformedEntryTask<K,V,U>
5416 <                (map, null, -1, transformer, action);
5417 <        }
5418 <
5419 <        /**
5420 <         * Returns a task that when invoked, returns a non-null result
5421 <         * from applying the given search function on each entry, or
5422 <         * null if none.  Upon success, further element processing is
5423 <         * suppressed and the results of any other parallel
5424 <         * invocations of the search function are ignored.
5425 <         *
5426 <         * @param map the map
5427 <         * @param searchFunction a function returning a non-null
5428 <         * result on success, else null
5429 <         * @return the task
5430 <         */
5431 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5432 <            (ConcurrentHashMapV8<K,V> map,
5433 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5434 <            if (searchFunction == null) throw new NullPointerException();
5435 <            return new SearchEntriesTask<K,V,U>
5436 <                (map, null, -1, searchFunction,
5437 <                 new AtomicReference<U>());
5438 <        }
5439 <
5440 <        /**
5441 <         * Returns a task that when invoked, returns the result of
5442 <         * accumulating all entries using the given reducer to combine
5443 <         * values, or null if none.
5444 <         *
5445 <         * @param map the map
5446 <         * @param reducer a commutative associative combining function
5447 <         * @return the task
5448 <         */
5449 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5450 <            (ConcurrentHashMapV8<K,V> map,
5451 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5452 <            if (reducer == null) throw new NullPointerException();
5453 <            return new ReduceEntriesTask<K,V>
5454 <                (map, null, -1, null, reducer);
4536 >            Node<K,V>[] t;
4537 >            if ((t = map.table) != null) {
4538 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4539 >                for (Node<K,V> p; (p = it.advance()) != null; )
4540 >                    action.apply(new MapEntry<K,V>(p.key, p.val, map));
4541 >            }
4542          }
4543  
4544 <        /**
5458 <         * Returns a task that when invoked, returns the result of
5459 <         * accumulating the given transformation of all entries using the
5460 <         * given reducer to combine values, or null if none.
5461 <         *
5462 <         * @param map the map
5463 <         * @param transformer a function returning the transformation
5464 <         * for an element, or null if there is no transformation (in
5465 <         * which case it is not combined)
5466 <         * @param reducer a commutative associative combining function
5467 <         * @return the task
5468 <         */
5469 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5470 <            (ConcurrentHashMapV8<K,V> map,
5471 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5472 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5473 <            if (transformer == null || reducer == null)
5474 <                throw new NullPointerException();
5475 <            return new MapReduceEntriesTask<K,V,U>
5476 <                (map, null, -1, null, transformer, reducer);
5477 <        }
4544 >    }
4545  
4546 <        /**
5480 <         * Returns a task that when invoked, returns the result of
5481 <         * accumulating the given transformation of all entries using the
5482 <         * given reducer to combine values, and the given basis as an
5483 <         * identity value.
5484 <         *
5485 <         * @param map the map
5486 <         * @param transformer a function returning the transformation
5487 <         * for an element
5488 <         * @param basis the identity (initial default value) for the reduction
5489 <         * @param reducer a commutative associative combining function
5490 <         * @return the task
5491 <         */
5492 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5493 <            (ConcurrentHashMapV8<K,V> map,
5494 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5495 <             double basis,
5496 <             DoubleByDoubleToDouble reducer) {
5497 <            if (transformer == null || reducer == null)
5498 <                throw new NullPointerException();
5499 <            return new MapReduceEntriesToDoubleTask<K,V>
5500 <                (map, null, -1, null, transformer, basis, reducer);
5501 <        }
4546 >    // -------------------------------------------------------
4547  
4548 <        /**
4549 <         * Returns a task that when invoked, returns the result of
4550 <         * accumulating the given transformation of all entries using the
4551 <         * given reducer to combine values, and the given basis as an
4552 <         * identity value.
4553 <         *
4554 <         * @param map the map
4555 <         * @param transformer a function returning the transformation
4556 <         * for an element
4557 <         * @param basis the identity (initial default value) for the reduction
4558 <         * @param reducer a commutative associative combining function
4559 <         * @return the task
4560 <         */
4561 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4562 <            (ConcurrentHashMapV8<K,V> map,
4563 <             ObjectToLong<Map.Entry<K,V>> transformer,
4564 <             long basis,
4565 <             LongByLongToLong reducer) {
4566 <            if (transformer == null || reducer == null)
4567 <                throw new NullPointerException();
4568 <            return new MapReduceEntriesToLongTask<K,V>
4569 <                (map, null, -1, null, transformer, basis, reducer);
4548 >    /**
4549 >     * Base class for bulk tasks. Repeats some fields and code from
4550 >     * class Traverser, because we need to subclass CountedCompleter.
4551 >     */
4552 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4553 >        Node<K,V>[] tab;        // same as Traverser
4554 >        Node<K,V> next;
4555 >        int index;
4556 >        int baseIndex;
4557 >        int baseLimit;
4558 >        final int baseSize;
4559 >        int batch;              // split control
4560 >
4561 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4562 >            super(par);
4563 >            this.batch = b;
4564 >            this.index = this.baseIndex = i;
4565 >            if ((this.tab = t) == null)
4566 >                this.baseSize = this.baseLimit = 0;
4567 >            else if (par == null)
4568 >                this.baseSize = this.baseLimit = t.length;
4569 >            else {
4570 >                this.baseLimit = f;
4571 >                this.baseSize = par.baseSize;
4572 >            }
4573          }
4574  
4575          /**
4576 <         * Returns a task that when invoked, returns the result of
5529 <         * accumulating the given transformation of all entries using the
5530 <         * given reducer to combine values, and the given basis as an
5531 <         * identity value.
5532 <         *
5533 <         * @param map the map
5534 <         * @param transformer a function returning the transformation
5535 <         * for an element
5536 <         * @param basis the identity (initial default value) for the reduction
5537 <         * @param reducer a commutative associative combining function
5538 <         * @return the task
4576 >         * Same as Traverser version
4577           */
4578 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4579 <            (ConcurrentHashMapV8<K,V> map,
4580 <             ObjectToInt<Map.Entry<K,V>> transformer,
4581 <             int basis,
4582 <             IntByIntToInt reducer) {
4583 <            if (transformer == null || reducer == null)
4584 <                throw new NullPointerException();
4585 <            return new MapReduceEntriesToIntTask<K,V>
4586 <                (map, null, -1, null, transformer, basis, reducer);
4578 >        final Node<K,V> advance() {
4579 >            Node<K,V> e;
4580 >            if ((e = next) != null)
4581 >                e = e.next;
4582 >            for (;;) {
4583 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4584 >                if (e != null)
4585 >                    return next = e;
4586 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4587 >                    (n = t.length) <= (i = index) || i < 0)
4588 >                    return next = null;
4589 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4590 >                    if (e instanceof ForwardingNode) {
4591 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4592 >                        e = null;
4593 >                        continue;
4594 >                    }
4595 >                    else if (e instanceof TreeBin)
4596 >                        e = ((TreeBin<K,V>)e).first;
4597 >                    else
4598 >                        e = null;
4599 >                }
4600 >                if ((index += baseSize) >= n)
4601 >                    index = ++baseIndex;    // visit upper slots if present
4602 >            }
4603          }
4604      }
4605  
5552    // -------------------------------------------------------
5553
4606      /*
4607       * Task classes. Coded in a regular but ugly format/style to
4608       * simplify checks that each variant differs in the right way from
# Line 5558 | Line 4610 | public class ConcurrentHashMapV8<K,V>
4610       * that we've already null-checked task arguments, so we force
4611       * simplest hoisted bypass to help avoid convoluted traps.
4612       */
4613 <
4614 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4615 <        extends Traverser<K,V,Void> {
4616 <        final Action<K> action;
4613 >    @SuppressWarnings("serial")
4614 >    static final class ForEachKeyTask<K,V>
4615 >        extends BulkTask<K,V,Void> {
4616 >        final Action<? super K> action;
4617          ForEachKeyTask
4618 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4619 <             Action<K> action) {
4620 <            super(m, p, b);
4618 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4619 >             Action<? super K> action) {
4620 >            super(p, b, i, f, t);
4621              this.action = action;
4622          }
4623 <        @SuppressWarnings("unchecked") public final void compute() {
4624 <            final Action<K> action;
4623 >        public final void compute() {
4624 >            final Action<? super K> action;
4625              if ((action = this.action) != null) {
4626 <                for (int b; (b = preSplit()) > 0;)
4627 <                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
4628 <                while (advance() != null)
4629 <                    action.apply((K)nextKey);
4626 >                for (int i = baseIndex, f, h; batch > 0 &&
4627 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4628 >                    addToPendingCount(1);
4629 >                    new ForEachKeyTask<K,V>
4630 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4631 >                         action).fork();
4632 >                }
4633 >                for (Node<K,V> p; (p = advance()) != null;)
4634 >                    action.apply(p.key);
4635                  propagateCompletion();
4636              }
4637          }
4638      }
4639  
4640 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4641 <        extends Traverser<K,V,Void> {
4642 <        final Action<V> action;
4640 >    @SuppressWarnings("serial")
4641 >    static final class ForEachValueTask<K,V>
4642 >        extends BulkTask<K,V,Void> {
4643 >        final Action<? super V> action;
4644          ForEachValueTask
4645 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4646 <             Action<V> action) {
4647 <            super(m, p, b);
4645 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4646 >             Action<? super V> action) {
4647 >            super(p, b, i, f, t);
4648              this.action = action;
4649          }
4650 <        @SuppressWarnings("unchecked") public final void compute() {
4651 <            final Action<V> action;
4650 >        public final void compute() {
4651 >            final Action<? super V> action;
4652              if ((action = this.action) != null) {
4653 <                for (int b; (b = preSplit()) > 0;)
4654 <                    new ForEachValueTask<K,V>(map, this, b, action).fork();
4655 <                V v;
4656 <                while ((v = advance()) != null)
4657 <                    action.apply(v);
4653 >                for (int i = baseIndex, f, h; batch > 0 &&
4654 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4655 >                    addToPendingCount(1);
4656 >                    new ForEachValueTask<K,V>
4657 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4658 >                         action).fork();
4659 >                }
4660 >                for (Node<K,V> p; (p = advance()) != null;)
4661 >                    action.apply(p.val);
4662                  propagateCompletion();
4663              }
4664          }
4665      }
4666  
4667 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4668 <        extends Traverser<K,V,Void> {
4669 <        final Action<Entry<K,V>> action;
4667 >    @SuppressWarnings("serial")
4668 >    static final class ForEachEntryTask<K,V>
4669 >        extends BulkTask<K,V,Void> {
4670 >        final Action<? super Entry<K,V>> action;
4671          ForEachEntryTask
4672 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4673 <             Action<Entry<K,V>> action) {
4674 <            super(m, p, b);
4672 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4673 >             Action<? super Entry<K,V>> action) {
4674 >            super(p, b, i, f, t);
4675              this.action = action;
4676          }
4677 <        @SuppressWarnings("unchecked") public final void compute() {
4678 <            final Action<Entry<K,V>> action;
4677 >        public final void compute() {
4678 >            final Action<? super Entry<K,V>> action;
4679              if ((action = this.action) != null) {
4680 <                for (int b; (b = preSplit()) > 0;)
4681 <                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
4682 <                V v;
4683 <                while ((v = advance()) != null)
4684 <                    action.apply(entryFor((K)nextKey, v));
4680 >                for (int i = baseIndex, f, h; batch > 0 &&
4681 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4682 >                    addToPendingCount(1);
4683 >                    new ForEachEntryTask<K,V>
4684 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4685 >                         action).fork();
4686 >                }
4687 >                for (Node<K,V> p; (p = advance()) != null; )
4688 >                    action.apply(p);
4689                  propagateCompletion();
4690              }
4691          }
4692      }
4693  
4694 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4695 <        extends Traverser<K,V,Void> {
4696 <        final BiAction<K,V> action;
4694 >    @SuppressWarnings("serial")
4695 >    static final class ForEachMappingTask<K,V>
4696 >        extends BulkTask<K,V,Void> {
4697 >        final BiAction<? super K, ? super V> action;
4698          ForEachMappingTask
4699 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4700 <             BiAction<K,V> action) {
4701 <            super(m, p, b);
4699 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4700 >             BiAction<? super K,? super V> action) {
4701 >            super(p, b, i, f, t);
4702              this.action = action;
4703          }
4704 <        @SuppressWarnings("unchecked") public final void compute() {
4705 <            final BiAction<K,V> action;
4704 >        public final void compute() {
4705 >            final BiAction<? super K, ? super V> action;
4706              if ((action = this.action) != null) {
4707 <                for (int b; (b = preSplit()) > 0;)
4708 <                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
4709 <                V v;
4710 <                while ((v = advance()) != null)
4711 <                    action.apply((K)nextKey, v);
4707 >                for (int i = baseIndex, f, h; batch > 0 &&
4708 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4709 >                    addToPendingCount(1);
4710 >                    new ForEachMappingTask<K,V>
4711 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4712 >                         action).fork();
4713 >                }
4714 >                for (Node<K,V> p; (p = advance()) != null; )
4715 >                    action.apply(p.key, p.val);
4716                  propagateCompletion();
4717              }
4718          }
4719      }
4720  
4721 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4722 <        extends Traverser<K,V,Void> {
4721 >    @SuppressWarnings("serial")
4722 >    static final class ForEachTransformedKeyTask<K,V,U>
4723 >        extends BulkTask<K,V,Void> {
4724          final Fun<? super K, ? extends U> transformer;
4725 <        final Action<U> action;
4725 >        final Action<? super U> action;
4726          ForEachTransformedKeyTask
4727 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4728 <             Fun<? super K, ? extends U> transformer, Action<U> action) {
4729 <            super(m, p, b);
4727 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4728 >             Fun<? super K, ? extends U> transformer, Action<? super U> action) {
4729 >            super(p, b, i, f, t);
4730              this.transformer = transformer; this.action = action;
4731          }
4732 <        @SuppressWarnings("unchecked") public final void compute() {
4732 >        public final void compute() {
4733              final Fun<? super K, ? extends U> transformer;
4734 <            final Action<U> action;
4734 >            final Action<? super U> action;
4735              if ((transformer = this.transformer) != null &&
4736                  (action = this.action) != null) {
4737 <                for (int b; (b = preSplit()) > 0;)
4737 >                for (int i = baseIndex, f, h; batch > 0 &&
4738 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4739 >                    addToPendingCount(1);
4740                      new ForEachTransformedKeyTask<K,V,U>
4741 <                        (map, this, b, transformer, action).fork();
4742 <                U u;
4743 <                while (advance() != null) {
4744 <                    if ((u = transformer.apply((K)nextKey)) != null)
4741 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4742 >                         transformer, action).fork();
4743 >                }
4744 >                for (Node<K,V> p; (p = advance()) != null; ) {
4745 >                    U u;
4746 >                    if ((u = transformer.apply(p.key)) != null)
4747                          action.apply(u);
4748                  }
4749                  propagateCompletion();
# Line 5674 | Line 4751 | public class ConcurrentHashMapV8<K,V>
4751          }
4752      }
4753  
4754 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
4755 <        extends Traverser<K,V,Void> {
4754 >    @SuppressWarnings("serial")
4755 >    static final class ForEachTransformedValueTask<K,V,U>
4756 >        extends BulkTask<K,V,Void> {
4757          final Fun<? super V, ? extends U> transformer;
4758 <        final Action<U> action;
4758 >        final Action<? super U> action;
4759          ForEachTransformedValueTask
4760 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4761 <             Fun<? super V, ? extends U> transformer, Action<U> action) {
4762 <            super(m, p, b);
4760 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4761 >             Fun<? super V, ? extends U> transformer, Action<? super U> action) {
4762 >            super(p, b, i, f, t);
4763              this.transformer = transformer; this.action = action;
4764          }
4765 <        @SuppressWarnings("unchecked") public final void compute() {
4765 >        public final void compute() {
4766              final Fun<? super V, ? extends U> transformer;
4767 <            final Action<U> action;
4767 >            final Action<? super U> action;
4768              if ((transformer = this.transformer) != null &&
4769                  (action = this.action) != null) {
4770 <                for (int b; (b = preSplit()) > 0;)
4770 >                for (int i = baseIndex, f, h; batch > 0 &&
4771 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4772 >                    addToPendingCount(1);
4773                      new ForEachTransformedValueTask<K,V,U>
4774 <                        (map, this, b, transformer, action).fork();
4775 <                V v; U u;
4776 <                while ((v = advance()) != null) {
4777 <                    if ((u = transformer.apply(v)) != null)
4774 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4775 >                         transformer, action).fork();
4776 >                }
4777 >                for (Node<K,V> p; (p = advance()) != null; ) {
4778 >                    U u;
4779 >                    if ((u = transformer.apply(p.val)) != null)
4780                          action.apply(u);
4781                  }
4782                  propagateCompletion();
# Line 5702 | Line 4784 | public class ConcurrentHashMapV8<K,V>
4784          }
4785      }
4786  
4787 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
4788 <        extends Traverser<K,V,Void> {
4787 >    @SuppressWarnings("serial")
4788 >    static final class ForEachTransformedEntryTask<K,V,U>
4789 >        extends BulkTask<K,V,Void> {
4790          final Fun<Map.Entry<K,V>, ? extends U> transformer;
4791 <        final Action<U> action;
4791 >        final Action<? super U> action;
4792          ForEachTransformedEntryTask
4793 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4794 <             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<U> action) {
4795 <            super(m, p, b);
4793 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4794 >             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<? super U> action) {
4795 >            super(p, b, i, f, t);
4796              this.transformer = transformer; this.action = action;
4797          }
4798 <        @SuppressWarnings("unchecked") public final void compute() {
4798 >        public final void compute() {
4799              final Fun<Map.Entry<K,V>, ? extends U> transformer;
4800 <            final Action<U> action;
4800 >            final Action<? super U> action;
4801              if ((transformer = this.transformer) != null &&
4802                  (action = this.action) != null) {
4803 <                for (int b; (b = preSplit()) > 0;)
4803 >                for (int i = baseIndex, f, h; batch > 0 &&
4804 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4805 >                    addToPendingCount(1);
4806                      new ForEachTransformedEntryTask<K,V,U>
4807 <                        (map, this, b, transformer, action).fork();
4808 <                V v; U u;
4809 <                while ((v = advance()) != null) {
4810 <                    if ((u = transformer.apply(entryFor((K)nextKey,
4811 <                                                        v))) != null)
4807 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4808 >                         transformer, action).fork();
4809 >                }
4810 >                for (Node<K,V> p; (p = advance()) != null; ) {
4811 >                    U u;
4812 >                    if ((u = transformer.apply(p)) != null)
4813                          action.apply(u);
4814                  }
4815                  propagateCompletion();
# Line 5731 | Line 4817 | public class ConcurrentHashMapV8<K,V>
4817          }
4818      }
4819  
4820 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
4821 <        extends Traverser<K,V,Void> {
4820 >    @SuppressWarnings("serial")
4821 >    static final class ForEachTransformedMappingTask<K,V,U>
4822 >        extends BulkTask<K,V,Void> {
4823          final BiFun<? super K, ? super V, ? extends U> transformer;
4824 <        final Action<U> action;
4824 >        final Action<? super U> action;
4825          ForEachTransformedMappingTask
4826 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4826 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4827               BiFun<? super K, ? super V, ? extends U> transformer,
4828 <             Action<U> action) {
4829 <            super(m, p, b);
4828 >             Action<? super U> action) {
4829 >            super(p, b, i, f, t);
4830              this.transformer = transformer; this.action = action;
4831          }
4832 <        @SuppressWarnings("unchecked") public final void compute() {
4832 >        public final void compute() {
4833              final BiFun<? super K, ? super V, ? extends U> transformer;
4834 <            final Action<U> action;
4834 >            final Action<? super U> action;
4835              if ((transformer = this.transformer) != null &&
4836                  (action = this.action) != null) {
4837 <                for (int b; (b = preSplit()) > 0;)
4837 >                for (int i = baseIndex, f, h; batch > 0 &&
4838 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4839 >                    addToPendingCount(1);
4840                      new ForEachTransformedMappingTask<K,V,U>
4841 <                        (map, this, b, transformer, action).fork();
4842 <                V v; U u;
4843 <                while ((v = advance()) != null) {
4844 <                    if ((u = transformer.apply((K)nextKey, v)) != null)
4841 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4842 >                         transformer, action).fork();
4843 >                }
4844 >                for (Node<K,V> p; (p = advance()) != null; ) {
4845 >                    U u;
4846 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4847                          action.apply(u);
4848                  }
4849                  propagateCompletion();
# Line 5760 | Line 4851 | public class ConcurrentHashMapV8<K,V>
4851          }
4852      }
4853  
4854 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
4855 <        extends Traverser<K,V,U> {
4854 >    @SuppressWarnings("serial")
4855 >    static final class SearchKeysTask<K,V,U>
4856 >        extends BulkTask<K,V,U> {
4857          final Fun<? super K, ? extends U> searchFunction;
4858          final AtomicReference<U> result;
4859          SearchKeysTask
4860 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4860 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4861               Fun<? super K, ? extends U> searchFunction,
4862               AtomicReference<U> result) {
4863 <            super(m, p, b);
4863 >            super(p, b, i, f, t);
4864              this.searchFunction = searchFunction; this.result = result;
4865          }
4866          public final U getRawResult() { return result.get(); }
4867 <        @SuppressWarnings("unchecked") public final void compute() {
4867 >        public final void compute() {
4868              final Fun<? super K, ? extends U> searchFunction;
4869              final AtomicReference<U> result;
4870              if ((searchFunction = this.searchFunction) != null &&
4871                  (result = this.result) != null) {
4872 <                for (int b;;) {
4872 >                for (int i = baseIndex, f, h; batch > 0 &&
4873 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4874                      if (result.get() != null)
4875                          return;
4876 <                    if ((b = preSplit()) <= 0)
5784 <                        break;
4876 >                    addToPendingCount(1);
4877                      new SearchKeysTask<K,V,U>
4878 <                        (map, this, b, searchFunction, result).fork();
4878 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4879 >                         searchFunction, result).fork();
4880                  }
4881                  while (result.get() == null) {
4882                      U u;
4883 <                    if (advance() == null) {
4883 >                    Node<K,V> p;
4884 >                    if ((p = advance()) == null) {
4885                          propagateCompletion();
4886                          break;
4887                      }
4888 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
4888 >                    if ((u = searchFunction.apply(p.key)) != null) {
4889                          if (result.compareAndSet(null, u))
4890                              quietlyCompleteRoot();
4891                          break;
# Line 5801 | Line 4895 | public class ConcurrentHashMapV8<K,V>
4895          }
4896      }
4897  
4898 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
4899 <        extends Traverser<K,V,U> {
4898 >    @SuppressWarnings("serial")
4899 >    static final class SearchValuesTask<K,V,U>
4900 >        extends BulkTask<K,V,U> {
4901          final Fun<? super V, ? extends U> searchFunction;
4902          final AtomicReference<U> result;
4903          SearchValuesTask
4904 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4904 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4905               Fun<? super V, ? extends U> searchFunction,
4906               AtomicReference<U> result) {
4907 <            super(m, p, b);
4907 >            super(p, b, i, f, t);
4908              this.searchFunction = searchFunction; this.result = result;
4909          }
4910          public final U getRawResult() { return result.get(); }
4911 <        @SuppressWarnings("unchecked") public final void compute() {
4911 >        public final void compute() {
4912              final Fun<? super V, ? extends U> searchFunction;
4913              final AtomicReference<U> result;
4914              if ((searchFunction = this.searchFunction) != null &&
4915                  (result = this.result) != null) {
4916 <                for (int b;;) {
4916 >                for (int i = baseIndex, f, h; batch > 0 &&
4917 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4918                      if (result.get() != null)
4919                          return;
4920 <                    if ((b = preSplit()) <= 0)
5825 <                        break;
4920 >                    addToPendingCount(1);
4921                      new SearchValuesTask<K,V,U>
4922 <                        (map, this, b, searchFunction, result).fork();
4922 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4923 >                         searchFunction, result).fork();
4924                  }
4925                  while (result.get() == null) {
4926 <                    V v; U u;
4927 <                    if ((v = advance()) == null) {
4926 >                    U u;
4927 >                    Node<K,V> p;
4928 >                    if ((p = advance()) == null) {
4929                          propagateCompletion();
4930                          break;
4931                      }
4932 <                    if ((u = searchFunction.apply(v)) != null) {
4932 >                    if ((u = searchFunction.apply(p.val)) != null) {
4933                          if (result.compareAndSet(null, u))
4934                              quietlyCompleteRoot();
4935                          break;
# Line 5842 | Line 4939 | public class ConcurrentHashMapV8<K,V>
4939          }
4940      }
4941  
4942 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
4943 <        extends Traverser<K,V,U> {
4942 >    @SuppressWarnings("serial")
4943 >    static final class SearchEntriesTask<K,V,U>
4944 >        extends BulkTask<K,V,U> {
4945          final Fun<Entry<K,V>, ? extends U> searchFunction;
4946          final AtomicReference<U> result;
4947          SearchEntriesTask
4948 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4948 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4949               Fun<Entry<K,V>, ? extends U> searchFunction,
4950               AtomicReference<U> result) {
4951 <            super(m, p, b);
4951 >            super(p, b, i, f, t);
4952              this.searchFunction = searchFunction; this.result = result;
4953          }
4954          public final U getRawResult() { return result.get(); }
4955 <        @SuppressWarnings("unchecked") public final void compute() {
4955 >        public final void compute() {
4956              final Fun<Entry<K,V>, ? extends U> searchFunction;
4957              final AtomicReference<U> result;
4958              if ((searchFunction = this.searchFunction) != null &&
4959                  (result = this.result) != null) {
4960 <                for (int b;;) {
4960 >                for (int i = baseIndex, f, h; batch > 0 &&
4961 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4962                      if (result.get() != null)
4963                          return;
4964 <                    if ((b = preSplit()) <= 0)
5866 <                        break;
4964 >                    addToPendingCount(1);
4965                      new SearchEntriesTask<K,V,U>
4966 <                        (map, this, b, searchFunction, result).fork();
4966 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4967 >                         searchFunction, result).fork();
4968                  }
4969                  while (result.get() == null) {
4970 <                    V v; U u;
4971 <                    if ((v = advance()) == null) {
4970 >                    U u;
4971 >                    Node<K,V> p;
4972 >                    if ((p = advance()) == null) {
4973                          propagateCompletion();
4974                          break;
4975                      }
4976 <                    if ((u = searchFunction.apply(entryFor((K)nextKey,
5877 <                                                           v))) != null) {
4976 >                    if ((u = searchFunction.apply(p)) != null) {
4977                          if (result.compareAndSet(null, u))
4978                              quietlyCompleteRoot();
4979                          return;
# Line 5884 | Line 4983 | public class ConcurrentHashMapV8<K,V>
4983          }
4984      }
4985  
4986 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
4987 <        extends Traverser<K,V,U> {
4986 >    @SuppressWarnings("serial")
4987 >    static final class SearchMappingsTask<K,V,U>
4988 >        extends BulkTask<K,V,U> {
4989          final BiFun<? super K, ? super V, ? extends U> searchFunction;
4990          final AtomicReference<U> result;
4991          SearchMappingsTask
4992 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4992 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4993               BiFun<? super K, ? super V, ? extends U> searchFunction,
4994               AtomicReference<U> result) {
4995 <            super(m, p, b);
4995 >            super(p, b, i, f, t);
4996              this.searchFunction = searchFunction; this.result = result;
4997          }
4998          public final U getRawResult() { return result.get(); }
4999 <        @SuppressWarnings("unchecked") public final void compute() {
4999 >        public final void compute() {
5000              final BiFun<? super K, ? super V, ? extends U> searchFunction;
5001              final AtomicReference<U> result;
5002              if ((searchFunction = this.searchFunction) != null &&
5003                  (result = this.result) != null) {
5004 <                for (int b;;) {
5004 >                for (int i = baseIndex, f, h; batch > 0 &&
5005 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5006                      if (result.get() != null)
5007                          return;
5008 <                    if ((b = preSplit()) <= 0)
5908 <                        break;
5008 >                    addToPendingCount(1);
5009                      new SearchMappingsTask<K,V,U>
5010 <                        (map, this, b, searchFunction, result).fork();
5010 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5011 >                         searchFunction, result).fork();
5012                  }
5013                  while (result.get() == null) {
5014 <                    V v; U u;
5015 <                    if ((v = advance()) == null) {
5014 >                    U u;
5015 >                    Node<K,V> p;
5016 >                    if ((p = advance()) == null) {
5017                          propagateCompletion();
5018                          break;
5019                      }
5020 <                    if ((u = searchFunction.apply((K)nextKey, v)) != null) {
5020 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5021                          if (result.compareAndSet(null, u))
5022                              quietlyCompleteRoot();
5023                          break;
# Line 5925 | Line 5027 | public class ConcurrentHashMapV8<K,V>
5027          }
5028      }
5029  
5030 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5031 <        extends Traverser<K,V,K> {
5030 >    @SuppressWarnings("serial")
5031 >    static final class ReduceKeysTask<K,V>
5032 >        extends BulkTask<K,V,K> {
5033          final BiFun<? super K, ? super K, ? extends K> reducer;
5034          K result;
5035          ReduceKeysTask<K,V> rights, nextRight;
5036          ReduceKeysTask
5037 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5037 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5038               ReduceKeysTask<K,V> nextRight,
5039               BiFun<? super K, ? super K, ? extends K> reducer) {
5040 <            super(m, p, b); this.nextRight = nextRight;
5040 >            super(p, b, i, f, t); this.nextRight = nextRight;
5041              this.reducer = reducer;
5042          }
5043          public final K getRawResult() { return result; }
5044 <        @SuppressWarnings("unchecked") public final void compute() {
5044 >        public final void compute() {
5045              final BiFun<? super K, ? super K, ? extends K> reducer;
5046              if ((reducer = this.reducer) != null) {
5047 <                for (int b; (b = preSplit()) > 0;)
5047 >                for (int i = baseIndex, f, h; batch > 0 &&
5048 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5049 >                    addToPendingCount(1);
5050                      (rights = new ReduceKeysTask<K,V>
5051 <                     (map, this, b, rights, reducer)).fork();
5051 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5052 >                      rights, reducer)).fork();
5053 >                }
5054                  K r = null;
5055 <                while (advance() != null) {
5056 <                    K u = (K)nextKey;
5057 <                    r = (r == null) ? u : reducer.apply(r, u);
5055 >                for (Node<K,V> p; (p = advance()) != null; ) {
5056 >                    K u = p.key;
5057 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5058                  }
5059                  result = r;
5060                  CountedCompleter<?> c;
5061                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5062 <                    ReduceKeysTask<K,V>
5062 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5063                          t = (ReduceKeysTask<K,V>)c,
5064                          s = t.rights;
5065                      while (s != null) {
# Line 5967 | Line 5074 | public class ConcurrentHashMapV8<K,V>
5074          }
5075      }
5076  
5077 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5078 <        extends Traverser<K,V,V> {
5077 >    @SuppressWarnings("serial")
5078 >    static final class ReduceValuesTask<K,V>
5079 >        extends BulkTask<K,V,V> {
5080          final BiFun<? super V, ? super V, ? extends V> reducer;
5081          V result;
5082          ReduceValuesTask<K,V> rights, nextRight;
5083          ReduceValuesTask
5084 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5084 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5085               ReduceValuesTask<K,V> nextRight,
5086               BiFun<? super V, ? super V, ? extends V> reducer) {
5087 <            super(m, p, b); this.nextRight = nextRight;
5087 >            super(p, b, i, f, t); this.nextRight = nextRight;
5088              this.reducer = reducer;
5089          }
5090          public final V getRawResult() { return result; }
5091 <        @SuppressWarnings("unchecked") public final void compute() {
5091 >        public final void compute() {
5092              final BiFun<? super V, ? super V, ? extends V> reducer;
5093              if ((reducer = this.reducer) != null) {
5094 <                for (int b; (b = preSplit()) > 0;)
5094 >                for (int i = baseIndex, f, h; batch > 0 &&
5095 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5096 >                    addToPendingCount(1);
5097                      (rights = new ReduceValuesTask<K,V>
5098 <                     (map, this, b, rights, reducer)).fork();
5098 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5099 >                      rights, reducer)).fork();
5100 >                }
5101                  V r = null;
5102 <                V v;
5103 <                while ((v = advance()) != null) {
5104 <                    V u = v;
5993 <                    r = (r == null) ? u : reducer.apply(r, u);
5102 >                for (Node<K,V> p; (p = advance()) != null; ) {
5103 >                    V v = p.val;
5104 >                    r = (r == null) ? v : reducer.apply(r, v);
5105                  }
5106                  result = r;
5107                  CountedCompleter<?> c;
5108                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5109 <                    ReduceValuesTask<K,V>
5109 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5110                          t = (ReduceValuesTask<K,V>)c,
5111                          s = t.rights;
5112                      while (s != null) {
# Line 6010 | Line 5121 | public class ConcurrentHashMapV8<K,V>
5121          }
5122      }
5123  
5124 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5125 <        extends Traverser<K,V,Map.Entry<K,V>> {
5124 >    @SuppressWarnings("serial")
5125 >    static final class ReduceEntriesTask<K,V>
5126 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5127          final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5128          Map.Entry<K,V> result;
5129          ReduceEntriesTask<K,V> rights, nextRight;
5130          ReduceEntriesTask
5131 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5131 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5132               ReduceEntriesTask<K,V> nextRight,
5133               BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5134 <            super(m, p, b); this.nextRight = nextRight;
5134 >            super(p, b, i, f, t); this.nextRight = nextRight;
5135              this.reducer = reducer;
5136          }
5137          public final Map.Entry<K,V> getRawResult() { return result; }
5138 <        @SuppressWarnings("unchecked") public final void compute() {
5138 >        public final void compute() {
5139              final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5140              if ((reducer = this.reducer) != null) {
5141 <                for (int b; (b = preSplit()) > 0;)
5141 >                for (int i = baseIndex, f, h; batch > 0 &&
5142 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5143 >                    addToPendingCount(1);
5144                      (rights = new ReduceEntriesTask<K,V>
5145 <                     (map, this, b, rights, reducer)).fork();
5146 <                Map.Entry<K,V> r = null;
6033 <                V v;
6034 <                while ((v = advance()) != null) {
6035 <                    Map.Entry<K,V> u = entryFor((K)nextKey, v);
6036 <                    r = (r == null) ? u : reducer.apply(r, u);
5145 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5146 >                      rights, reducer)).fork();
5147                  }
5148 +                Map.Entry<K,V> r = null;
5149 +                for (Node<K,V> p; (p = advance()) != null; )
5150 +                    r = (r == null) ? p : reducer.apply(r, p);
5151                  result = r;
5152                  CountedCompleter<?> c;
5153                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5154 <                    ReduceEntriesTask<K,V>
5154 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5155                          t = (ReduceEntriesTask<K,V>)c,
5156                          s = t.rights;
5157                      while (s != null) {
# Line 6053 | Line 5166 | public class ConcurrentHashMapV8<K,V>
5166          }
5167      }
5168  
5169 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5170 <        extends Traverser<K,V,U> {
5169 >    @SuppressWarnings("serial")
5170 >    static final class MapReduceKeysTask<K,V,U>
5171 >        extends BulkTask<K,V,U> {
5172          final Fun<? super K, ? extends U> transformer;
5173          final BiFun<? super U, ? super U, ? extends U> reducer;
5174          U result;
5175          MapReduceKeysTask<K,V,U> rights, nextRight;
5176          MapReduceKeysTask
5177 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5177 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5178               MapReduceKeysTask<K,V,U> nextRight,
5179               Fun<? super K, ? extends U> transformer,
5180               BiFun<? super U, ? super U, ? extends U> reducer) {
5181 <            super(m, p, b); this.nextRight = nextRight;
5181 >            super(p, b, i, f, t); this.nextRight = nextRight;
5182              this.transformer = transformer;
5183              this.reducer = reducer;
5184          }
5185          public final U getRawResult() { return result; }
5186 <        @SuppressWarnings("unchecked") public final void compute() {
5186 >        public final void compute() {
5187              final Fun<? super K, ? extends U> transformer;
5188              final BiFun<? super U, ? super U, ? extends U> reducer;
5189              if ((transformer = this.transformer) != null &&
5190                  (reducer = this.reducer) != null) {
5191 <                for (int b; (b = preSplit()) > 0;)
5191 >                for (int i = baseIndex, f, h; batch > 0 &&
5192 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5193 >                    addToPendingCount(1);
5194                      (rights = new MapReduceKeysTask<K,V,U>
5195 <                     (map, this, b, rights, transformer, reducer)).fork();
5196 <                U r = null, u;
5197 <                while (advance() != null) {
5198 <                    if ((u = transformer.apply((K)nextKey)) != null)
5195 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5196 >                      rights, transformer, reducer)).fork();
5197 >                }
5198 >                U r = null;
5199 >                for (Node<K,V> p; (p = advance()) != null; ) {
5200 >                    U u;
5201 >                    if ((u = transformer.apply(p.key)) != null)
5202                          r = (r == null) ? u : reducer.apply(r, u);
5203                  }
5204                  result = r;
5205                  CountedCompleter<?> c;
5206                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5207 <                    MapReduceKeysTask<K,V,U>
5207 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5208                          t = (MapReduceKeysTask<K,V,U>)c,
5209                          s = t.rights;
5210                      while (s != null) {
# Line 6100 | Line 5219 | public class ConcurrentHashMapV8<K,V>
5219          }
5220      }
5221  
5222 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5223 <        extends Traverser<K,V,U> {
5222 >    @SuppressWarnings("serial")
5223 >    static final class MapReduceValuesTask<K,V,U>
5224 >        extends BulkTask<K,V,U> {
5225          final Fun<? super V, ? extends U> transformer;
5226          final BiFun<? super U, ? super U, ? extends U> reducer;
5227          U result;
5228          MapReduceValuesTask<K,V,U> rights, nextRight;
5229          MapReduceValuesTask
5230 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5230 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5231               MapReduceValuesTask<K,V,U> nextRight,
5232               Fun<? super V, ? extends U> transformer,
5233               BiFun<? super U, ? super U, ? extends U> reducer) {
5234 <            super(m, p, b); this.nextRight = nextRight;
5234 >            super(p, b, i, f, t); this.nextRight = nextRight;
5235              this.transformer = transformer;
5236              this.reducer = reducer;
5237          }
5238          public final U getRawResult() { return result; }
5239 <        @SuppressWarnings("unchecked") public final void compute() {
5239 >        public final void compute() {
5240              final Fun<? super V, ? extends U> transformer;
5241              final BiFun<? super U, ? super U, ? extends U> reducer;
5242              if ((transformer = this.transformer) != null &&
5243                  (reducer = this.reducer) != null) {
5244 <                for (int b; (b = preSplit()) > 0;)
5244 >                for (int i = baseIndex, f, h; batch > 0 &&
5245 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5246 >                    addToPendingCount(1);
5247                      (rights = new MapReduceValuesTask<K,V,U>
5248 <                     (map, this, b, rights, transformer, reducer)).fork();
5249 <                U r = null, u;
5250 <                V v;
5251 <                while ((v = advance()) != null) {
5252 <                    if ((u = transformer.apply(v)) != null)
5248 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5249 >                      rights, transformer, reducer)).fork();
5250 >                }
5251 >                U r = null;
5252 >                for (Node<K,V> p; (p = advance()) != null; ) {
5253 >                    U u;
5254 >                    if ((u = transformer.apply(p.val)) != null)
5255                          r = (r == null) ? u : reducer.apply(r, u);
5256                  }
5257                  result = r;
5258                  CountedCompleter<?> c;
5259                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5260 <                    MapReduceValuesTask<K,V,U>
5260 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5261                          t = (MapReduceValuesTask<K,V,U>)c,
5262                          s = t.rights;
5263                      while (s != null) {
# Line 6148 | Line 5272 | public class ConcurrentHashMapV8<K,V>
5272          }
5273      }
5274  
5275 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5276 <        extends Traverser<K,V,U> {
5275 >    @SuppressWarnings("serial")
5276 >    static final class MapReduceEntriesTask<K,V,U>
5277 >        extends BulkTask<K,V,U> {
5278          final Fun<Map.Entry<K,V>, ? extends U> transformer;
5279          final BiFun<? super U, ? super U, ? extends U> reducer;
5280          U result;
5281          MapReduceEntriesTask<K,V,U> rights, nextRight;
5282          MapReduceEntriesTask
5283 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5283 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5284               MapReduceEntriesTask<K,V,U> nextRight,
5285               Fun<Map.Entry<K,V>, ? extends U> transformer,
5286               BiFun<? super U, ? super U, ? extends U> reducer) {
5287 <            super(m, p, b); this.nextRight = nextRight;
5287 >            super(p, b, i, f, t); this.nextRight = nextRight;
5288              this.transformer = transformer;
5289              this.reducer = reducer;
5290          }
5291          public final U getRawResult() { return result; }
5292 <        @SuppressWarnings("unchecked") public final void compute() {
5292 >        public final void compute() {
5293              final Fun<Map.Entry<K,V>, ? extends U> transformer;
5294              final BiFun<? super U, ? super U, ? extends U> reducer;
5295              if ((transformer = this.transformer) != null &&
5296                  (reducer = this.reducer) != null) {
5297 <                for (int b; (b = preSplit()) > 0;)
5297 >                for (int i = baseIndex, f, h; batch > 0 &&
5298 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5299 >                    addToPendingCount(1);
5300                      (rights = new MapReduceEntriesTask<K,V,U>
5301 <                     (map, this, b, rights, transformer, reducer)).fork();
5302 <                U r = null, u;
5303 <                V v;
5304 <                while ((v = advance()) != null) {
5305 <                    if ((u = transformer.apply(entryFor((K)nextKey,
5306 <                                                        v))) != null)
5301 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5302 >                      rights, transformer, reducer)).fork();
5303 >                }
5304 >                U r = null;
5305 >                for (Node<K,V> p; (p = advance()) != null; ) {
5306 >                    U u;
5307 >                    if ((u = transformer.apply(p)) != null)
5308                          r = (r == null) ? u : reducer.apply(r, u);
5309                  }
5310                  result = r;
5311                  CountedCompleter<?> c;
5312                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5313 <                    MapReduceEntriesTask<K,V,U>
5313 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5314                          t = (MapReduceEntriesTask<K,V,U>)c,
5315                          s = t.rights;
5316                      while (s != null) {
# Line 6197 | Line 5325 | public class ConcurrentHashMapV8<K,V>
5325          }
5326      }
5327  
5328 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5329 <        extends Traverser<K,V,U> {
5328 >    @SuppressWarnings("serial")
5329 >    static final class MapReduceMappingsTask<K,V,U>
5330 >        extends BulkTask<K,V,U> {
5331          final BiFun<? super K, ? super V, ? extends U> transformer;
5332          final BiFun<? super U, ? super U, ? extends U> reducer;
5333          U result;
5334          MapReduceMappingsTask<K,V,U> rights, nextRight;
5335          MapReduceMappingsTask
5336 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5336 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5337               MapReduceMappingsTask<K,V,U> nextRight,
5338               BiFun<? super K, ? super V, ? extends U> transformer,
5339               BiFun<? super U, ? super U, ? extends U> reducer) {
5340 <            super(m, p, b); this.nextRight = nextRight;
5340 >            super(p, b, i, f, t); this.nextRight = nextRight;
5341              this.transformer = transformer;
5342              this.reducer = reducer;
5343          }
5344          public final U getRawResult() { return result; }
5345 <        @SuppressWarnings("unchecked") public final void compute() {
5345 >        public final void compute() {
5346              final BiFun<? super K, ? super V, ? extends U> transformer;
5347              final BiFun<? super U, ? super U, ? extends U> reducer;
5348              if ((transformer = this.transformer) != null &&
5349                  (reducer = this.reducer) != null) {
5350 <                for (int b; (b = preSplit()) > 0;)
5350 >                for (int i = baseIndex, f, h; batch > 0 &&
5351 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5352 >                    addToPendingCount(1);
5353                      (rights = new MapReduceMappingsTask<K,V,U>
5354 <                     (map, this, b, rights, transformer, reducer)).fork();
5355 <                U r = null, u;
5356 <                V v;
5357 <                while ((v = advance()) != null) {
5358 <                    if ((u = transformer.apply((K)nextKey, v)) != null)
5354 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5355 >                      rights, transformer, reducer)).fork();
5356 >                }
5357 >                U r = null;
5358 >                for (Node<K,V> p; (p = advance()) != null; ) {
5359 >                    U u;
5360 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5361                          r = (r == null) ? u : reducer.apply(r, u);
5362                  }
5363                  result = r;
5364                  CountedCompleter<?> c;
5365                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5366 <                    MapReduceMappingsTask<K,V,U>
5366 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5367                          t = (MapReduceMappingsTask<K,V,U>)c,
5368                          s = t.rights;
5369                      while (s != null) {
# Line 6245 | Line 5378 | public class ConcurrentHashMapV8<K,V>
5378          }
5379      }
5380  
5381 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5382 <        extends Traverser<K,V,Double> {
5381 >    @SuppressWarnings("serial")
5382 >    static final class MapReduceKeysToDoubleTask<K,V>
5383 >        extends BulkTask<K,V,Double> {
5384          final ObjectToDouble<? super K> transformer;
5385          final DoubleByDoubleToDouble reducer;
5386          final double basis;
5387          double result;
5388          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5389          MapReduceKeysToDoubleTask
5390 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5390 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5391               MapReduceKeysToDoubleTask<K,V> nextRight,
5392               ObjectToDouble<? super K> transformer,
5393               double basis,
5394               DoubleByDoubleToDouble reducer) {
5395 <            super(m, p, b); this.nextRight = nextRight;
5395 >            super(p, b, i, f, t); this.nextRight = nextRight;
5396              this.transformer = transformer;
5397              this.basis = basis; this.reducer = reducer;
5398          }
5399          public final Double getRawResult() { return result; }
5400 <        @SuppressWarnings("unchecked") public final void compute() {
5400 >        public final void compute() {
5401              final ObjectToDouble<? super K> transformer;
5402              final DoubleByDoubleToDouble reducer;
5403              if ((transformer = this.transformer) != null &&
5404                  (reducer = this.reducer) != null) {
5405                  double r = this.basis;
5406 <                for (int b; (b = preSplit()) > 0;)
5406 >                for (int i = baseIndex, f, h; batch > 0 &&
5407 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5408 >                    addToPendingCount(1);
5409                      (rights = new MapReduceKeysToDoubleTask<K,V>
5410 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5411 <                while (advance() != null)
5412 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5410 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5411 >                      rights, transformer, r, reducer)).fork();
5412 >                }
5413 >                for (Node<K,V> p; (p = advance()) != null; )
5414 >                    r = reducer.apply(r, transformer.apply(p.key));
5415                  result = r;
5416                  CountedCompleter<?> c;
5417                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5418 <                    MapReduceKeysToDoubleTask<K,V>
5418 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5419                          t = (MapReduceKeysToDoubleTask<K,V>)c,
5420                          s = t.rights;
5421                      while (s != null) {
# Line 6289 | Line 5427 | public class ConcurrentHashMapV8<K,V>
5427          }
5428      }
5429  
5430 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5431 <        extends Traverser<K,V,Double> {
5430 >    @SuppressWarnings("serial")
5431 >    static final class MapReduceValuesToDoubleTask<K,V>
5432 >        extends BulkTask<K,V,Double> {
5433          final ObjectToDouble<? super V> transformer;
5434          final DoubleByDoubleToDouble reducer;
5435          final double basis;
5436          double result;
5437          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5438          MapReduceValuesToDoubleTask
5439 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5439 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5440               MapReduceValuesToDoubleTask<K,V> nextRight,
5441               ObjectToDouble<? super V> transformer,
5442               double basis,
5443               DoubleByDoubleToDouble reducer) {
5444 <            super(m, p, b); this.nextRight = nextRight;
5444 >            super(p, b, i, f, t); this.nextRight = nextRight;
5445              this.transformer = transformer;
5446              this.basis = basis; this.reducer = reducer;
5447          }
5448          public final Double getRawResult() { return result; }
5449 <        @SuppressWarnings("unchecked") public final void compute() {
5449 >        public final void compute() {
5450              final ObjectToDouble<? super V> transformer;
5451              final DoubleByDoubleToDouble reducer;
5452              if ((transformer = this.transformer) != null &&
5453                  (reducer = this.reducer) != null) {
5454                  double r = this.basis;
5455 <                for (int b; (b = preSplit()) > 0;)
5455 >                for (int i = baseIndex, f, h; batch > 0 &&
5456 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5457 >                    addToPendingCount(1);
5458                      (rights = new MapReduceValuesToDoubleTask<K,V>
5459 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5460 <                V v;
5461 <                while ((v = advance()) != null)
5462 <                    r = reducer.apply(r, transformer.apply(v));
5459 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5460 >                      rights, transformer, r, reducer)).fork();
5461 >                }
5462 >                for (Node<K,V> p; (p = advance()) != null; )
5463 >                    r = reducer.apply(r, transformer.apply(p.val));
5464                  result = r;
5465                  CountedCompleter<?> c;
5466                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5467 <                    MapReduceValuesToDoubleTask<K,V>
5467 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5468                          t = (MapReduceValuesToDoubleTask<K,V>)c,
5469                          s = t.rights;
5470                      while (s != null) {
# Line 6334 | Line 5476 | public class ConcurrentHashMapV8<K,V>
5476          }
5477      }
5478  
5479 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5480 <        extends Traverser<K,V,Double> {
5479 >    @SuppressWarnings("serial")
5480 >    static final class MapReduceEntriesToDoubleTask<K,V>
5481 >        extends BulkTask<K,V,Double> {
5482          final ObjectToDouble<Map.Entry<K,V>> transformer;
5483          final DoubleByDoubleToDouble reducer;
5484          final double basis;
5485          double result;
5486          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5487          MapReduceEntriesToDoubleTask
5488 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5488 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5489               MapReduceEntriesToDoubleTask<K,V> nextRight,
5490               ObjectToDouble<Map.Entry<K,V>> transformer,
5491               double basis,
5492               DoubleByDoubleToDouble reducer) {
5493 <            super(m, p, b); this.nextRight = nextRight;
5493 >            super(p, b, i, f, t); this.nextRight = nextRight;
5494              this.transformer = transformer;
5495              this.basis = basis; this.reducer = reducer;
5496          }
5497          public final Double getRawResult() { return result; }
5498 <        @SuppressWarnings("unchecked") public final void compute() {
5498 >        public final void compute() {
5499              final ObjectToDouble<Map.Entry<K,V>> transformer;
5500              final DoubleByDoubleToDouble reducer;
5501              if ((transformer = this.transformer) != null &&
5502                  (reducer = this.reducer) != null) {
5503                  double r = this.basis;
5504 <                for (int b; (b = preSplit()) > 0;)
5504 >                for (int i = baseIndex, f, h; batch > 0 &&
5505 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5506 >                    addToPendingCount(1);
5507                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5508 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5509 <                V v;
5510 <                while ((v = advance()) != null)
5511 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5512 <                                                                    v)));
5508 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5509 >                      rights, transformer, r, reducer)).fork();
5510 >                }
5511 >                for (Node<K,V> p; (p = advance()) != null; )
5512 >                    r = reducer.apply(r, transformer.apply(p));
5513                  result = r;
5514                  CountedCompleter<?> c;
5515                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5516 <                    MapReduceEntriesToDoubleTask<K,V>
5516 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5517                          t = (MapReduceEntriesToDoubleTask<K,V>)c,
5518                          s = t.rights;
5519                      while (s != null) {
# Line 6380 | Line 5525 | public class ConcurrentHashMapV8<K,V>
5525          }
5526      }
5527  
5528 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5529 <        extends Traverser<K,V,Double> {
5528 >    @SuppressWarnings("serial")
5529 >    static final class MapReduceMappingsToDoubleTask<K,V>
5530 >        extends BulkTask<K,V,Double> {
5531          final ObjectByObjectToDouble<? super K, ? super V> transformer;
5532          final DoubleByDoubleToDouble reducer;
5533          final double basis;
5534          double result;
5535          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5536          MapReduceMappingsToDoubleTask
5537 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5537 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5538               MapReduceMappingsToDoubleTask<K,V> nextRight,
5539               ObjectByObjectToDouble<? super K, ? super V> transformer,
5540               double basis,
5541               DoubleByDoubleToDouble reducer) {
5542 <            super(m, p, b); this.nextRight = nextRight;
5542 >            super(p, b, i, f, t); this.nextRight = nextRight;
5543              this.transformer = transformer;
5544              this.basis = basis; this.reducer = reducer;
5545          }
5546          public final Double getRawResult() { return result; }
5547 <        @SuppressWarnings("unchecked") public final void compute() {
5547 >        public final void compute() {
5548              final ObjectByObjectToDouble<? super K, ? super V> transformer;
5549              final DoubleByDoubleToDouble reducer;
5550              if ((transformer = this.transformer) != null &&
5551                  (reducer = this.reducer) != null) {
5552                  double r = this.basis;
5553 <                for (int b; (b = preSplit()) > 0;)
5553 >                for (int i = baseIndex, f, h; batch > 0 &&
5554 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5555 >                    addToPendingCount(1);
5556                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5557 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5558 <                V v;
5559 <                while ((v = advance()) != null)
5560 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5557 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5558 >                      rights, transformer, r, reducer)).fork();
5559 >                }
5560 >                for (Node<K,V> p; (p = advance()) != null; )
5561 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5562                  result = r;
5563                  CountedCompleter<?> c;
5564                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5565 <                    MapReduceMappingsToDoubleTask<K,V>
5565 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5566                          t = (MapReduceMappingsToDoubleTask<K,V>)c,
5567                          s = t.rights;
5568                      while (s != null) {
# Line 6425 | Line 5574 | public class ConcurrentHashMapV8<K,V>
5574          }
5575      }
5576  
5577 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5578 <        extends Traverser<K,V,Long> {
5577 >    @SuppressWarnings("serial")
5578 >    static final class MapReduceKeysToLongTask<K,V>
5579 >        extends BulkTask<K,V,Long> {
5580          final ObjectToLong<? super K> transformer;
5581          final LongByLongToLong reducer;
5582          final long basis;
5583          long result;
5584          MapReduceKeysToLongTask<K,V> rights, nextRight;
5585          MapReduceKeysToLongTask
5586 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5586 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5587               MapReduceKeysToLongTask<K,V> nextRight,
5588               ObjectToLong<? super K> transformer,
5589               long basis,
5590               LongByLongToLong reducer) {
5591 <            super(m, p, b); this.nextRight = nextRight;
5591 >            super(p, b, i, f, t); this.nextRight = nextRight;
5592              this.transformer = transformer;
5593              this.basis = basis; this.reducer = reducer;
5594          }
5595          public final Long getRawResult() { return result; }
5596 <        @SuppressWarnings("unchecked") public final void compute() {
5596 >        public final void compute() {
5597              final ObjectToLong<? super K> transformer;
5598              final LongByLongToLong reducer;
5599              if ((transformer = this.transformer) != null &&
5600                  (reducer = this.reducer) != null) {
5601                  long r = this.basis;
5602 <                for (int b; (b = preSplit()) > 0;)
5602 >                for (int i = baseIndex, f, h; batch > 0 &&
5603 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5604 >                    addToPendingCount(1);
5605                      (rights = new MapReduceKeysToLongTask<K,V>
5606 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5607 <                while (advance() != null)
5608 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5606 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5607 >                      rights, transformer, r, reducer)).fork();
5608 >                }
5609 >                for (Node<K,V> p; (p = advance()) != null; )
5610 >                    r = reducer.apply(r, transformer.apply(p.key));
5611                  result = r;
5612                  CountedCompleter<?> c;
5613                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5614 <                    MapReduceKeysToLongTask<K,V>
5614 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5615                          t = (MapReduceKeysToLongTask<K,V>)c,
5616                          s = t.rights;
5617                      while (s != null) {
# Line 6469 | Line 5623 | public class ConcurrentHashMapV8<K,V>
5623          }
5624      }
5625  
5626 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5627 <        extends Traverser<K,V,Long> {
5626 >    @SuppressWarnings("serial")
5627 >    static final class MapReduceValuesToLongTask<K,V>
5628 >        extends BulkTask<K,V,Long> {
5629          final ObjectToLong<? super V> transformer;
5630          final LongByLongToLong reducer;
5631          final long basis;
5632          long result;
5633          MapReduceValuesToLongTask<K,V> rights, nextRight;
5634          MapReduceValuesToLongTask
5635 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5635 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5636               MapReduceValuesToLongTask<K,V> nextRight,
5637               ObjectToLong<? super V> transformer,
5638               long basis,
5639               LongByLongToLong reducer) {
5640 <            super(m, p, b); this.nextRight = nextRight;
5640 >            super(p, b, i, f, t); this.nextRight = nextRight;
5641              this.transformer = transformer;
5642              this.basis = basis; this.reducer = reducer;
5643          }
5644          public final Long getRawResult() { return result; }
5645 <        @SuppressWarnings("unchecked") public final void compute() {
5645 >        public final void compute() {
5646              final ObjectToLong<? super V> transformer;
5647              final LongByLongToLong reducer;
5648              if ((transformer = this.transformer) != null &&
5649                  (reducer = this.reducer) != null) {
5650                  long r = this.basis;
5651 <                for (int b; (b = preSplit()) > 0;)
5651 >                for (int i = baseIndex, f, h; batch > 0 &&
5652 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5653 >                    addToPendingCount(1);
5654                      (rights = new MapReduceValuesToLongTask<K,V>
5655 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5656 <                V v;
5657 <                while ((v = advance()) != null)
5658 <                    r = reducer.apply(r, transformer.apply(v));
5655 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5656 >                      rights, transformer, r, reducer)).fork();
5657 >                }
5658 >                for (Node<K,V> p; (p = advance()) != null; )
5659 >                    r = reducer.apply(r, transformer.apply(p.val));
5660                  result = r;
5661                  CountedCompleter<?> c;
5662                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5663 <                    MapReduceValuesToLongTask<K,V>
5663 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5664                          t = (MapReduceValuesToLongTask<K,V>)c,
5665                          s = t.rights;
5666                      while (s != null) {
# Line 6514 | Line 5672 | public class ConcurrentHashMapV8<K,V>
5672          }
5673      }
5674  
5675 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5676 <        extends Traverser<K,V,Long> {
5675 >    @SuppressWarnings("serial")
5676 >    static final class MapReduceEntriesToLongTask<K,V>
5677 >        extends BulkTask<K,V,Long> {
5678          final ObjectToLong<Map.Entry<K,V>> transformer;
5679          final LongByLongToLong reducer;
5680          final long basis;
5681          long result;
5682          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5683          MapReduceEntriesToLongTask
5684 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5684 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5685               MapReduceEntriesToLongTask<K,V> nextRight,
5686               ObjectToLong<Map.Entry<K,V>> transformer,
5687               long basis,
5688               LongByLongToLong reducer) {
5689 <            super(m, p, b); this.nextRight = nextRight;
5689 >            super(p, b, i, f, t); this.nextRight = nextRight;
5690              this.transformer = transformer;
5691              this.basis = basis; this.reducer = reducer;
5692          }
5693          public final Long getRawResult() { return result; }
5694 <        @SuppressWarnings("unchecked") public final void compute() {
5694 >        public final void compute() {
5695              final ObjectToLong<Map.Entry<K,V>> transformer;
5696              final LongByLongToLong reducer;
5697              if ((transformer = this.transformer) != null &&
5698                  (reducer = this.reducer) != null) {
5699                  long r = this.basis;
5700 <                for (int b; (b = preSplit()) > 0;)
5700 >                for (int i = baseIndex, f, h; batch > 0 &&
5701 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5702 >                    addToPendingCount(1);
5703                      (rights = new MapReduceEntriesToLongTask<K,V>
5704 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5705 <                V v;
5706 <                while ((v = advance()) != null)
5707 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5708 <                                                                    v)));
5704 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5705 >                      rights, transformer, r, reducer)).fork();
5706 >                }
5707 >                for (Node<K,V> p; (p = advance()) != null; )
5708 >                    r = reducer.apply(r, transformer.apply(p));
5709                  result = r;
5710                  CountedCompleter<?> c;
5711                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5712 <                    MapReduceEntriesToLongTask<K,V>
5712 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5713                          t = (MapReduceEntriesToLongTask<K,V>)c,
5714                          s = t.rights;
5715                      while (s != null) {
# Line 6560 | Line 5721 | public class ConcurrentHashMapV8<K,V>
5721          }
5722      }
5723  
5724 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
5725 <        extends Traverser<K,V,Long> {
5724 >    @SuppressWarnings("serial")
5725 >    static final class MapReduceMappingsToLongTask<K,V>
5726 >        extends BulkTask<K,V,Long> {
5727          final ObjectByObjectToLong<? super K, ? super V> transformer;
5728          final LongByLongToLong reducer;
5729          final long basis;
5730          long result;
5731          MapReduceMappingsToLongTask<K,V> rights, nextRight;
5732          MapReduceMappingsToLongTask
5733 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5733 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5734               MapReduceMappingsToLongTask<K,V> nextRight,
5735               ObjectByObjectToLong<? super K, ? super V> transformer,
5736               long basis,
5737               LongByLongToLong reducer) {
5738 <            super(m, p, b); this.nextRight = nextRight;
5738 >            super(p, b, i, f, t); this.nextRight = nextRight;
5739              this.transformer = transformer;
5740              this.basis = basis; this.reducer = reducer;
5741          }
5742          public final Long getRawResult() { return result; }
5743 <        @SuppressWarnings("unchecked") public final void compute() {
5743 >        public final void compute() {
5744              final ObjectByObjectToLong<? super K, ? super V> transformer;
5745              final LongByLongToLong reducer;
5746              if ((transformer = this.transformer) != null &&
5747                  (reducer = this.reducer) != null) {
5748                  long r = this.basis;
5749 <                for (int b; (b = preSplit()) > 0;)
5749 >                for (int i = baseIndex, f, h; batch > 0 &&
5750 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5751 >                    addToPendingCount(1);
5752                      (rights = new MapReduceMappingsToLongTask<K,V>
5753 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5754 <                V v;
5755 <                while ((v = advance()) != null)
5756 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5753 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5754 >                      rights, transformer, r, reducer)).fork();
5755 >                }
5756 >                for (Node<K,V> p; (p = advance()) != null; )
5757 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5758                  result = r;
5759                  CountedCompleter<?> c;
5760                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5761 <                    MapReduceMappingsToLongTask<K,V>
5761 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5762                          t = (MapReduceMappingsToLongTask<K,V>)c,
5763                          s = t.rights;
5764                      while (s != null) {
# Line 6605 | Line 5770 | public class ConcurrentHashMapV8<K,V>
5770          }
5771      }
5772  
5773 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
5774 <        extends Traverser<K,V,Integer> {
5773 >    @SuppressWarnings("serial")
5774 >    static final class MapReduceKeysToIntTask<K,V>
5775 >        extends BulkTask<K,V,Integer> {
5776          final ObjectToInt<? super K> transformer;
5777          final IntByIntToInt reducer;
5778          final int basis;
5779          int result;
5780          MapReduceKeysToIntTask<K,V> rights, nextRight;
5781          MapReduceKeysToIntTask
5782 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5782 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5783               MapReduceKeysToIntTask<K,V> nextRight,
5784               ObjectToInt<? super K> transformer,
5785               int basis,
5786               IntByIntToInt reducer) {
5787 <            super(m, p, b); this.nextRight = nextRight;
5787 >            super(p, b, i, f, t); this.nextRight = nextRight;
5788              this.transformer = transformer;
5789              this.basis = basis; this.reducer = reducer;
5790          }
5791          public final Integer getRawResult() { return result; }
5792 <        @SuppressWarnings("unchecked") public final void compute() {
5792 >        public final void compute() {
5793              final ObjectToInt<? super K> transformer;
5794              final IntByIntToInt reducer;
5795              if ((transformer = this.transformer) != null &&
5796                  (reducer = this.reducer) != null) {
5797                  int r = this.basis;
5798 <                for (int b; (b = preSplit()) > 0;)
5798 >                for (int i = baseIndex, f, h; batch > 0 &&
5799 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5800 >                    addToPendingCount(1);
5801                      (rights = new MapReduceKeysToIntTask<K,V>
5802 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5803 <                while (advance() != null)
5804 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5802 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5803 >                      rights, transformer, r, reducer)).fork();
5804 >                }
5805 >                for (Node<K,V> p; (p = advance()) != null; )
5806 >                    r = reducer.apply(r, transformer.apply(p.key));
5807                  result = r;
5808                  CountedCompleter<?> c;
5809                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5810 <                    MapReduceKeysToIntTask<K,V>
5810 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5811                          t = (MapReduceKeysToIntTask<K,V>)c,
5812                          s = t.rights;
5813                      while (s != null) {
# Line 6649 | Line 5819 | public class ConcurrentHashMapV8<K,V>
5819          }
5820      }
5821  
5822 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
5823 <        extends Traverser<K,V,Integer> {
5822 >    @SuppressWarnings("serial")
5823 >    static final class MapReduceValuesToIntTask<K,V>
5824 >        extends BulkTask<K,V,Integer> {
5825          final ObjectToInt<? super V> transformer;
5826          final IntByIntToInt reducer;
5827          final int basis;
5828          int result;
5829          MapReduceValuesToIntTask<K,V> rights, nextRight;
5830          MapReduceValuesToIntTask
5831 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5831 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5832               MapReduceValuesToIntTask<K,V> nextRight,
5833               ObjectToInt<? super V> transformer,
5834               int basis,
5835               IntByIntToInt reducer) {
5836 <            super(m, p, b); this.nextRight = nextRight;
5836 >            super(p, b, i, f, t); this.nextRight = nextRight;
5837              this.transformer = transformer;
5838              this.basis = basis; this.reducer = reducer;
5839          }
5840          public final Integer getRawResult() { return result; }
5841 <        @SuppressWarnings("unchecked") public final void compute() {
5841 >        public final void compute() {
5842              final ObjectToInt<? super V> transformer;
5843              final IntByIntToInt reducer;
5844              if ((transformer = this.transformer) != null &&
5845                  (reducer = this.reducer) != null) {
5846                  int r = this.basis;
5847 <                for (int b; (b = preSplit()) > 0;)
5847 >                for (int i = baseIndex, f, h; batch > 0 &&
5848 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5849 >                    addToPendingCount(1);
5850                      (rights = new MapReduceValuesToIntTask<K,V>
5851 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5852 <                V v;
5853 <                while ((v = advance()) != null)
5854 <                    r = reducer.apply(r, transformer.apply(v));
5851 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5852 >                      rights, transformer, r, reducer)).fork();
5853 >                }
5854 >                for (Node<K,V> p; (p = advance()) != null; )
5855 >                    r = reducer.apply(r, transformer.apply(p.val));
5856                  result = r;
5857                  CountedCompleter<?> c;
5858                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5859 <                    MapReduceValuesToIntTask<K,V>
5859 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5860                          t = (MapReduceValuesToIntTask<K,V>)c,
5861                          s = t.rights;
5862                      while (s != null) {
# Line 6694 | Line 5868 | public class ConcurrentHashMapV8<K,V>
5868          }
5869      }
5870  
5871 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
5872 <        extends Traverser<K,V,Integer> {
5871 >    @SuppressWarnings("serial")
5872 >    static final class MapReduceEntriesToIntTask<K,V>
5873 >        extends BulkTask<K,V,Integer> {
5874          final ObjectToInt<Map.Entry<K,V>> transformer;
5875          final IntByIntToInt reducer;
5876          final int basis;
5877          int result;
5878          MapReduceEntriesToIntTask<K,V> rights, nextRight;
5879          MapReduceEntriesToIntTask
5880 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5880 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5881               MapReduceEntriesToIntTask<K,V> nextRight,
5882               ObjectToInt<Map.Entry<K,V>> transformer,
5883               int basis,
5884               IntByIntToInt reducer) {
5885 <            super(m, p, b); this.nextRight = nextRight;
5885 >            super(p, b, i, f, t); this.nextRight = nextRight;
5886              this.transformer = transformer;
5887              this.basis = basis; this.reducer = reducer;
5888          }
5889          public final Integer getRawResult() { return result; }
5890 <        @SuppressWarnings("unchecked") public final void compute() {
5890 >        public final void compute() {
5891              final ObjectToInt<Map.Entry<K,V>> transformer;
5892              final IntByIntToInt reducer;
5893              if ((transformer = this.transformer) != null &&
5894                  (reducer = this.reducer) != null) {
5895                  int r = this.basis;
5896 <                for (int b; (b = preSplit()) > 0;)
5896 >                for (int i = baseIndex, f, h; batch > 0 &&
5897 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5898 >                    addToPendingCount(1);
5899                      (rights = new MapReduceEntriesToIntTask<K,V>
5900 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5901 <                V v;
5902 <                while ((v = advance()) != null)
5903 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5904 <                                                                    v)));
5900 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5901 >                      rights, transformer, r, reducer)).fork();
5902 >                }
5903 >                for (Node<K,V> p; (p = advance()) != null; )
5904 >                    r = reducer.apply(r, transformer.apply(p));
5905                  result = r;
5906                  CountedCompleter<?> c;
5907                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5908 <                    MapReduceEntriesToIntTask<K,V>
5908 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5909                          t = (MapReduceEntriesToIntTask<K,V>)c,
5910                          s = t.rights;
5911                      while (s != null) {
# Line 6740 | Line 5917 | public class ConcurrentHashMapV8<K,V>
5917          }
5918      }
5919  
5920 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
5921 <        extends Traverser<K,V,Integer> {
5920 >    @SuppressWarnings("serial")
5921 >    static final class MapReduceMappingsToIntTask<K,V>
5922 >        extends BulkTask<K,V,Integer> {
5923          final ObjectByObjectToInt<? super K, ? super V> transformer;
5924          final IntByIntToInt reducer;
5925          final int basis;
5926          int result;
5927          MapReduceMappingsToIntTask<K,V> rights, nextRight;
5928          MapReduceMappingsToIntTask
5929 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5929 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5930               MapReduceMappingsToIntTask<K,V> nextRight,
5931               ObjectByObjectToInt<? super K, ? super V> transformer,
5932               int basis,
5933               IntByIntToInt reducer) {
5934 <            super(m, p, b); this.nextRight = nextRight;
5934 >            super(p, b, i, f, t); this.nextRight = nextRight;
5935              this.transformer = transformer;
5936              this.basis = basis; this.reducer = reducer;
5937          }
5938          public final Integer getRawResult() { return result; }
5939 <        @SuppressWarnings("unchecked") public final void compute() {
5939 >        public final void compute() {
5940              final ObjectByObjectToInt<? super K, ? super V> transformer;
5941              final IntByIntToInt reducer;
5942              if ((transformer = this.transformer) != null &&
5943                  (reducer = this.reducer) != null) {
5944                  int r = this.basis;
5945 <                for (int b; (b = preSplit()) > 0;)
5945 >                for (int i = baseIndex, f, h; batch > 0 &&
5946 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5947 >                    addToPendingCount(1);
5948                      (rights = new MapReduceMappingsToIntTask<K,V>
5949 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5950 <                V v;
5951 <                while ((v = advance()) != null)
5952 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5949 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5950 >                      rights, transformer, r, reducer)).fork();
5951 >                }
5952 >                for (Node<K,V> p; (p = advance()) != null; )
5953 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5954                  result = r;
5955                  CountedCompleter<?> c;
5956                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5957 <                    MapReduceMappingsToIntTask<K,V>
5957 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
5958                          t = (MapReduceMappingsToIntTask<K,V>)c,
5959                          s = t.rights;
5960                      while (s != null) {
# Line 6785 | Line 5966 | public class ConcurrentHashMapV8<K,V>
5966          }
5967      }
5968  
5969 +    /* ---------------- Counters -------------- */
5970 +
5971 +    // Adapted from LongAdder and Striped64.
5972 +    // See their internal docs for explanation.
5973 +
5974 +    // A padded cell for distributing counts
5975 +    static final class CounterCell {
5976 +        volatile long p0, p1, p2, p3, p4, p5, p6;
5977 +        volatile long value;
5978 +        volatile long q0, q1, q2, q3, q4, q5, q6;
5979 +        CounterCell(long x) { value = x; }
5980 +    }
5981 +
5982 +    /**
5983 +     * Holder for the thread-local hash code determining which
5984 +     * CounterCell to use. The code is initialized via the
5985 +     * counterHashCodeGenerator, but may be moved upon collisions.
5986 +     */
5987 +    static final class CounterHashCode {
5988 +        int code;
5989 +    }
5990 +
5991 +    /**
5992 +     * Generates initial value for per-thread CounterHashCodes.
5993 +     */
5994 +    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
5995 +
5996 +    /**
5997 +     * Increment for counterHashCodeGenerator. See class ThreadLocal
5998 +     * for explanation.
5999 +     */
6000 +    static final int SEED_INCREMENT = 0x61c88647;
6001 +
6002 +    /**
6003 +     * Per-thread counter hash codes. Shared across all instances.
6004 +     */
6005 +    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
6006 +        new ThreadLocal<CounterHashCode>();
6007 +
6008 +
6009 +    final long sumCount() {
6010 +        CounterCell[] as = counterCells; CounterCell a;
6011 +        long sum = baseCount;
6012 +        if (as != null) {
6013 +            for (int i = 0; i < as.length; ++i) {
6014 +                if ((a = as[i]) != null)
6015 +                    sum += a.value;
6016 +            }
6017 +        }
6018 +        return sum;
6019 +    }
6020 +
6021 +    // See LongAdder version for explanation
6022 +    private final void fullAddCount(long x, CounterHashCode hc,
6023 +                                    boolean wasUncontended) {
6024 +        int h;
6025 +        if (hc == null) {
6026 +            hc = new CounterHashCode();
6027 +            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
6028 +            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
6029 +            threadCounterHashCode.set(hc);
6030 +        }
6031 +        else
6032 +            h = hc.code;
6033 +        boolean collide = false;                // True if last slot nonempty
6034 +        for (;;) {
6035 +            CounterCell[] as; CounterCell a; int n; long v;
6036 +            if ((as = counterCells) != null && (n = as.length) > 0) {
6037 +                if ((a = as[(n - 1) & h]) == null) {
6038 +                    if (cellsBusy == 0) {            // Try to attach new Cell
6039 +                        CounterCell r = new CounterCell(x); // Optimistic create
6040 +                        if (cellsBusy == 0 &&
6041 +                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6042 +                            boolean created = false;
6043 +                            try {               // Recheck under lock
6044 +                                CounterCell[] rs; int m, j;
6045 +                                if ((rs = counterCells) != null &&
6046 +                                    (m = rs.length) > 0 &&
6047 +                                    rs[j = (m - 1) & h] == null) {
6048 +                                    rs[j] = r;
6049 +                                    created = true;
6050 +                                }
6051 +                            } finally {
6052 +                                cellsBusy = 0;
6053 +                            }
6054 +                            if (created)
6055 +                                break;
6056 +                            continue;           // Slot is now non-empty
6057 +                        }
6058 +                    }
6059 +                    collide = false;
6060 +                }
6061 +                else if (!wasUncontended)       // CAS already known to fail
6062 +                    wasUncontended = true;      // Continue after rehash
6063 +                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
6064 +                    break;
6065 +                else if (counterCells != as || n >= NCPU)
6066 +                    collide = false;            // At max size or stale
6067 +                else if (!collide)
6068 +                    collide = true;
6069 +                else if (cellsBusy == 0 &&
6070 +                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6071 +                    try {
6072 +                        if (counterCells == as) {// Expand table unless stale
6073 +                            CounterCell[] rs = new CounterCell[n << 1];
6074 +                            for (int i = 0; i < n; ++i)
6075 +                                rs[i] = as[i];
6076 +                            counterCells = rs;
6077 +                        }
6078 +                    } finally {
6079 +                        cellsBusy = 0;
6080 +                    }
6081 +                    collide = false;
6082 +                    continue;                   // Retry with expanded table
6083 +                }
6084 +                h ^= h << 13;                   // Rehash
6085 +                h ^= h >>> 17;
6086 +                h ^= h << 5;
6087 +            }
6088 +            else if (cellsBusy == 0 && counterCells == as &&
6089 +                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6090 +                boolean init = false;
6091 +                try {                           // Initialize table
6092 +                    if (counterCells == as) {
6093 +                        CounterCell[] rs = new CounterCell[2];
6094 +                        rs[h & 1] = new CounterCell(x);
6095 +                        counterCells = rs;
6096 +                        init = true;
6097 +                    }
6098 +                } finally {
6099 +                    cellsBusy = 0;
6100 +                }
6101 +                if (init)
6102 +                    break;
6103 +            }
6104 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
6105 +                break;                          // Fall back on using base
6106 +        }
6107 +        hc.code = h;                            // Record index for next time
6108 +    }
6109 +
6110      // Unsafe mechanics
6111      private static final sun.misc.Unsafe U;
6112      private static final long SIZECTL;
6113      private static final long TRANSFERINDEX;
6114      private static final long TRANSFERORIGIN;
6115      private static final long BASECOUNT;
6116 <    private static final long COUNTERBUSY;
6116 >    private static final long CELLSBUSY;
6117      private static final long CELLVALUE;
6118      private static final long ABASE;
6119      private static final int ASHIFT;
# Line 6808 | Line 6130 | public class ConcurrentHashMapV8<K,V>
6130                  (k.getDeclaredField("transferOrigin"));
6131              BASECOUNT = U.objectFieldOffset
6132                  (k.getDeclaredField("baseCount"));
6133 <            COUNTERBUSY = U.objectFieldOffset
6134 <                (k.getDeclaredField("counterBusy"));
6133 >            CELLSBUSY = U.objectFieldOffset
6134 >                (k.getDeclaredField("cellsBusy"));
6135              Class<?> ck = CounterCell.class;
6136              CELLVALUE = U.objectFieldOffset
6137                  (ck.getDeclaredField("value"));

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines