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.97 by jsr166, Mon Feb 11 20:43:59 2013 UTC vs.
Revision 1.114 by dl, Fri Aug 9 18:43:44 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.AbstractMap;
16   import java.util.Arrays;
11 import java.util.Map;
12 import java.util.Set;
17   import java.util.Collection;
18 < import java.util.AbstractMap;
19 < import java.util.AbstractSet;
20 < import java.util.AbstractCollection;
17 < import java.util.Hashtable;
18 > import java.util.Comparator;
19 > import java.util.ConcurrentModificationException;
20 > import java.util.Enumeration;
21   import java.util.HashMap;
22 + import java.util.Hashtable;
23   import java.util.Iterator;
24 < import java.util.Enumeration;
21 < import java.util.ConcurrentModificationException;
24 > import java.util.Map;
25   import java.util.NoSuchElementException;
26 + import java.util.Set;
27   import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
25 import java.util.concurrent.atomic.AtomicInteger;
28   import java.util.concurrent.atomic.AtomicReference;
29 < import java.io.Serializable;
29 > import java.util.concurrent.atomic.AtomicInteger;
30 > import java.util.concurrent.locks.LockSupport;
31 > import java.util.concurrent.locks.ReentrantLock;
32  
33   /**
34   * A hash table supporting full concurrency of retrievals and
# Line 78 | Line 82 | import java.io.Serializable;
82   * expected {@code concurrencyLevel} as an additional hint for
83   * internal sizing.  Note that using many keys with exactly the same
84   * {@code hashCode()} is a sure way to slow down performance of any
85 < * hash table.
85 > * hash table. To ameliorate impact, when keys are {@link Comparable},
86 > * this class may use comparison order among keys to help break ties.
87   *
88   * <p>A {@link Set} projection of a ConcurrentHashMapV8 may be created
89   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
# Line 86 | Line 91 | import java.io.Serializable;
91   * mapped values are (perhaps transiently) not used or all take the
92   * same mapping value.
93   *
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 *
94   * <p>This class and its views and iterators implement all of the
95   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
96   * interfaces.
# Line 100 | Line 98 | import java.io.Serializable;
98   * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
99   * does <em>not</em> allow {@code null} to be used as a key or value.
100   *
101 < * <p>ConcurrentHashMapV8s support sequential and parallel operations
102 < * bulk operations. (Parallel forms use the {@link
103 < * ForkJoinPool#commonPool()}). Tasks that may be used in other
104 < * contexts are available in class {@link ForkJoinTasks}. These
105 < * operations are designed to be safely, and often sensibly, applied
106 < * even with maps that are being concurrently updated by other
107 < * threads; for example, when computing a snapshot summary of the
108 < * values in a shared registry.  There are three kinds of operation,
109 < * each with four forms, accepting functions with Keys, Values,
110 < * Entries, and (Key, Value) arguments and/or return values. Because
111 < * the elements of a ConcurrentHashMapV8 are not ordered in any
112 < * particular way, and may be processed in different orders in
113 < * different parallel executions, the correctness of supplied
114 < * functions should not depend on any ordering, or on any other
115 < * 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.
101 > * <p>ConcurrentHashMapV8s support a set of sequential and parallel bulk
102 > * operations that are designed
103 > * to be safely, and often sensibly, applied even with maps that are
104 > * being concurrently updated by other threads; for example, when
105 > * computing a snapshot summary of the values in a shared registry.
106 > * There are three kinds of operation, each with four forms, accepting
107 > * functions with Keys, Values, Entries, and (Key, Value) arguments
108 > * and/or return values. Because the elements of a ConcurrentHashMapV8
109 > * are not ordered in any particular way, and may be processed in
110 > * different orders in different parallel executions, the correctness
111 > * of supplied functions should not depend on any ordering, or on any
112 > * other objects or values that may transiently change while
113 > * computation is in progress; and except for forEach actions, should
114 > * ideally be side-effect-free. Bulk operations on {@link java.util.Map.Entry}
115 > * objects do not support method {@code setValue}.
116   *
117   * <ul>
118   * <li> forEach: Perform a given action on each element.
# Line 143 | Line 139 | import java.io.Serializable;
139   * <li> Reductions to scalar doubles, longs, and ints, using a
140   * given basis value.</li>
141   *
146 * </li>
142   * </ul>
143 + * </li>
144   * </ul>
145   *
146 + * <p>These bulk operations accept a {@code parallelismThreshold}
147 + * argument. Methods proceed sequentially if the current map size is
148 + * estimated to be less than the given threshold. Using a value of
149 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
150 + * of {@code 1} results in maximal parallelism by partitioning into
151 + * enough subtasks to fully utilize the {@link
152 + * ForkJoinPool#commonPool()} that is used for all parallel
153 + * computations. Normally, you would initially choose one of these
154 + * extreme values, and then measure performance of using in-between
155 + * values that trade off overhead versus throughput.
156 + *
157   * <p>The concurrency properties of bulk operations follow
158   * from those of ConcurrentHashMapV8: Any non-null result returned
159   * from {@code get(key)} and related access methods bears a
# Line 212 | Line 219 | import java.io.Serializable;
219   * @param <K> the type of keys maintained by this map
220   * @param <V> the type of mapped values
221   */
222 < public class ConcurrentHashMapV8<K, V>
223 <    implements ConcurrentMap<K, V>, Serializable {
222 > public class ConcurrentHashMapV8<K,V> extends AbstractMap<K,V>
223 >    implements ConcurrentMap<K,V>, Serializable {
224      private static final long serialVersionUID = 7249069246763182397L;
225  
226      /**
227 <     * A partitionable iterator. A Spliterator can be traversed
228 <     * directly, but can also be partitioned (before traversal) by
229 <     * 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>
227 >     * An object for traversing and partitioning elements of a source.
228 >     * This interface provides a subset of the functionality of JDK8
229 >     * java.util.Spliterator.
230       */
231 <    public static interface Spliterator<T> extends Iterator<T> {
231 >    public static interface ConcurrentHashMapSpliterator<T> {
232          /**
233 <         * Returns a Spliterator covering approximately half of the
234 <         * elements, guaranteed not to overlap with those subsequently
235 <         * returned by this Spliterator.  After invoking this method,
236 <         * the current Spliterator will <em>not</em> produce any of
272 <         * the elements of the returned Spliterator, but the two
273 <         * Spliterators together will produce all of the elements that
274 <         * would have been produced by this Spliterator had this
275 <         * method not been called. The exact number of elements
276 <         * 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
233 >         * If possible, returns a new spliterator covering
234 >         * approximately one half of the elements, which will not be
235 >         * covered by this spliterator. Returns null if cannot be
236 >         * split.
237           */
238 <        Spliterator<T> split();
238 >        ConcurrentHashMapSpliterator<T> trySplit();
239 >        /**
240 >         * Returns an estimate of the number of elements covered by
241 >         * this Spliterator.
242 >         */
243 >        long estimateSize();
244 >
245 >        /** Applies the action to each untraversed element */
246 >        void forEachRemaining(Action<? super T> action);
247 >        /** If an element remains, applies the action and returns true. */
248 >        boolean tryAdvance(Action<? super T> action);
249      }
250  
251 +    // Sams
252 +    /** Interface describing a void action of one argument */
253 +    public interface Action<A> { void apply(A a); }
254 +    /** Interface describing a void action of two arguments */
255 +    public interface BiAction<A,B> { void apply(A a, B b); }
256 +    /** Interface describing a function of one argument */
257 +    public interface Fun<A,T> { T apply(A a); }
258 +    /** Interface describing a function of two arguments */
259 +    public interface BiFun<A,B,T> { T apply(A a, B b); }
260 +    /** Interface describing a function mapping its argument to a double */
261 +    public interface ObjectToDouble<A> { double apply(A a); }
262 +    /** Interface describing a function mapping its argument to a long */
263 +    public interface ObjectToLong<A> { long apply(A a); }
264 +    /** Interface describing a function mapping its argument to an int */
265 +    public interface ObjectToInt<A> {int apply(A a); }
266 +    /** Interface describing a function mapping two arguments to a double */
267 +    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
268 +    /** Interface describing a function mapping two arguments to a long */
269 +    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
270 +    /** Interface describing a function mapping two arguments to an int */
271 +    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
272 +    /** Interface describing a function mapping two doubles to a double */
273 +    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
274 +    /** Interface describing a function mapping two longs to a long */
275 +    public interface LongByLongToLong { long apply(long a, long b); }
276 +    /** Interface describing a function mapping two ints to an int */
277 +    public interface IntByIntToInt { int apply(int a, int b); }
278 +
279      /*
280       * Overview:
281       *
# Line 295 | Line 286 | public class ConcurrentHashMapV8<K, V>
286       * the same or better than java.util.HashMap, and to support high
287       * initial insertion rates on an empty table by many threads.
288       *
289 <     * Each key-value mapping is held in a Node.  Because Node key
290 <     * fields can contain special values, they are defined using plain
291 <     * Object types (not type "K"). This leads to a lot of explicit
292 <     * casting (and many explicit warning suppressions to tell
293 <     * compilers not to complain about it). It also allows some of the
294 <     * public methods to be factored into a smaller number of internal
295 <     * methods (although sadly not so for the five variants of
296 <     * put-related operations). The validation-based approach
297 <     * explained below leads to a lot of code sprawl because
298 <     * retry-control precludes factoring into smaller methods.
289 >     * This map usually acts as a binned (bucketed) hash table.  Each
290 >     * key-value mapping is held in a Node.  Most nodes are instances
291 >     * of the basic Node class with hash, key, value, and next
292 >     * fields. However, various subclasses exist: TreeNodes are
293 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
294 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
295 >     * of bins during resizing. ReservationNodes are used as
296 >     * placeholders while establishing values in computeIfAbsent and
297 >     * related methods.  The types TreeBin, ForwardingNode, and
298 >     * ReservationNode do not hold normal user keys, values, or
299 >     * hashes, and are readily distinguishable during search etc
300 >     * because they have negative hash fields and null key and value
301 >     * fields. (These special nodes are either uncommon or transient,
302 >     * so the impact of carrying around some unused fields is
303 >     * insignificant.)
304       *
305       * The table is lazily initialized to a power-of-two size upon the
306       * first insertion.  Each bin in the table normally contains a
# Line 312 | Line 308 | public class ConcurrentHashMapV8<K, V>
308       * Table accesses require volatile/atomic reads, writes, and
309       * CASes.  Because there is no other way to arrange this without
310       * adding further indirections, we use intrinsics
311 <     * (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.
311 >     * (sun.misc.Unsafe) operations.
312       *
313       * We use the top (sign) bit of Node hash fields for control
314       * purposes -- it is available anyway because of addressing
315 <     * constraints.  Nodes with negative hash fields are forwarding
316 <     * 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.
315 >     * constraints.  Nodes with negative hash fields are specially
316 >     * handled or ignored in map methods.
317       *
318       * Insertion (via put or its variants) of the first node in an
319       * empty bin is performed by just CASing it to the bin.  This is
# Line 339 | Line 330 | public class ConcurrentHashMapV8<K, V>
330       * validate that it is still the first node after locking it, and
331       * retry if not. Because new nodes are always appended to lists,
332       * once a node is first in a bin, it remains first until deleted
333 <     * 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.
333 >     * or the bin becomes invalidated (upon resizing).
334       *
335       * The main disadvantage of per-bin locks is that other update
336       * operations on other nodes in a bin list protected by the same
# Line 375 | Line 363 | public class ConcurrentHashMapV8<K, V>
363       * sometimes deviate significantly from uniform randomness.  This
364       * includes the case when N > (1<<30), so some keys MUST collide.
365       * Similarly for dumb or hostile usages in which multiple keys are
366 <     * designed to have identical hash codes. Also, although we guard
367 <     * against the worst effects of this (see method spread), sets of
368 <     * hashes may differ only in bits that do not impact their bin
369 <     * index for a given power-of-two mask.  So we use a secondary
370 <     * strategy that applies when the number of nodes in a bin exceeds
371 <     * 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
366 >     * designed to have identical hash codes or ones that differs only
367 >     * in masked-out high bits. So we use a secondary strategy that
368 >     * applies when the number of nodes in a bin exceeds a
369 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
370 >     * specialized form of red-black trees), bounding search time to
371 >     * O(log N).  Each search step in a TreeBin is at least twice as
372       * slow as in a regular list, but given that N cannot exceed
373       * (1<<64) (before running out of addresses) this bounds search
374       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 456 | Line 441 | public class ConcurrentHashMapV8<K, V>
441       * bin already holding two or more nodes. Under uniform hash
442       * distributions, the probability of this occurring at threshold
443       * is around 13%, meaning that only about 1 in 8 puts check
444 <     * threshold (and after resizing, many fewer do so). The bulk
445 <     * putAll operation further reduces contention by only committing
446 <     * count updates upon these size checks.
444 >     * threshold (and after resizing, many fewer do so).
445 >     *
446 >     * TreeBins use a special form of comparison for search and
447 >     * related operations (which is the main reason we cannot use
448 >     * existing collections such as TreeMaps). TreeBins contain
449 >     * Comparable elements, but may contain others, as well as
450 >     * elements that are Comparable but not necessarily Comparable for
451 >     * the same T, so we cannot invoke compareTo among them. To handle
452 >     * this, the tree is ordered primarily by hash value, then by
453 >     * Comparable.compareTo order if applicable.  On lookup at a node,
454 >     * if elements are not comparable or compare as 0 then both left
455 >     * and right children may need to be searched in the case of tied
456 >     * hash values. (This corresponds to the full list search that
457 >     * would be necessary if all elements were non-Comparable and had
458 >     * tied hashes.) On insertion, to keep a total ordering (or as
459 >     * close as is required here) across rebalancings, we compare
460 >     * classes and identityHashCodes as tie-breakers. The red-black
461 >     * balancing code is updated from pre-jdk-collections
462 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
463 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
464 >     * Algorithms" (CLR).
465 >     *
466 >     * TreeBins also require an additional locking mechanism.  While
467 >     * list traversal is always possible by readers even during
468 >     * updates, tree traversal is not, mainly because of tree-rotations
469 >     * that may change the root node and/or its linkages.  TreeBins
470 >     * include a simple read-write lock mechanism parasitic on the
471 >     * main bin-synchronization strategy: Structural adjustments
472 >     * associated with an insertion or removal are already bin-locked
473 >     * (and so cannot conflict with other writers) but must wait for
474 >     * ongoing readers to finish. Since there can be only one such
475 >     * waiter, we use a simple scheme using a single "waiter" field to
476 >     * block writers.  However, readers need never block.  If the root
477 >     * lock is held, they proceed along the slow traversal path (via
478 >     * next-pointers) until the lock becomes available or the list is
479 >     * exhausted, whichever comes first. These cases are not fast, but
480 >     * maximize aggregate expected throughput.
481       *
482       * Maintaining API and serialization compatibility with previous
483       * versions of this class introduces several oddities. Mainly: We
# Line 468 | Line 487 | public class ConcurrentHashMapV8<K, V>
487       * time that we can guarantee to honor it.) We also declare an
488       * unused "Segment" class that is instantiated in minimal form
489       * only when serializing.
490 +     *
491 +     * Also, solely for compatibility with previous versions of this
492 +     * class, it extends AbstractMap, even though all of its methods
493 +     * are overridden, so it is just useless baggage.
494 +     *
495 +     * This file is organized to make things a little easier to follow
496 +     * while reading than they might otherwise: First the main static
497 +     * declarations and utilities, then fields, then main public
498 +     * methods (with a few factorings of multiple public methods into
499 +     * internal ones), then sizing methods, trees, traversers, and
500 +     * bulk operations.
501       */
502  
503      /* ---------------- Constants -------------- */
# Line 510 | Line 540 | public class ConcurrentHashMapV8<K, V>
540  
541      /**
542       * The bin count threshold for using a tree rather than list for a
543 <     * bin.  The value reflects the approximate break-even point for
544 <     * using tree-based operations.
543 >     * bin.  Bins are converted to trees when adding an element to a
544 >     * bin with at least this many nodes. The value must be greater
545 >     * than 2, and should be at least 8 to mesh with assumptions in
546 >     * tree removal about conversion back to plain bins upon
547 >     * shrinkage.
548 >     */
549 >    static final int TREEIFY_THRESHOLD = 8;
550 >
551 >    /**
552 >     * The bin count threshold for untreeifying a (split) bin during a
553 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
554 >     * most 6 to mesh with shrinkage detection under removal.
555 >     */
556 >    static final int UNTREEIFY_THRESHOLD = 6;
557 >
558 >    /**
559 >     * The smallest table capacity for which bins may be treeified.
560 >     * (Otherwise the table is resized if too many nodes in a bin.)
561 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
562 >     * conflicts between resizing and treeification thresholds.
563       */
564 <    private static final int TREE_THRESHOLD = 8;
564 >    static final int MIN_TREEIFY_CAPACITY = 64;
565  
566      /**
567       * Minimum number of rebinnings per transfer step. Ranges are
# Line 527 | Line 575 | public class ConcurrentHashMapV8<K, V>
575      /*
576       * Encodings for Node hash fields. See above for explanation.
577       */
578 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
578 >    static final int MOVED     = -1; // hash for forwarding nodes
579 >    static final int TREEBIN   = -2; // hash for roots of trees
580 >    static final int RESERVED  = -3; // hash for transient reservations
581      static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
582  
583      /** Number of CPUS, to place bounds on some sizings */
584      static final int NCPU = Runtime.getRuntime().availableProcessors();
585  
586 <    /* ---------------- Counters -------------- */
586 >    /** For serialization compatibility. */
587 >    private static final ObjectStreamField[] serialPersistentFields = {
588 >        new ObjectStreamField("segments", Segment[].class),
589 >        new ObjectStreamField("segmentMask", Integer.TYPE),
590 >        new ObjectStreamField("segmentShift", Integer.TYPE)
591 >    };
592  
593 <    // Adapted from LongAdder and Striped64.
539 <    // See their internal docs for explanation.
593 >    /* ---------------- Nodes -------------- */
594  
595 <    // A padded cell for distributing counts
596 <    static final class CounterCell {
597 <        volatile long p0, p1, p2, p3, p4, p5, p6;
598 <        volatile long value;
599 <        volatile long q0, q1, q2, q3, q4, q5, q6;
600 <        CounterCell(long x) { value = x; }
595 >    /**
596 >     * Key-value entry.  This class is never exported out as a
597 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
598 >     * MapEntry below), but can be used for read-only traversals used
599 >     * in bulk tasks.  Subclasses of Node with a negative hash field
600 >     * are special, and contain null keys and values (but are never
601 >     * exported).  Otherwise, keys and vals are never null.
602 >     */
603 >    static class Node<K,V> implements Map.Entry<K,V> {
604 >        final int hash;
605 >        final K key;
606 >        volatile V val;
607 >        volatile Node<K,V> next;
608 >
609 >        Node(int hash, K key, V val, Node<K,V> next) {
610 >            this.hash = hash;
611 >            this.key = key;
612 >            this.val = val;
613 >            this.next = next;
614 >        }
615 >
616 >        public final K getKey()       { return key; }
617 >        public final V getValue()     { return val; }
618 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
619 >        public final String toString(){ return key + "=" + val; }
620 >        public final V setValue(V value) {
621 >            throw new UnsupportedOperationException();
622 >        }
623 >
624 >        public final boolean equals(Object o) {
625 >            Object k, v, u; Map.Entry<?,?> e;
626 >            return ((o instanceof Map.Entry) &&
627 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
628 >                    (v = e.getValue()) != null &&
629 >                    (k == key || k.equals(key)) &&
630 >                    (v == (u = val) || v.equals(u)));
631 >        }
632 >
633 >        /**
634 >         * Virtualized support for map.get(); overridden in subclasses.
635 >         */
636 >        Node<K,V> find(int h, Object k) {
637 >            Node<K,V> e = this;
638 >            if (k != null) {
639 >                do {
640 >                    K ek;
641 >                    if (e.hash == h &&
642 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
643 >                        return e;
644 >                } while ((e = e.next) != null);
645 >            }
646 >            return null;
647 >        }
648      }
649  
650 +    /* ---------------- Static utilities -------------- */
651 +
652      /**
653 <     * Holder for the thread-local hash code determining which
654 <     * CounterCell to use. The code is initialized via the
655 <     * counterHashCodeGenerator, but may be moved upon collisions.
653 >     * Spreads (XORs) higher bits of hash to lower and also forces top
654 >     * bit to 0. Because the table uses power-of-two masking, sets of
655 >     * hashes that vary only in bits above the current mask will
656 >     * always collide. (Among known examples are sets of Float keys
657 >     * holding consecutive whole numbers in small tables.)  So we
658 >     * apply a transform that spreads the impact of higher bits
659 >     * downward. There is a tradeoff between speed, utility, and
660 >     * quality of bit-spreading. Because many common sets of hashes
661 >     * are already reasonably distributed (so don't benefit from
662 >     * spreading), and because we use trees to handle large sets of
663 >     * collisions in bins, we just XOR some shifted bits in the
664 >     * cheapest possible way to reduce systematic lossage, as well as
665 >     * to incorporate impact of the highest bits that would otherwise
666 >     * never be used in index calculations because of table bounds.
667       */
668 <    static final class CounterHashCode {
669 <        int code;
668 >    static final int spread(int h) {
669 >        return (h ^ (h >>> 16)) & HASH_BITS;
670      }
671  
672      /**
673 <     * Generates initial value for per-thread CounterHashCodes
673 >     * Returns a power of two table size for the given desired capacity.
674 >     * See Hackers Delight, sec 3.2
675       */
676 <    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
676 >    private static final int tableSizeFor(int c) {
677 >        int n = c - 1;
678 >        n |= n >>> 1;
679 >        n |= n >>> 2;
680 >        n |= n >>> 4;
681 >        n |= n >>> 8;
682 >        n |= n >>> 16;
683 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
684 >    }
685  
686      /**
687 <     * Increment for counterHashCodeGenerator. See class ThreadLocal
688 <     * for explanation.
687 >     * Returns x's Class if it is of the form "class C implements
688 >     * Comparable<C>", else null.
689       */
690 <    static final int SEED_INCREMENT = 0x61c88647;
690 >    static Class<?> comparableClassFor(Object x) {
691 >        if (x instanceof Comparable) {
692 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
693 >            if ((c = x.getClass()) == String.class) // bypass checks
694 >                return c;
695 >            if ((ts = c.getGenericInterfaces()) != null) {
696 >                for (int i = 0; i < ts.length; ++i) {
697 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
698 >                        ((p = (ParameterizedType)t).getRawType() ==
699 >                         Comparable.class) &&
700 >                        (as = p.getActualTypeArguments()) != null &&
701 >                        as.length == 1 && as[0] == c) // type arg is c
702 >                        return c;
703 >                }
704 >            }
705 >        }
706 >        return null;
707 >    }
708  
709      /**
710 <     * Per-thread counter hash codes. Shared across all instances.
710 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
711 >     * class), else 0.
712       */
713 <    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
714 <        new ThreadLocal<CounterHashCode>();
713 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
714 >    static int compareComparables(Class<?> kc, Object k, Object x) {
715 >        return (x == null || x.getClass() != kc ? 0 :
716 >                ((Comparable)k).compareTo(x));
717 >    }
718 >
719 >    /* ---------------- Table element access -------------- */
720 >
721 >    /*
722 >     * Volatile access methods are used for table elements as well as
723 >     * elements of in-progress next table while resizing.  All uses of
724 >     * the tab arguments must be null checked by callers.  All callers
725 >     * also paranoically precheck that tab's length is not zero (or an
726 >     * equivalent check), thus ensuring that any index argument taking
727 >     * the form of a hash value anded with (length - 1) is a valid
728 >     * index.  Note that, to be correct wrt arbitrary concurrency
729 >     * errors by users, these checks must operate on local variables,
730 >     * which accounts for some odd-looking inline assignments below.
731 >     * Note that calls to setTabAt always occur within locked regions,
732 >     * and so in principle require only release ordering, not need
733 >     * full volatile semantics, but are currently coded as volatile
734 >     * writes to be conservative.
735 >     */
736 >
737 >    @SuppressWarnings("unchecked")
738 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
739 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
740 >    }
741 >
742 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
743 >                                        Node<K,V> c, Node<K,V> v) {
744 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
745 >    }
746 >
747 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
748 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
749 >    }
750  
751      /* ---------------- Fields -------------- */
752  
# Line 578 | Line 754 | public class ConcurrentHashMapV8<K, V>
754       * The array of bins. Lazily initialized upon first insertion.
755       * Size is always a power of two. Accessed directly by iterators.
756       */
757 <    transient volatile Node<V>[] table;
757 >    transient volatile Node<K,V>[] table;
758  
759      /**
760       * The next table to use; non-null only while resizing.
761       */
762 <    private transient volatile Node<V>[] nextTable;
762 >    private transient volatile Node<K,V>[] nextTable;
763  
764      /**
765       * Base counter value, used mainly when there is no contention,
# Line 613 | Line 789 | public class ConcurrentHashMapV8<K, V>
789      private transient volatile int transferOrigin;
790  
791      /**
792 <     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
792 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
793       */
794 <    private transient volatile int counterBusy;
794 >    private transient volatile int cellsBusy;
795  
796      /**
797       * Table of counter cells. When non-null, size is a power of 2.
# Line 627 | Line 803 | public class ConcurrentHashMapV8<K, V>
803      private transient ValuesView<K,V> values;
804      private transient EntrySetView<K,V> entrySet;
805  
630    /** For serialization compatibility. Null unless serialized; see below */
631    private Segment<K,V>[] segments;
806  
807 <    /* ---------------- Table element access -------------- */
807 >    /* ---------------- Public operations -------------- */
808  
809 <    /*
810 <     * Volatile access methods are used for table elements as well as
811 <     * elements of in-progress next table while resizing.  Uses are
812 <     * 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);
809 >    /**
810 >     * Creates a new, empty map with the default initial table size (16).
811 >     */
812 >    public ConcurrentHashMapV8() {
813      }
814  
815 <    private static final <V> boolean casTabAt
816 <        (Node<V>[] tab, int i, Node<V> c, Node<V> v) {
817 <        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
815 >    /**
816 >     * Creates a new, empty map with an initial table size
817 >     * accommodating the specified number of elements without the need
818 >     * to dynamically resize.
819 >     *
820 >     * @param initialCapacity The implementation performs internal
821 >     * sizing to accommodate this many elements.
822 >     * @throws IllegalArgumentException if the initial capacity of
823 >     * elements is negative
824 >     */
825 >    public ConcurrentHashMapV8(int initialCapacity) {
826 >        if (initialCapacity < 0)
827 >            throw new IllegalArgumentException();
828 >        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
829 >                   MAXIMUM_CAPACITY :
830 >                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
831 >        this.sizeCtl = cap;
832      }
833  
834 <    private static final <V> void setTabAt
835 <        (Node<V>[] tab, int i, Node<V> v) {
836 <        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
834 >    /**
835 >     * Creates a new map with the same mappings as the given map.
836 >     *
837 >     * @param m the map
838 >     */
839 >    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
840 >        this.sizeCtl = DEFAULT_CAPACITY;
841 >        putAll(m);
842      }
843  
662    /* ---------------- Nodes -------------- */
663
844      /**
845 <     * Key-value entry. Note that this is never exported out as a
846 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
847 <     * field of MOVED are special, and do not contain user keys or
848 <     * values.  Otherwise, keys are never null, and null val fields
849 <     * indicate that a node is in the process of being deleted or
850 <     * created. For purposes of read-only access, a key may be read
851 <     * before a val, but can only be used after checking val to be
852 <     * non-null.
845 >     * Creates a new, empty map with an initial table size based on
846 >     * the given number of elements ({@code initialCapacity}) and
847 >     * initial table density ({@code loadFactor}).
848 >     *
849 >     * @param initialCapacity the initial capacity. The implementation
850 >     * performs internal sizing to accommodate this many elements,
851 >     * given the specified load factor.
852 >     * @param loadFactor the load factor (table density) for
853 >     * establishing the initial table size
854 >     * @throws IllegalArgumentException if the initial capacity of
855 >     * elements is negative or the load factor is nonpositive
856 >     *
857 >     * @since 1.6
858       */
859 <    static class Node<V> {
860 <        final int hash;
861 <        final Object key;
677 <        volatile V val;
678 <        volatile Node<V> next;
859 >    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
860 >        this(initialCapacity, loadFactor, 1);
861 >    }
862  
863 <        Node(int hash, Object key, V val, Node<V> next) {
864 <            this.hash = hash;
865 <            this.key = key;
866 <            this.val = val;
867 <            this.next = next;
868 <        }
863 >    /**
864 >     * Creates a new, empty map with an initial table size based on
865 >     * the given number of elements ({@code initialCapacity}), table
866 >     * density ({@code loadFactor}), and number of concurrently
867 >     * updating threads ({@code concurrencyLevel}).
868 >     *
869 >     * @param initialCapacity the initial capacity. The implementation
870 >     * performs internal sizing to accommodate this many elements,
871 >     * given the specified load factor.
872 >     * @param loadFactor the load factor (table density) for
873 >     * establishing the initial table size
874 >     * @param concurrencyLevel the estimated number of concurrently
875 >     * updating threads. The implementation may use this value as
876 >     * a sizing hint.
877 >     * @throws IllegalArgumentException if the initial capacity is
878 >     * negative or the load factor or concurrencyLevel are
879 >     * nonpositive
880 >     */
881 >    public ConcurrentHashMapV8(int initialCapacity,
882 >                             float loadFactor, int concurrencyLevel) {
883 >        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
884 >            throw new IllegalArgumentException();
885 >        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
886 >            initialCapacity = concurrencyLevel;   // as estimated threads
887 >        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
888 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
889 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
890 >        this.sizeCtl = cap;
891      }
892  
893 <    /* ---------------- TreeBins -------------- */
893 >    // Original (since JDK1.2) Map methods
894  
895      /**
896 <     * Nodes for use in TreeBins
896 >     * {@inheritDoc}
897       */
898 <    static final class TreeNode<V> extends Node<V> {
899 <        TreeNode<V> parent;  // red-black tree links
900 <        TreeNode<V> left;
901 <        TreeNode<V> right;
902 <        TreeNode<V> prev;    // needed to unlink next upon deletion
903 <        boolean red;
898 >    public int size() {
899 >        long n = sumCount();
900 >        return ((n < 0L) ? 0 :
901 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
902 >                (int)n);
903 >    }
904  
905 <        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
906 <            super(hash, key, val, next);
907 <            this.parent = parent;
908 <        }
905 >    /**
906 >     * {@inheritDoc}
907 >     */
908 >    public boolean isEmpty() {
909 >        return sumCount() <= 0L; // ignore transient negative values
910      }
911  
912      /**
913 <     * A specialized form of red-black tree for use in bins
914 <     * whose size exceeds a threshold.
913 >     * Returns the value to which the specified key is mapped,
914 >     * or {@code null} if this map contains no mapping for the key.
915       *
916 <     * TreeBins use a special form of comparison for search and
917 <     * related operations (which is the main reason we cannot use
918 <     * existing collections such as TreeMaps). TreeBins contain
919 <     * 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).
916 >     * <p>More formally, if this map contains a mapping from a key
917 >     * {@code k} to a value {@code v} such that {@code key.equals(k)},
918 >     * then this method returns {@code v}; otherwise it returns
919 >     * {@code null}.  (There can be at most one such mapping.)
920       *
921 <     * 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.
921 >     * @throws NullPointerException if the specified key is null
922       */
923 <    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
924 <        private static final long serialVersionUID = 2249069246763182397L;
925 <        transient TreeNode<V> root;  // root of tree
926 <        transient TreeNode<V> first; // head of next-pointer list
927 <
928 <        /* AQS overrides */
929 <        public final boolean isHeldExclusively() { return getState() > 0; }
930 <        public final boolean tryAcquire(int ignore) {
931 <            if (compareAndSetState(0, 1)) {
932 <                setExclusiveOwnerThread(Thread.currentThread());
933 <                return true;
934 <            }
935 <            return false;
936 <        }
937 <        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;
923 >    public V get(Object key) {
924 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
925 >        int h = spread(key.hashCode());
926 >        if ((tab = table) != null && (n = tab.length) > 0 &&
927 >            (e = tabAt(tab, (n - 1) & h)) != null) {
928 >            if ((eh = e.hash) == h) {
929 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
930 >                    return e.val;
931 >            }
932 >            else if (eh < 0)
933 >                return (p = e.find(h, key)) != null ? p.val : null;
934 >            while ((e = e.next) != null) {
935 >                if (e.hash == h &&
936 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
937 >                    return e.val;
938              }
939          }
940 +        return null;
941 +    }
942  
943 <        /**
944 <         * Returns the TreeNode (or null if not found) for the given key
945 <         * starting at given root.
946 <         */
947 <        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
948 <            (int h, Object k, TreeNode<V> p) {
949 <            Class<?> c = k.getClass();
950 <            while (p != null) {
951 <                int dir, ph;  Object pk; Class<?> pc;
952 <                if ((ph = p.hash) == h) {
953 <                    if ((pk = p.key) == k || k.equals(pk))
954 <                        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 <        }
943 >    /**
944 >     * Tests if the specified object is a key in this table.
945 >     *
946 >     * @param  key possible key
947 >     * @return {@code true} if and only if the specified object
948 >     *         is a key in this table, as determined by the
949 >     *         {@code equals} method; {@code false} otherwise
950 >     * @throws NullPointerException if the specified key is null
951 >     */
952 >    public boolean containsKey(Object key) {
953 >        return get(key) != null;
954 >    }
955  
956 <        /**
957 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
958 <         * read-lock to call getTreeNode, but during failure to get
959 <         * lock, searches along next links.
960 <         */
961 <        final V getValue(int h, Object k) {
962 <            Node<V> r = null;
963 <            int c = getState(); // Must read lock state first
964 <            for (Node<V> e = first; e != null; e = e.next) {
965 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
966 <                    try {
967 <                        r = getTreeNode(h, k, root);
968 <                    } finally {
969 <                        releaseShared(0);
970 <                    }
971 <                    break;
972 <                }
973 <                else if (e.hash == h && k.equals(e.key)) {
974 <                    r = e;
975 <                    break;
871 <                }
872 <                else
873 <                    c = getState();
956 >    /**
957 >     * Returns {@code true} if this map maps one or more keys to the
958 >     * specified value. Note: This method may require a full traversal
959 >     * of the map, and is much slower than method {@code containsKey}.
960 >     *
961 >     * @param value value whose presence in this map is to be tested
962 >     * @return {@code true} if this map maps one or more keys to the
963 >     *         specified value
964 >     * @throws NullPointerException if the specified value is null
965 >     */
966 >    public boolean containsValue(Object value) {
967 >        if (value == null)
968 >            throw new NullPointerException();
969 >        Node<K,V>[] t;
970 >        if ((t = table) != null) {
971 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
972 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
973 >                V v;
974 >                if ((v = p.val) == value || (v != null && value.equals(v)))
975 >                    return true;
976              }
875            return r == null ? null : r.val;
977          }
978 +        return false;
979 +    }
980  
981 <        /**
982 <         * Finds or adds a node.
983 <         * @return null if added
984 <         */
985 <        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
986 <            (int h, Object k, V v) {
987 <            Class<?> c = k.getClass();
988 <            TreeNode<V> pp = root, p = null;
989 <            int dir = 0;
990 <            while (pp != null) { // find existing node or leaf to insert at
991 <                int ph;  Object pk; Class<?> pc;
992 <                p = pp;
993 <                if ((ph = p.hash) == h) {
994 <                    if ((pk = p.key) == k || k.equals(pk))
995 <                        return p;
996 <                    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 <        }
981 >    /**
982 >     * Maps the specified key to the specified value in this table.
983 >     * Neither the key nor the value can be null.
984 >     *
985 >     * <p>The value can be retrieved by calling the {@code get} method
986 >     * with a key that is equal to the original key.
987 >     *
988 >     * @param key key with which the specified value is to be associated
989 >     * @param value value to be associated with the specified key
990 >     * @return the previous value associated with {@code key}, or
991 >     *         {@code null} if there was no mapping for {@code key}
992 >     * @throws NullPointerException if the specified key or value is null
993 >     */
994 >    public V put(K key, V value) {
995 >        return putVal(key, value, false);
996 >    }
997  
998 <        /**
999 <         * Removes the given node, that must be present before this
1000 <         * call.  This is messier than typical red-black deletion code
1001 <         * because we cannot swap the contents of an interior node
1002 <         * with a leaf successor that is pinned by "next" pointers
1003 <         * that are accessible independently of lock. So instead we
1004 <         * swap the tree linkages.
1005 <         */
1006 <        final void deleteTreeNode(TreeNode<V> p) {
1007 <            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
1008 <            TreeNode<V> pred = p.prev;
1009 <            if (pred == null)
1010 <                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;
998 >    /** Implementation for put and putIfAbsent */
999 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
1000 >        if (key == null || value == null) throw new NullPointerException();
1001 >        int hash = spread(key.hashCode());
1002 >        int binCount = 0;
1003 >        for (Node<K,V>[] tab = table;;) {
1004 >            Node<K,V> f; int n, i, fh;
1005 >            if (tab == null || (n = tab.length) == 0)
1006 >                tab = initTable();
1007 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
1008 >                if (casTabAt(tab, i, null,
1009 >                             new Node<K,V>(hash, key, value, null)))
1010 >                    break;                   // no lock when adding to empty bin
1011              }
1012 +            else if ((fh = f.hash) == MOVED)
1013 +                tab = helpTransfer(tab, f);
1014              else {
1015 <                replacement.parent = pp;
1016 <                if (pp == null)
1017 <                    root = replacement;
1018 <                else if (p == pp.left)
1019 <                    pp.left = replacement;
1020 <                else
1021 <                    pp.right = replacement;
1022 <                p.left = p.right = p.parent = null;
1023 <            }
1024 <            if (!p.red) { // rebalance, from CLR
1025 <                TreeNode<V> x = replacement;
1026 <                while (x != null) {
1027 <                    TreeNode<V> xp, xpl;
1028 <                    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;
1015 >                V oldVal = null;
1016 >                synchronized (f) {
1017 >                    if (tabAt(tab, i) == f) {
1018 >                        if (fh >= 0) {
1019 >                            binCount = 1;
1020 >                            for (Node<K,V> e = f;; ++binCount) {
1021 >                                K ek;
1022 >                                if (e.hash == hash &&
1023 >                                    ((ek = e.key) == key ||
1024 >                                     (ek != null && key.equals(ek)))) {
1025 >                                    oldVal = e.val;
1026 >                                    if (!onlyIfAbsent)
1027 >                                        e.val = value;
1028 >                                    break;
1029                                  }
1030 <                                if (xp != null) {
1031 <                                    xp.red = false;
1032 <                                    rotateLeft(xp);
1030 >                                Node<K,V> pred = e;
1031 >                                if ((e = e.next) == null) {
1032 >                                    pred.next = new Node<K,V>(hash, key,
1033 >                                                              value, null);
1034 >                                    break;
1035                                  }
1102                                x = root;
1036                              }
1037                          }
1038 <                    }
1039 <                    else { // symmetric
1040 <                        TreeNode<V> sib = xpl;
1041 <                        if (sib != null && sib.red) {
1042 <                            sib.red = false;
1043 <                            xp.red = true;
1044 <                            rotateRight(xp);
1045 <                            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;
1038 >                        else if (f instanceof TreeBin) {
1039 >                            Node<K,V> p;
1040 >                            binCount = 2;
1041 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1042 >                                                           value)) != null) {
1043 >                                oldVal = p.val;
1044 >                                if (!onlyIfAbsent)
1045 >                                    p.val = value;
1046                              }
1047                          }
1048                      }
1049                  }
1050 <            }
1051 <            if (p == replacement && (pp = p.parent) != null) {
1052 <                if (p == pp.left) // detach pointers
1053 <                    pp.left = null;
1054 <                else if (p == pp.right)
1055 <                    pp.right = null;
1056 <                p.parent = null;
1050 >                if (binCount != 0) {
1051 >                    if (binCount >= TREEIFY_THRESHOLD)
1052 >                        treeifyBin(tab, i);
1053 >                    if (oldVal != null)
1054 >                        return oldVal;
1055 >                    break;
1056 >                }
1057              }
1058          }
1059 +        addCount(1L, binCount);
1060 +        return null;
1061      }
1062  
1157    /* ---------------- Collision reduction methods -------------- */
1158
1063      /**
1064 <     * Spreads higher bits to lower, and also forces top bit to 0.
1065 <     * Because the table uses power-of-two masking, sets of hashes
1066 <     * that vary only in bits above the current mask will always
1067 <     * collide. (Among known examples are sets of Float keys holding
1068 <     * 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.
1064 >     * Copies all of the mappings from the specified map to this one.
1065 >     * These mappings replace any mappings that this map had for any of the
1066 >     * keys currently in the specified map.
1067 >     *
1068 >     * @param m mappings to be stored in this map
1069       */
1070 <    private static final int spread(int h) {
1071 <        h ^= (h >>> 18) ^ (h >>> 12);
1072 <        return (h ^ (h >>> 10)) & HASH_BITS;
1070 >    public void putAll(Map<? extends K, ? extends V> m) {
1071 >        tryPresize(m.size());
1072 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1073 >            putVal(e.getKey(), e.getValue(), false);
1074      }
1075  
1076      /**
1077 <     * Replaces a list bin with a tree bin if key is comparable.  Call
1078 <     * only when locked.
1077 >     * Removes the key (and its corresponding value) from this map.
1078 >     * This method does nothing if the key is not in the map.
1079 >     *
1080 >     * @param  key the key that needs to be removed
1081 >     * @return the previous value associated with {@code key}, or
1082 >     *         {@code null} if there was no mapping for {@code key}
1083 >     * @throws NullPointerException if the specified key is null
1084       */
1085 <    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1086 <        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;
1085 >    public V remove(Object key) {
1086 >        return replaceNode(key, null, null);
1087      }
1088  
1089      /**
# Line 1217 | Line 1091 | public class ConcurrentHashMapV8<K, V>
1091       * Replaces node value with v, conditional upon match of cv if
1092       * non-null.  If resulting value is null, delete.
1093       */
1094 <    @SuppressWarnings("unchecked") private final V internalReplace
1095 <        (Object k, V v, Object cv) {
1096 <        int h = spread(k.hashCode());
1097 <        V oldVal = null;
1098 <        for (Node<V>[] tab = table;;) {
1099 <            Node<V> f; int i, fh; Object fk;
1226 <            if (tab == null ||
1227 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1094 >    final V replaceNode(Object key, V value, Object cv) {
1095 >        int hash = spread(key.hashCode());
1096 >        for (Node<K,V>[] tab = table;;) {
1097 >            Node<K,V> f; int n, i, fh;
1098 >            if (tab == null || (n = tab.length) == 0 ||
1099 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1100                  break;
1101 <            else if ((fh = f.hash) < 0) {
1102 <                if ((fk = f.key) instanceof TreeBin) {
1103 <                    TreeBin<V> t = (TreeBin<V>)fk;
1104 <                    boolean validated = false;
1105 <                    boolean deleted = false;
1106 <                    t.acquire(0);
1107 <                    try {
1108 <                        if (tabAt(tab, i) == f) {
1101 >            else if ((fh = f.hash) == MOVED)
1102 >                tab = helpTransfer(tab, f);
1103 >            else {
1104 >                V oldVal = null;
1105 >                boolean validated = false;
1106 >                synchronized (f) {
1107 >                    if (tabAt(tab, i) == f) {
1108 >                        if (fh >= 0) {
1109 >                            validated = true;
1110 >                            for (Node<K,V> e = f, pred = null;;) {
1111 >                                K ek;
1112 >                                if (e.hash == hash &&
1113 >                                    ((ek = e.key) == key ||
1114 >                                     (ek != null && key.equals(ek)))) {
1115 >                                    V ev = e.val;
1116 >                                    if (cv == null || cv == ev ||
1117 >                                        (ev != null && cv.equals(ev))) {
1118 >                                        oldVal = ev;
1119 >                                        if (value != null)
1120 >                                            e.val = value;
1121 >                                        else if (pred != null)
1122 >                                            pred.next = e.next;
1123 >                                        else
1124 >                                            setTabAt(tab, i, e.next);
1125 >                                    }
1126 >                                    break;
1127 >                                }
1128 >                                pred = e;
1129 >                                if ((e = e.next) == null)
1130 >                                    break;
1131 >                            }
1132 >                        }
1133 >                        else if (f instanceof TreeBin) {
1134                              validated = true;
1135 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1136 <                            if (p != null) {
1135 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1136 >                            TreeNode<K,V> r, p;
1137 >                            if ((r = t.root) != null &&
1138 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1139                                  V pv = p.val;
1140 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1140 >                                if (cv == null || cv == pv ||
1141 >                                    (pv != null && cv.equals(pv))) {
1142                                      oldVal = pv;
1143 <                                    if ((p.val = v) == null) {
1144 <                                        deleted = true;
1145 <                                        t.deleteTreeNode(p);
1146 <                                    }
1143 >                                    if (value != null)
1144 >                                        p.val = value;
1145 >                                    else if (t.removeTreeNode(p))
1146 >                                        setTabAt(tab, i, untreeify(t.first));
1147                                  }
1148                              }
1149                          }
1250                    } finally {
1251                        t.release(0);
1150                      }
1151 <                    if (validated) {
1152 <                        if (deleted)
1151 >                }
1152 >                if (validated) {
1153 >                    if (oldVal != null) {
1154 >                        if (value == null)
1155                              addCount(-1L, -1);
1156 <                        break;
1156 >                        return oldVal;
1157                      }
1158 +                    break;
1159                  }
1259                else
1260                    tab = (Node<V>[])fk;
1160              }
1161 <            else if (fh != h && f.next == null) // precheck
1162 <                break;                          // rules out possible existence
1161 >        }
1162 >        return null;
1163 >    }
1164 >
1165 >    /**
1166 >     * Removes all of the mappings from this map.
1167 >     */
1168 >    public void clear() {
1169 >        long delta = 0L; // negative number of deletions
1170 >        int i = 0;
1171 >        Node<K,V>[] tab = table;
1172 >        while (tab != null && i < tab.length) {
1173 >            int fh;
1174 >            Node<K,V> f = tabAt(tab, i);
1175 >            if (f == null)
1176 >                ++i;
1177 >            else if ((fh = f.hash) == MOVED) {
1178 >                tab = helpTransfer(tab, f);
1179 >                i = 0; // restart
1180 >            }
1181              else {
1265                boolean validated = false;
1266                boolean deleted = false;
1182                  synchronized (f) {
1183                      if (tabAt(tab, i) == f) {
1184 <                        validated = true;
1185 <                        for (Node<V> e = f, pred = null;;) {
1186 <                            Object ek; V ev;
1187 <                            if (e.hash == h &&
1188 <                                ((ev = e.val) != null) &&
1189 <                                ((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;
1184 >                        Node<K,V> p = (fh >= 0 ? f :
1185 >                                       (f instanceof TreeBin) ?
1186 >                                       ((TreeBin<K,V>)f).first : null);
1187 >                        while (p != null) {
1188 >                            --delta;
1189 >                            p = p.next;
1190                          }
1191 +                        setTabAt(tab, i++, null);
1192                      }
1193                  }
1194 <                if (validated) {
1195 <                    if (deleted)
1196 <                        addCount(-1L, -1);
1194 >            }
1195 >        }
1196 >        if (delta != 0L)
1197 >            addCount(delta, -1);
1198 >    }
1199 >
1200 >    /**
1201 >     * Returns a {@link Set} view of the keys contained in this map.
1202 >     * The set is backed by the map, so changes to the map are
1203 >     * reflected in the set, and vice-versa. The set supports element
1204 >     * removal, which removes the corresponding mapping from this map,
1205 >     * via the {@code Iterator.remove}, {@code Set.remove},
1206 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1207 >     * operations.  It does not support the {@code add} or
1208 >     * {@code addAll} operations.
1209 >     *
1210 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1211 >     * that will never throw {@link ConcurrentModificationException},
1212 >     * and guarantees to traverse elements as they existed upon
1213 >     * construction of the iterator, and may (but is not guaranteed to)
1214 >     * reflect any modifications subsequent to construction.
1215 >     *
1216 >     * @return the set view
1217 >     */
1218 >    public KeySetView<K,V> keySet() {
1219 >        KeySetView<K,V> ks;
1220 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1221 >    }
1222 >
1223 >    /**
1224 >     * Returns a {@link Collection} view of the values contained in this map.
1225 >     * The collection is backed by the map, so changes to the map are
1226 >     * reflected in the collection, and vice-versa.  The collection
1227 >     * supports element removal, which removes the corresponding
1228 >     * mapping from this map, via the {@code Iterator.remove},
1229 >     * {@code Collection.remove}, {@code removeAll},
1230 >     * {@code retainAll}, and {@code clear} operations.  It does not
1231 >     * support the {@code add} or {@code addAll} operations.
1232 >     *
1233 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1234 >     * that will never throw {@link ConcurrentModificationException},
1235 >     * and guarantees to traverse elements as they existed upon
1236 >     * construction of the iterator, and may (but is not guaranteed to)
1237 >     * reflect any modifications subsequent to construction.
1238 >     *
1239 >     * @return the collection view
1240 >     */
1241 >    public Collection<V> values() {
1242 >        ValuesView<K,V> vs;
1243 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1244 >    }
1245 >
1246 >    /**
1247 >     * Returns a {@link Set} view of the mappings contained in this map.
1248 >     * The set is backed by the map, so changes to the map are
1249 >     * reflected in the set, and vice-versa.  The set supports element
1250 >     * removal, which removes the corresponding mapping from the map,
1251 >     * via the {@code Iterator.remove}, {@code Set.remove},
1252 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1253 >     * operations.
1254 >     *
1255 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1256 >     * that will never throw {@link ConcurrentModificationException},
1257 >     * and guarantees to traverse elements as they existed upon
1258 >     * construction of the iterator, and may (but is not guaranteed to)
1259 >     * reflect any modifications subsequent to construction.
1260 >     *
1261 >     * @return the set view
1262 >     */
1263 >    public Set<Map.Entry<K,V>> entrySet() {
1264 >        EntrySetView<K,V> es;
1265 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1266 >    }
1267 >
1268 >    /**
1269 >     * Returns the hash code value for this {@link Map}, i.e.,
1270 >     * the sum of, for each key-value pair in the map,
1271 >     * {@code key.hashCode() ^ value.hashCode()}.
1272 >     *
1273 >     * @return the hash code value for this map
1274 >     */
1275 >    public int hashCode() {
1276 >        int h = 0;
1277 >        Node<K,V>[] t;
1278 >        if ((t = table) != null) {
1279 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1280 >            for (Node<K,V> p; (p = it.advance()) != null; )
1281 >                h += p.key.hashCode() ^ p.val.hashCode();
1282 >        }
1283 >        return h;
1284 >    }
1285 >
1286 >    /**
1287 >     * Returns a string representation of this map.  The string
1288 >     * representation consists of a list of key-value mappings (in no
1289 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1290 >     * mappings are separated by the characters {@code ", "} (comma
1291 >     * and space).  Each key-value mapping is rendered as the key
1292 >     * followed by an equals sign ("{@code =}") followed by the
1293 >     * associated value.
1294 >     *
1295 >     * @return a string representation of this map
1296 >     */
1297 >    public String toString() {
1298 >        Node<K,V>[] t;
1299 >        int f = (t = table) == null ? 0 : t.length;
1300 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1301 >        StringBuilder sb = new StringBuilder();
1302 >        sb.append('{');
1303 >        Node<K,V> p;
1304 >        if ((p = it.advance()) != null) {
1305 >            for (;;) {
1306 >                K k = p.key;
1307 >                V v = p.val;
1308 >                sb.append(k == this ? "(this Map)" : k);
1309 >                sb.append('=');
1310 >                sb.append(v == this ? "(this Map)" : v);
1311 >                if ((p = it.advance()) == null)
1312                      break;
1313 <                }
1313 >                sb.append(',').append(' ');
1314              }
1315          }
1316 <        return oldVal;
1316 >        return sb.append('}').toString();
1317      }
1318  
1319 <    /*
1320 <     * Internal versions of insertion methods
1321 <     * All have the same basic structure as the first (internalPut):
1322 <     *  1. If table uninitialized, create
1323 <     *  2. If bin empty, try to CAS new node
1324 <     *  3. If bin stale, use new table
1325 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1326 <     *  5. Lock and validate; if valid, scan and add or update
1327 <     *
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.
1319 >    /**
1320 >     * Compares the specified object with this map for equality.
1321 >     * Returns {@code true} if the given object is a map with the same
1322 >     * mappings as this map.  This operation may return misleading
1323 >     * results if either map is concurrently modified during execution
1324 >     * of this method.
1325 >     *
1326 >     * @param o object to be compared for equality with this map
1327 >     * @return {@code true} if the specified object is equal to this map
1328       */
1329 +    public boolean equals(Object o) {
1330 +        if (o != this) {
1331 +            if (!(o instanceof Map))
1332 +                return false;
1333 +            Map<?,?> m = (Map<?,?>) o;
1334 +            Node<K,V>[] t;
1335 +            int f = (t = table) == null ? 0 : t.length;
1336 +            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1337 +            for (Node<K,V> p; (p = it.advance()) != null; ) {
1338 +                V val = p.val;
1339 +                Object v = m.get(p.key);
1340 +                if (v == null || (v != val && !v.equals(val)))
1341 +                    return false;
1342 +            }
1343 +            for (Map.Entry<?,?> e : m.entrySet()) {
1344 +                Object mk, mv, v;
1345 +                if ((mk = e.getKey()) == null ||
1346 +                    (mv = e.getValue()) == null ||
1347 +                    (v = get(mk)) == null ||
1348 +                    (mv != v && !mv.equals(v)))
1349 +                    return false;
1350 +            }
1351 +        }
1352 +        return true;
1353 +    }
1354  
1355 <    /** Implementation for put and putIfAbsent */
1356 <    @SuppressWarnings("unchecked") private final V internalPut
1357 <        (K k, V v, boolean onlyIfAbsent) {
1358 <        if (k == null || v == null) throw new NullPointerException();
1359 <        int h = spread(k.hashCode());
1360 <        int len = 0;
1361 <        for (Node<V>[] tab = table;;) {
1362 <            int i, fh; Node<V> f; Object fk; V fv;
1363 <            if (tab == null)
1364 <                tab = initTable();
1365 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1366 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1367 <                    break;                   // no lock when adding to empty bin
1355 >    /**
1356 >     * Stripped-down version of helper class used in previous version,
1357 >     * declared for the sake of serialization compatibility
1358 >     */
1359 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1360 >        private static final long serialVersionUID = 2249069246763182397L;
1361 >        final float loadFactor;
1362 >        Segment(float lf) { this.loadFactor = lf; }
1363 >    }
1364 >
1365 >    /**
1366 >     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
1367 >     * stream (i.e., serializes it).
1368 >     * @param s the stream
1369 >     * @throws java.io.IOException if an I/O error occurs
1370 >     * @serialData
1371 >     * the key (Object) and value (Object)
1372 >     * for each key-value mapping, followed by a null pair.
1373 >     * The key-value mappings are emitted in no particular order.
1374 >     */
1375 >    private void writeObject(java.io.ObjectOutputStream s)
1376 >        throws java.io.IOException {
1377 >        // For serialization compatibility
1378 >        // Emulate segment calculation from previous version of this class
1379 >        int sshift = 0;
1380 >        int ssize = 1;
1381 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1382 >            ++sshift;
1383 >            ssize <<= 1;
1384 >        }
1385 >        int segmentShift = 32 - sshift;
1386 >        int segmentMask = ssize - 1;
1387 >        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1388 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1389 >        for (int i = 0; i < segments.length; ++i)
1390 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1391 >        s.putFields().put("segments", segments);
1392 >        s.putFields().put("segmentShift", segmentShift);
1393 >        s.putFields().put("segmentMask", segmentMask);
1394 >        s.writeFields();
1395 >
1396 >        Node<K,V>[] t;
1397 >        if ((t = table) != null) {
1398 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1399 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1400 >                s.writeObject(p.key);
1401 >                s.writeObject(p.val);
1402              }
1403 <            else if ((fh = f.hash) < 0) {
1404 <                if ((fk = f.key) instanceof TreeBin) {
1405 <                    TreeBin<V> t = (TreeBin<V>)fk;
1406 <                    V oldVal = null;
1407 <                    t.acquire(0);
1408 <                    try {
1409 <                        if (tabAt(tab, i) == f) {
1410 <                            len = 2;
1411 <                            TreeNode<V> p = t.putTreeNode(h, k, v);
1412 <                            if (p != null) {
1413 <                                oldVal = p.val;
1414 <                                if (!onlyIfAbsent)
1415 <                                    p.val = v;
1416 <                            }
1417 <                        }
1418 <                    } finally {
1419 <                        t.release(0);
1420 <                    }
1421 <                    if (len != 0) {
1422 <                        if (oldVal != null)
1423 <                            return oldVal;
1424 <                        break;
1425 <                    }
1426 <                }
1427 <                else
1428 <                    tab = (Node<V>[])fk;
1403 >        }
1404 >        s.writeObject(null);
1405 >        s.writeObject(null);
1406 >        segments = null; // throw away
1407 >    }
1408 >
1409 >    /**
1410 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1411 >     * @param s the stream
1412 >     * @throws ClassNotFoundException if the class of a serialized object
1413 >     *         could not be found
1414 >     * @throws java.io.IOException if an I/O error occurs
1415 >     */
1416 >    private void readObject(java.io.ObjectInputStream s)
1417 >        throws java.io.IOException, ClassNotFoundException {
1418 >        /*
1419 >         * To improve performance in typical cases, we create nodes
1420 >         * while reading, then place in table once size is known.
1421 >         * However, we must also validate uniqueness and deal with
1422 >         * overpopulated bins while doing so, which requires
1423 >         * specialized versions of putVal mechanics.
1424 >         */
1425 >        sizeCtl = -1; // force exclusion for table construction
1426 >        s.defaultReadObject();
1427 >        long size = 0L;
1428 >        Node<K,V> p = null;
1429 >        for (;;) {
1430 >            @SuppressWarnings("unchecked") K k = (K) s.readObject();
1431 >            @SuppressWarnings("unchecked") V v = (V) s.readObject();
1432 >            if (k != null && v != null) {
1433 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1434 >                ++size;
1435              }
1436 <            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1437 <                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1438 <                return fv;
1436 >            else
1437 >                break;
1438 >        }
1439 >        if (size == 0L)
1440 >            sizeCtl = 0;
1441 >        else {
1442 >            int n;
1443 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1444 >                n = MAXIMUM_CAPACITY;
1445              else {
1446 <                V oldVal = null;
1447 <                synchronized (f) {
1448 <                    if (tabAt(tab, i) == f) {
1449 <                        len = 1;
1450 <                        for (Node<V> e = f;; ++len) {
1451 <                            Object ek; V ev;
1452 <                            if (e.hash == h &&
1453 <                                (ev = e.val) != null &&
1454 <                                ((ek = e.key) == k || k.equals(ek))) {
1455 <                                oldVal = ev;
1456 <                                if (!onlyIfAbsent)
1457 <                                    e.val = v;
1446 >                int sz = (int)size;
1447 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1448 >            }
1449 >            @SuppressWarnings({"rawtypes","unchecked"})
1450 >                Node<K,V>[] tab = (Node<K,V>[])new Node[n];
1451 >            int mask = n - 1;
1452 >            long added = 0L;
1453 >            while (p != null) {
1454 >                boolean insertAtFront;
1455 >                Node<K,V> next = p.next, first;
1456 >                int h = p.hash, j = h & mask;
1457 >                if ((first = tabAt(tab, j)) == null)
1458 >                    insertAtFront = true;
1459 >                else {
1460 >                    K k = p.key;
1461 >                    if (first.hash < 0) {
1462 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1463 >                        if (t.putTreeVal(h, k, p.val) == null)
1464 >                            ++added;
1465 >                        insertAtFront = false;
1466 >                    }
1467 >                    else {
1468 >                        int binCount = 0;
1469 >                        insertAtFront = true;
1470 >                        Node<K,V> q; K qk;
1471 >                        for (q = first; q != null; q = q.next) {
1472 >                            if (q.hash == h &&
1473 >                                ((qk = q.key) == k ||
1474 >                                 (qk != null && k.equals(qk)))) {
1475 >                                insertAtFront = false;
1476                                  break;
1477                              }
1478 <                            Node<V> last = e;
1479 <                            if ((e = e.next) == null) {
1480 <                                last.next = new Node<V>(h, k, v, null);
1481 <                                if (len >= TREE_THRESHOLD)
1482 <                                    replaceWithTreeBin(tab, i, k);
1483 <                                break;
1478 >                            ++binCount;
1479 >                        }
1480 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1481 >                            insertAtFront = false;
1482 >                            ++added;
1483 >                            p.next = first;
1484 >                            TreeNode<K,V> hd = null, tl = null;
1485 >                            for (q = p; q != null; q = q.next) {
1486 >                                TreeNode<K,V> t = new TreeNode<K,V>
1487 >                                    (q.hash, q.key, q.val, null, null);
1488 >                                if ((t.prev = tl) == null)
1489 >                                    hd = t;
1490 >                                else
1491 >                                    tl.next = t;
1492 >                                tl = t;
1493                              }
1494 +                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1495                          }
1496                      }
1497                  }
1498 <                if (len != 0) {
1499 <                    if (oldVal != null)
1500 <                        return oldVal;
1501 <                    break;
1498 >                if (insertAtFront) {
1499 >                    ++added;
1500 >                    p.next = first;
1501 >                    setTabAt(tab, j, p);
1502                  }
1503 +                p = next;
1504              }
1505 +            table = tab;
1506 +            sizeCtl = n - (n >>> 2);
1507 +            baseCount = added;
1508          }
1398        addCount(1L, len);
1399        return null;
1509      }
1510  
1511 <    /** Implementation for computeIfAbsent */
1512 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1513 <        (K k, Fun<? super K, ? extends V> mf) {
1514 <        if (k == null || mf == null)
1511 >    // ConcurrentMap methods
1512 >
1513 >    /**
1514 >     * {@inheritDoc}
1515 >     *
1516 >     * @return the previous value associated with the specified key,
1517 >     *         or {@code null} if there was no mapping for the key
1518 >     * @throws NullPointerException if the specified key or value is null
1519 >     */
1520 >    public V putIfAbsent(K key, V value) {
1521 >        return putVal(key, value, true);
1522 >    }
1523 >
1524 >    /**
1525 >     * {@inheritDoc}
1526 >     *
1527 >     * @throws NullPointerException if the specified key is null
1528 >     */
1529 >    public boolean remove(Object key, Object value) {
1530 >        if (key == null)
1531 >            throw new NullPointerException();
1532 >        return value != null && replaceNode(key, null, value) != null;
1533 >    }
1534 >
1535 >    /**
1536 >     * {@inheritDoc}
1537 >     *
1538 >     * @throws NullPointerException if any of the arguments are null
1539 >     */
1540 >    public boolean replace(K key, V oldValue, V newValue) {
1541 >        if (key == null || oldValue == null || newValue == null)
1542 >            throw new NullPointerException();
1543 >        return replaceNode(key, newValue, oldValue) != null;
1544 >    }
1545 >
1546 >    /**
1547 >     * {@inheritDoc}
1548 >     *
1549 >     * @return the previous value associated with the specified key,
1550 >     *         or {@code null} if there was no mapping for the key
1551 >     * @throws NullPointerException if the specified key or value is null
1552 >     */
1553 >    public V replace(K key, V value) {
1554 >        if (key == null || value == null)
1555              throw new NullPointerException();
1556 <        int h = spread(k.hashCode());
1556 >        return replaceNode(key, value, null);
1557 >    }
1558 >
1559 >    // Overrides of JDK8+ Map extension method defaults
1560 >
1561 >    /**
1562 >     * Returns the value to which the specified key is mapped, or the
1563 >     * given default value if this map contains no mapping for the
1564 >     * key.
1565 >     *
1566 >     * @param key the key whose associated value is to be returned
1567 >     * @param defaultValue the value to return if this map contains
1568 >     * no mapping for the given key
1569 >     * @return the mapping for the key, if present; else the default value
1570 >     * @throws NullPointerException if the specified key is null
1571 >     */
1572 >    public V getOrDefault(Object key, V defaultValue) {
1573 >        V v;
1574 >        return (v = get(key)) == null ? defaultValue : v;
1575 >    }
1576 >
1577 >    public void forEach(BiAction<? super K, ? super V> action) {
1578 >        if (action == 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 >                action.apply(p.key, p.val);
1584 >            }
1585 >        }
1586 >    }
1587 >
1588 >    public void replaceAll(BiFun<? super K, ? super V, ? extends V> function) {
1589 >        if (function == null) throw new NullPointerException();
1590 >        Node<K,V>[] t;
1591 >        if ((t = table) != null) {
1592 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1593 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1594 >                V oldValue = p.val;
1595 >                for (K key = p.key;;) {
1596 >                    V newValue = function.apply(key, oldValue);
1597 >                    if (newValue == null)
1598 >                        throw new NullPointerException();
1599 >                    if (replaceNode(key, newValue, oldValue) != null ||
1600 >                        (oldValue = get(key)) == null)
1601 >                        break;
1602 >                }
1603 >            }
1604 >        }
1605 >    }
1606 >
1607 >    /**
1608 >     * If the specified key is not already associated with a value,
1609 >     * attempts to compute its value using the given mapping function
1610 >     * and enters it into this map unless {@code null}.  The entire
1611 >     * method invocation is performed atomically, so the function is
1612 >     * applied at most once per key.  Some attempted update operations
1613 >     * on this map by other threads may be blocked while computation
1614 >     * is in progress, so the computation should be short and simple,
1615 >     * and must not attempt to update any other mappings of this map.
1616 >     *
1617 >     * @param key key with which the specified value is to be associated
1618 >     * @param mappingFunction the function to compute a value
1619 >     * @return the current (existing or computed) value associated with
1620 >     *         the specified key, or null if the computed value is null
1621 >     * @throws NullPointerException if the specified key or mappingFunction
1622 >     *         is null
1623 >     * @throws IllegalStateException if the computation detectably
1624 >     *         attempts a recursive update to this map that would
1625 >     *         otherwise never complete
1626 >     * @throws RuntimeException or Error if the mappingFunction does so,
1627 >     *         in which case the mapping is left unestablished
1628 >     */
1629 >    public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
1630 >        if (key == null || mappingFunction == null)
1631 >            throw new NullPointerException();
1632 >        int h = spread(key.hashCode());
1633          V val = null;
1634 <        int len = 0;
1635 <        for (Node<V>[] tab = table;;) {
1636 <            Node<V> f; int i; Object fk;
1637 <            if (tab == null)
1634 >        int binCount = 0;
1635 >        for (Node<K,V>[] tab = table;;) {
1636 >            Node<K,V> f; int n, i, fh;
1637 >            if (tab == null || (n = tab.length) == 0)
1638                  tab = initTable();
1639 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1640 <                Node<V> node = new Node<V>(h, k, null, null);
1641 <                synchronized (node) {
1642 <                    if (casTabAt(tab, i, null, node)) {
1643 <                        len = 1;
1639 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1640 >                Node<K,V> r = new ReservationNode<K,V>();
1641 >                synchronized (r) {
1642 >                    if (casTabAt(tab, i, null, r)) {
1643 >                        binCount = 1;
1644 >                        Node<K,V> node = null;
1645                          try {
1646 <                            if ((val = mf.apply(k)) != null)
1647 <                                node.val = val;
1646 >                            if ((val = mappingFunction.apply(key)) != null)
1647 >                                node = new Node<K,V>(h, key, val, null);
1648                          } finally {
1649 <                            if (val == null)
1424 <                                setTabAt(tab, i, null);
1649 >                            setTabAt(tab, i, node);
1650                          }
1651                      }
1652                  }
1653 <                if (len != 0)
1653 >                if (binCount != 0)
1654                      break;
1655              }
1656 <            else if (f.hash < 0) {
1657 <                if ((fk = f.key) instanceof TreeBin) {
1658 <                    TreeBin<V> t = (TreeBin<V>)fk;
1659 <                    boolean added = false;
1660 <                    t.acquire(0);
1661 <                    try {
1662 <                        if (tabAt(tab, i) == f) {
1663 <                            len = 1;
1664 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1665 <                            if (p != null)
1656 >            else if ((fh = f.hash) == MOVED)
1657 >                tab = helpTransfer(tab, f);
1658 >            else {
1659 >                boolean added = false;
1660 >                synchronized (f) {
1661 >                    if (tabAt(tab, i) == f) {
1662 >                        if (fh >= 0) {
1663 >                            binCount = 1;
1664 >                            for (Node<K,V> e = f;; ++binCount) {
1665 >                                K ek; V ev;
1666 >                                if (e.hash == h &&
1667 >                                    ((ek = e.key) == key ||
1668 >                                     (ek != null && key.equals(ek)))) {
1669 >                                    val = e.val;
1670 >                                    break;
1671 >                                }
1672 >                                Node<K,V> pred = e;
1673 >                                if ((e = e.next) == null) {
1674 >                                    if ((val = mappingFunction.apply(key)) != null) {
1675 >                                        added = true;
1676 >                                        pred.next = new Node<K,V>(h, key, val, null);
1677 >                                    }
1678 >                                    break;
1679 >                                }
1680 >                            }
1681 >                        }
1682 >                        else if (f instanceof TreeBin) {
1683 >                            binCount = 2;
1684 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1685 >                            TreeNode<K,V> r, p;
1686 >                            if ((r = t.root) != null &&
1687 >                                (p = r.findTreeNode(h, key, null)) != null)
1688                                  val = p.val;
1689 <                            else if ((val = mf.apply(k)) != null) {
1689 >                            else if ((val = mappingFunction.apply(key)) != null) {
1690                                  added = true;
1691 <                                len = 2;
1445 <                                t.putTreeNode(h, k, val);
1691 >                                t.putTreeVal(h, key, val);
1692                              }
1693                          }
1448                    } finally {
1449                        t.release(0);
1450                    }
1451                    if (len != 0) {
1452                        if (!added)
1453                            return val;
1454                        break;
1694                      }
1695                  }
1696 <                else
1697 <                    tab = (Node<V>[])fk;
1696 >                if (binCount != 0) {
1697 >                    if (binCount >= TREEIFY_THRESHOLD)
1698 >                        treeifyBin(tab, i);
1699 >                    if (!added)
1700 >                        return val;
1701 >                    break;
1702 >                }
1703              }
1704 +        }
1705 +        if (val != null)
1706 +            addCount(1L, binCount);
1707 +        return val;
1708 +    }
1709 +
1710 +    /**
1711 +     * If the value for the specified key is present, attempts to
1712 +     * compute a new mapping given the key and its current mapped
1713 +     * value.  The entire method invocation is performed atomically.
1714 +     * Some attempted update operations on this map by other threads
1715 +     * may be blocked while computation is in progress, so the
1716 +     * computation should be short and simple, and must not attempt to
1717 +     * update any other mappings of this map.
1718 +     *
1719 +     * @param key key with which a value may be associated
1720 +     * @param remappingFunction the function to compute a value
1721 +     * @return the new value associated with the specified key, or null if none
1722 +     * @throws NullPointerException if the specified key or remappingFunction
1723 +     *         is null
1724 +     * @throws IllegalStateException if the computation detectably
1725 +     *         attempts a recursive update to this map that would
1726 +     *         otherwise never complete
1727 +     * @throws RuntimeException or Error if the remappingFunction does so,
1728 +     *         in which case the mapping is unchanged
1729 +     */
1730 +    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1731 +        if (key == null || remappingFunction == null)
1732 +            throw new NullPointerException();
1733 +        int h = spread(key.hashCode());
1734 +        V val = null;
1735 +        int delta = 0;
1736 +        int binCount = 0;
1737 +        for (Node<K,V>[] tab = table;;) {
1738 +            Node<K,V> f; int n, i, fh;
1739 +            if (tab == null || (n = tab.length) == 0)
1740 +                tab = initTable();
1741 +            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1742 +                break;
1743 +            else if ((fh = f.hash) == MOVED)
1744 +                tab = helpTransfer(tab, f);
1745              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;
1746                  synchronized (f) {
1747                      if (tabAt(tab, i) == f) {
1748 <                        len = 1;
1749 <                        for (Node<V> e = f;; ++len) {
1750 <                            Object ek; V ev;
1751 <                            if (e.hash == h &&
1752 <                                (ev = e.val) != null &&
1753 <                                ((ek = e.key) == k || k.equals(ek))) {
1754 <                                val = ev;
1755 <                                break;
1748 >                        if (fh >= 0) {
1749 >                            binCount = 1;
1750 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1751 >                                K ek;
1752 >                                if (e.hash == h &&
1753 >                                    ((ek = e.key) == key ||
1754 >                                     (ek != null && key.equals(ek)))) {
1755 >                                    val = remappingFunction.apply(key, e.val);
1756 >                                    if (val != null)
1757 >                                        e.val = val;
1758 >                                    else {
1759 >                                        delta = -1;
1760 >                                        Node<K,V> en = e.next;
1761 >                                        if (pred != null)
1762 >                                            pred.next = en;
1763 >                                        else
1764 >                                            setTabAt(tab, i, en);
1765 >                                    }
1766 >                                    break;
1767 >                                }
1768 >                                pred = e;
1769 >                                if ((e = e.next) == null)
1770 >                                    break;
1771                              }
1772 <                            Node<V> last = e;
1773 <                            if ((e = e.next) == null) {
1774 <                                if ((val = mf.apply(k)) != null) {
1775 <                                    added = true;
1776 <                                    last.next = new Node<V>(h, k, val, null);
1777 <                                    if (len >= TREE_THRESHOLD)
1778 <                                        replaceWithTreeBin(tab, i, k);
1772 >                        }
1773 >                        else if (f instanceof TreeBin) {
1774 >                            binCount = 2;
1775 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1776 >                            TreeNode<K,V> r, p;
1777 >                            if ((r = t.root) != null &&
1778 >                                (p = r.findTreeNode(h, key, null)) != null) {
1779 >                                val = remappingFunction.apply(key, p.val);
1780 >                                if (val != null)
1781 >                                    p.val = val;
1782 >                                else {
1783 >                                    delta = -1;
1784 >                                    if (t.removeTreeNode(p))
1785 >                                        setTabAt(tab, i, untreeify(t.first));
1786                                  }
1487                                break;
1787                              }
1788                          }
1789                      }
1790                  }
1791 <                if (len != 0) {
1493 <                    if (!added)
1494 <                        return val;
1791 >                if (binCount != 0)
1792                      break;
1496                }
1793              }
1794          }
1795 <        if (val != null)
1796 <            addCount(1L, len);
1795 >        if (delta != 0)
1796 >            addCount((long)delta, binCount);
1797          return val;
1798      }
1799  
1800 <    /** Implementation for compute */
1801 <    @SuppressWarnings("unchecked") private final V internalCompute
1802 <        (K k, boolean onlyIfPresent,
1803 <         BiFun<? super K, ? super V, ? extends V> mf) {
1804 <        if (k == null || mf == null)
1800 >    /**
1801 >     * Attempts to compute a mapping for the specified key and its
1802 >     * current mapped value (or {@code null} if there is no current
1803 >     * mapping). The entire method invocation is performed atomically.
1804 >     * Some attempted update operations on this map by other threads
1805 >     * may be blocked while computation is in progress, so the
1806 >     * computation should be short and simple, and must not attempt to
1807 >     * update any other mappings of this Map.
1808 >     *
1809 >     * @param key key with which the specified value is to be associated
1810 >     * @param remappingFunction the function to compute a value
1811 >     * @return the new value associated with the specified key, or null if none
1812 >     * @throws NullPointerException if the specified key or remappingFunction
1813 >     *         is null
1814 >     * @throws IllegalStateException if the computation detectably
1815 >     *         attempts a recursive update to this map that would
1816 >     *         otherwise never complete
1817 >     * @throws RuntimeException or Error if the remappingFunction does so,
1818 >     *         in which case the mapping is unchanged
1819 >     */
1820 >    public V compute(K key,
1821 >                     BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1822 >        if (key == null || remappingFunction == null)
1823              throw new NullPointerException();
1824 <        int h = spread(k.hashCode());
1824 >        int h = spread(key.hashCode());
1825          V val = null;
1826          int delta = 0;
1827 <        int len = 0;
1828 <        for (Node<V>[] tab = table;;) {
1829 <            Node<V> f; int i, fh; Object fk;
1830 <            if (tab == null)
1827 >        int binCount = 0;
1828 >        for (Node<K,V>[] tab = table;;) {
1829 >            Node<K,V> f; int n, i, fh;
1830 >            if (tab == null || (n = tab.length) == 0)
1831                  tab = initTable();
1832 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1833 <                if (onlyIfPresent)
1834 <                    break;
1835 <                Node<V> node = new Node<V>(h, k, null, null);
1836 <                synchronized (node) {
1837 <                    if (casTabAt(tab, i, null, node)) {
1832 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1833 >                Node<K,V> r = new ReservationNode<K,V>();
1834 >                synchronized (r) {
1835 >                    if (casTabAt(tab, i, null, r)) {
1836 >                        binCount = 1;
1837 >                        Node<K,V> node = null;
1838                          try {
1839 <                            len = 1;
1526 <                            if ((val = mf.apply(k, null)) != null) {
1527 <                                node.val = val;
1839 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1840                                  delta = 1;
1841 +                                node = new Node<K,V>(h, key, val, null);
1842                              }
1843                          } finally {
1844 <                            if (delta == 0)
1532 <                                setTabAt(tab, i, null);
1844 >                            setTabAt(tab, i, node);
1845                          }
1846                      }
1847                  }
1848 <                if (len != 0)
1848 >                if (binCount != 0)
1849                      break;
1850              }
1851 <            else if ((fh = f.hash) < 0) {
1852 <                if ((fk = f.key) instanceof TreeBin) {
1853 <                    TreeBin<V> t = (TreeBin<V>)fk;
1854 <                    t.acquire(0);
1855 <                    try {
1856 <                        if (tabAt(tab, i) == f) {
1857 <                            len = 1;
1858 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1859 <                            if (p == null && onlyIfPresent)
1860 <                                break;
1851 >            else if ((fh = f.hash) == MOVED)
1852 >                tab = helpTransfer(tab, f);
1853 >            else {
1854 >                synchronized (f) {
1855 >                    if (tabAt(tab, i) == f) {
1856 >                        if (fh >= 0) {
1857 >                            binCount = 1;
1858 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1859 >                                K ek;
1860 >                                if (e.hash == h &&
1861 >                                    ((ek = e.key) == key ||
1862 >                                     (ek != null && key.equals(ek)))) {
1863 >                                    val = remappingFunction.apply(key, e.val);
1864 >                                    if (val != null)
1865 >                                        e.val = val;
1866 >                                    else {
1867 >                                        delta = -1;
1868 >                                        Node<K,V> en = e.next;
1869 >                                        if (pred != null)
1870 >                                            pred.next = en;
1871 >                                        else
1872 >                                            setTabAt(tab, i, en);
1873 >                                    }
1874 >                                    break;
1875 >                                }
1876 >                                pred = e;
1877 >                                if ((e = e.next) == null) {
1878 >                                    val = remappingFunction.apply(key, null);
1879 >                                    if (val != null) {
1880 >                                        delta = 1;
1881 >                                        pred.next =
1882 >                                            new Node<K,V>(h, key, val, null);
1883 >                                    }
1884 >                                    break;
1885 >                                }
1886 >                            }
1887 >                        }
1888 >                        else if (f instanceof TreeBin) {
1889 >                            binCount = 1;
1890 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1891 >                            TreeNode<K,V> r, p;
1892 >                            if ((r = t.root) != null)
1893 >                                p = r.findTreeNode(h, key, null);
1894 >                            else
1895 >                                p = null;
1896                              V pv = (p == null) ? null : p.val;
1897 <                            if ((val = mf.apply(k, pv)) != null) {
1897 >                            val = remappingFunction.apply(key, pv);
1898 >                            if (val != null) {
1899                                  if (p != null)
1900                                      p.val = val;
1901                                  else {
1554                                    len = 2;
1902                                      delta = 1;
1903 <                                    t.putTreeNode(h, k, val);
1903 >                                    t.putTreeVal(h, key, val);
1904                                  }
1905                              }
1906                              else if (p != null) {
1907                                  delta = -1;
1908 <                                t.deleteTreeNode(p);
1909 <                            }
1563 <                        }
1564 <                    } finally {
1565 <                        t.release(0);
1566 <                    }
1567 <                    if (len != 0)
1568 <                        break;
1569 <                }
1570 <                else
1571 <                    tab = (Node<V>[])fk;
1572 <            }
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;
1908 >                                if (t.removeTreeNode(p))
1909 >                                    setTabAt(tab, i, untreeify(t.first));
1910                              }
1911                          }
1912                      }
1913                  }
1914 <                if (len != 0)
1914 >                if (binCount != 0) {
1915 >                    if (binCount >= TREEIFY_THRESHOLD)
1916 >                        treeifyBin(tab, i);
1917                      break;
1918 +                }
1919              }
1920          }
1921          if (delta != 0)
1922 <            addCount((long)delta, len);
1922 >            addCount((long)delta, binCount);
1923          return val;
1924      }
1925  
1926 <    /** Implementation for merge */
1927 <    @SuppressWarnings("unchecked") private final V internalMerge
1928 <        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1929 <        if (k == null || v == null || mf == null)
1926 >    /**
1927 >     * If the specified key is not already associated with a
1928 >     * (non-null) value, associates it with the given value.
1929 >     * Otherwise, replaces the value with the results of the given
1930 >     * remapping function, or removes if {@code null}. The entire
1931 >     * method invocation is performed atomically.  Some attempted
1932 >     * update operations on this map by other threads may be blocked
1933 >     * while computation is in progress, so the computation should be
1934 >     * short and simple, and must not attempt to update any other
1935 >     * mappings of this Map.
1936 >     *
1937 >     * @param key key with which the specified value is to be associated
1938 >     * @param value the value to use if absent
1939 >     * @param remappingFunction the function to recompute a value if present
1940 >     * @return the new value associated with the specified key, or null if none
1941 >     * @throws NullPointerException if the specified key or the
1942 >     *         remappingFunction is null
1943 >     * @throws RuntimeException or Error if the remappingFunction does so,
1944 >     *         in which case the mapping is unchanged
1945 >     */
1946 >    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1947 >        if (key == null || value == null || remappingFunction == null)
1948              throw new NullPointerException();
1949 <        int h = spread(k.hashCode());
1949 >        int h = spread(key.hashCode());
1950          V val = null;
1951          int delta = 0;
1952 <        int len = 0;
1953 <        for (Node<V>[] tab = table;;) {
1954 <            int i; Node<V> f; Object fk; V fv;
1955 <            if (tab == null)
1952 >        int binCount = 0;
1953 >        for (Node<K,V>[] tab = table;;) {
1954 >            Node<K,V> f; int n, i, fh;
1955 >            if (tab == null || (n = tab.length) == 0)
1956                  tab = initTable();
1957 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1958 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
1957 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1958 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1959                      delta = 1;
1960 <                    val = v;
1960 >                    val = value;
1961                      break;
1962                  }
1963              }
1964 <            else if (f.hash < 0) {
1965 <                if ((fk = f.key) instanceof TreeBin) {
1966 <                    TreeBin<V> t = (TreeBin<V>)fk;
1967 <                    t.acquire(0);
1968 <                    try {
1969 <                        if (tabAt(tab, i) == f) {
1970 <                            len = 1;
1971 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1972 <                            val = (p == null) ? v : mf.apply(p.val, v);
1964 >            else if ((fh = f.hash) == MOVED)
1965 >                tab = helpTransfer(tab, f);
1966 >            else {
1967 >                synchronized (f) {
1968 >                    if (tabAt(tab, i) == f) {
1969 >                        if (fh >= 0) {
1970 >                            binCount = 1;
1971 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1972 >                                K ek;
1973 >                                if (e.hash == h &&
1974 >                                    ((ek = e.key) == key ||
1975 >                                     (ek != null && key.equals(ek)))) {
1976 >                                    val = remappingFunction.apply(e.val, value);
1977 >                                    if (val != null)
1978 >                                        e.val = val;
1979 >                                    else {
1980 >                                        delta = -1;
1981 >                                        Node<K,V> en = e.next;
1982 >                                        if (pred != null)
1983 >                                            pred.next = en;
1984 >                                        else
1985 >                                            setTabAt(tab, i, en);
1986 >                                    }
1987 >                                    break;
1988 >                                }
1989 >                                pred = e;
1990 >                                if ((e = e.next) == null) {
1991 >                                    delta = 1;
1992 >                                    val = value;
1993 >                                    pred.next =
1994 >                                        new Node<K,V>(h, key, val, null);
1995 >                                    break;
1996 >                                }
1997 >                            }
1998 >                        }
1999 >                        else if (f instanceof TreeBin) {
2000 >                            binCount = 2;
2001 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2002 >                            TreeNode<K,V> r = t.root;
2003 >                            TreeNode<K,V> p = (r == null) ? null :
2004 >                                r.findTreeNode(h, key, null);
2005 >                            val = (p == null) ? value :
2006 >                                remappingFunction.apply(p.val, value);
2007                              if (val != null) {
2008                                  if (p != null)
2009                                      p.val = val;
2010                                  else {
1651                                    len = 2;
2011                                      delta = 1;
2012 <                                    t.putTreeNode(h, k, val);
2012 >                                    t.putTreeVal(h, key, val);
2013                                  }
2014                              }
2015                              else if (p != null) {
2016                                  delta = -1;
2017 <                                t.deleteTreeNode(p);
2018 <                            }
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;
2017 >                                if (t.removeTreeNode(p))
2018 >                                    setTabAt(tab, i, untreeify(t.first));
2019                              }
2020                          }
2021                      }
2022                  }
2023 <                if (len != 0)
2023 >                if (binCount != 0) {
2024 >                    if (binCount >= TREEIFY_THRESHOLD)
2025 >                        treeifyBin(tab, i);
2026                      break;
2027 +                }
2028              }
2029          }
2030          if (delta != 0)
2031 <            addCount((long)delta, len);
2031 >            addCount((long)delta, binCount);
2032          return val;
2033      }
2034  
2035 <    /** Implementation for putAll */
2036 <    @SuppressWarnings("unchecked") private final void internalPutAll
2037 <        (Map<? extends K, ? extends V> m) {
2038 <        tryPresize(m.size());
2039 <        long delta = 0L;     // number of uncommitted additions
2040 <        boolean npe = false; // to throw exception on exit for nulls
2041 <        try {                // to clean up counts on other exceptions
2042 <            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
2043 <                Object k; V v;
2044 <                if (entry == null || (k = entry.getKey()) == null ||
2045 <                    (v = entry.getValue()) == null) {
2046 <                    npe = true;
2047 <                    break;
2048 <                }
2049 <                int h = spread(k.hashCode());
2050 <                for (Node<V>[] tab = table;;) {
2051 <                    int i; Node<V> f; int fh; Object fk;
2052 <                    if (tab == null)
2053 <                        tab = initTable();
2054 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
2055 <                        if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
2056 <                            ++delta;
2057 <                            break;
2058 <                        }
2059 <                    }
2060 <                    else if ((fh = f.hash) < 0) {
2061 <                        if ((fk = f.key) instanceof TreeBin) {
2062 <                            TreeBin<V> t = (TreeBin<V>)fk;
2063 <                            boolean validated = false;
2064 <                            t.acquire(0);
2065 <                            try {
2066 <                                if (tabAt(tab, i) == f) {
2067 <                                    validated = true;
2068 <                                    TreeNode<V> p = t.getTreeNode(h, k, t.root);
2069 <                                    if (p != null)
2070 <                                        p.val = v;
2071 <                                    else {
2072 <                                        t.putTreeNode(h, k, v);
2073 <                                        ++delta;
2074 <                                    }
2075 <                                }
2076 <                            } finally {
2077 <                                t.release(0);
2078 <                            }
2079 <                            if (validated)
2080 <                                break;
2081 <                        }
2082 <                        else
2083 <                            tab = (Node<V>[])fk;
2084 <                    }
2085 <                    else {
2086 <                        int len = 0;
2087 <                        synchronized (f) {
2088 <                            if (tabAt(tab, i) == f) {
2089 <                                len = 1;
2090 <                                for (Node<V> e = f;; ++len) {
2091 <                                    Object ek; V ev;
2092 <                                    if (e.hash == h &&
2093 <                                        (ev = e.val) != null &&
2094 <                                        ((ek = e.key) == k || k.equals(ek))) {
2095 <                                        e.val = v;
2096 <                                        break;
2097 <                                    }
2098 <                                    Node<V> last = e;
2099 <                                    if ((e = e.next) == null) {
2100 <                                        ++delta;
2101 <                                        last.next = new Node<V>(h, k, v, null);
2102 <                                        if (len >= TREE_THRESHOLD)
2103 <                                            replaceWithTreeBin(tab, i, k);
2104 <                                        break;
2105 <                                    }
2106 <                                }
2107 <                            }
2108 <                        }
2109 <                        if (len != 0) {
2110 <                            if (len > 1) {
2111 <                                addCount(delta, len);
2112 <                                delta = 0L;
2113 <                            }
2114 <                            break;
2115 <                        }
2116 <                    }
2117 <                }
2118 <            }
2119 <        } finally {
2120 <            if (delta != 0L)
2121 <                addCount(delta, 2);
2122 <        }
2123 <        if (npe)
2035 >    // Hashtable legacy methods
2036 >
2037 >    /**
2038 >     * Legacy method testing if some key maps into the specified value
2039 >     * in this table.  This method is identical in functionality to
2040 >     * {@link #containsValue(Object)}, and exists solely to ensure
2041 >     * full compatibility with class {@link java.util.Hashtable},
2042 >     * which supported this method prior to introduction of the
2043 >     * Java Collections framework.
2044 >     *
2045 >     * @param  value a value to search for
2046 >     * @return {@code true} if and only if some key maps to the
2047 >     *         {@code value} argument in this table as
2048 >     *         determined by the {@code equals} method;
2049 >     *         {@code false} otherwise
2050 >     * @throws NullPointerException if the specified value is null
2051 >     */
2052 >    @Deprecated public boolean contains(Object value) {
2053 >        return containsValue(value);
2054 >    }
2055 >
2056 >    /**
2057 >     * Returns an enumeration of the keys in this table.
2058 >     *
2059 >     * @return an enumeration of the keys in this table
2060 >     * @see #keySet()
2061 >     */
2062 >    public Enumeration<K> keys() {
2063 >        Node<K,V>[] t;
2064 >        int f = (t = table) == null ? 0 : t.length;
2065 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2066 >    }
2067 >
2068 >    /**
2069 >     * Returns an enumeration of the values in this table.
2070 >     *
2071 >     * @return an enumeration of the values in this table
2072 >     * @see #values()
2073 >     */
2074 >    public Enumeration<V> elements() {
2075 >        Node<K,V>[] t;
2076 >        int f = (t = table) == null ? 0 : t.length;
2077 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2078 >    }
2079 >
2080 >    // ConcurrentHashMapV8-only methods
2081 >
2082 >    /**
2083 >     * Returns the number of mappings. This method should be used
2084 >     * instead of {@link #size} because a ConcurrentHashMapV8 may
2085 >     * contain more mappings than can be represented as an int. The
2086 >     * value returned is an estimate; the actual count may differ if
2087 >     * there are concurrent insertions or removals.
2088 >     *
2089 >     * @return the number of mappings
2090 >     * @since 1.8
2091 >     */
2092 >    public long mappingCount() {
2093 >        long n = sumCount();
2094 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2095 >    }
2096 >
2097 >    /**
2098 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2099 >     * from the given type to {@code Boolean.TRUE}.
2100 >     *
2101 >     * @return the new set
2102 >     * @since 1.8
2103 >     */
2104 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2105 >        return new KeySetView<K,Boolean>
2106 >            (new ConcurrentHashMapV8<K,Boolean>(), Boolean.TRUE);
2107 >    }
2108 >
2109 >    /**
2110 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2111 >     * from the given type to {@code Boolean.TRUE}.
2112 >     *
2113 >     * @param initialCapacity The implementation performs internal
2114 >     * sizing to accommodate this many elements.
2115 >     * @return the new set
2116 >     * @throws IllegalArgumentException if the initial capacity of
2117 >     * elements is negative
2118 >     * @since 1.8
2119 >     */
2120 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2121 >        return new KeySetView<K,Boolean>
2122 >            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2123 >    }
2124 >
2125 >    /**
2126 >     * Returns a {@link Set} view of the keys in this map, using the
2127 >     * given common mapped value for any additions (i.e., {@link
2128 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2129 >     * This is of course only appropriate if it is acceptable to use
2130 >     * the same value for all additions from this view.
2131 >     *
2132 >     * @param mappedValue the mapped value to use for any additions
2133 >     * @return the set view
2134 >     * @throws NullPointerException if the mappedValue is null
2135 >     */
2136 >    public KeySetView<K,V> keySet(V mappedValue) {
2137 >        if (mappedValue == null)
2138              throw new NullPointerException();
2139 +        return new KeySetView<K,V>(this, mappedValue);
2140      }
2141  
2142 +    /* ---------------- Special Nodes -------------- */
2143 +
2144      /**
2145 <     * Implementation for clear. Steps through each bin, removing all
1807 <     * nodes.
2145 >     * A node inserted at head of bins during transfer operations.
2146       */
2147 <    @SuppressWarnings("unchecked") private final void internalClear() {
2148 <        long delta = 0L; // negative number of deletions
2149 <        int i = 0;
2150 <        Node<V>[] tab = table;
2151 <        while (tab != null && i < tab.length) {
2152 <            Node<V> f = tabAt(tab, i);
2153 <            if (f == null)
2154 <                ++i;
2155 <            else if (f.hash < 0) {
2156 <                Object fk;
2157 <                if ((fk = f.key) instanceof TreeBin) {
2158 <                    TreeBin<V> t = (TreeBin<V>)fk;
2159 <                    t.acquire(0);
2160 <                    try {
2161 <                        if (tabAt(tab, i) == f) {
2162 <                            for (Node<V> p = t.first; p != null; p = p.next) {
2163 <                                if (p.val != null) { // (currently always true)
2164 <                                    p.val = null;
2165 <                                    --delta;
2166 <                                }
2167 <                            }
2168 <                            t.first = null;
2169 <                            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 <                            }
2147 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2148 >        final Node<K,V>[] nextTable;
2149 >        ForwardingNode(Node<K,V>[] tab) {
2150 >            super(MOVED, null, null, null);
2151 >            this.nextTable = tab;
2152 >        }
2153 >
2154 >        Node<K,V> find(int h, Object k) {
2155 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2156 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2157 >                Node<K,V> e; int n;
2158 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2159 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2160 >                    return null;
2161 >                for (;;) {
2162 >                    int eh; K ek;
2163 >                    if ((eh = e.hash) == h &&
2164 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2165 >                        return e;
2166 >                    if (eh < 0) {
2167 >                        if (e instanceof ForwardingNode) {
2168 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2169 >                            continue outer;
2170                          }
2171 <                        setTabAt(tab, i, null);
2172 <                        ++i;
2171 >                        else
2172 >                            return e.find(h, k);
2173                      }
2174 +                    if ((e = e.next) == null)
2175 +                        return null;
2176                  }
2177              }
2178          }
1856        if (delta != 0L)
1857            addCount(delta, -1);
2179      }
2180  
1860    /* ---------------- Table Initialization and Resizing -------------- */
1861
2181      /**
2182 <     * Returns a power of two table size for the given desired capacity.
1864 <     * See Hackers Delight, sec 3.2
2182 >     * A place-holder node used in computeIfAbsent and compute
2183       */
2184 <    private static final int tableSizeFor(int c) {
2185 <        int n = c - 1;
2186 <        n |= n >>> 1;
2187 <        n |= n >>> 2;
2188 <        n |= n >>> 4;
2189 <        n |= n >>> 8;
2190 <        n |= n >>> 16;
2191 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
2184 >    static final class ReservationNode<K,V> extends Node<K,V> {
2185 >        ReservationNode() {
2186 >            super(RESERVED, null, null, null);
2187 >        }
2188 >
2189 >        Node<K,V> find(int h, Object k) {
2190 >            return null;
2191 >        }
2192      }
2193  
2194 +    /* ---------------- Table Initialization and Resizing -------------- */
2195 +
2196      /**
2197       * Initializes table, using the size recorded in sizeCtl.
2198       */
2199 <    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
2200 <        Node<V>[] tab; int sc;
2201 <        while ((tab = table) == null) {
2199 >    private final Node<K,V>[] initTable() {
2200 >        Node<K,V>[] tab; int sc;
2201 >        while ((tab = table) == null || tab.length == 0) {
2202              if ((sc = sizeCtl) < 0)
2203                  Thread.yield(); // lost initialization race; just spin
2204              else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2205                  try {
2206 <                    if ((tab = table) == null) {
2206 >                    if ((tab = table) == null || tab.length == 0) {
2207                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2208 <                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2209 <                        table = tab = (Node<V>[])tb;
2208 >                        @SuppressWarnings({"rawtypes","unchecked"})
2209 >                            Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2210 >                        table = tab = nt;
2211                          sc = n - (n >>> 2);
2212                      }
2213                  } finally {
# Line 1927 | Line 2248 | public class ConcurrentHashMapV8<K, V>
2248              s = sumCount();
2249          }
2250          if (check >= 0) {
2251 <            Node<V>[] tab, nt; int sc;
2251 >            Node<K,V>[] tab, nt; int sc;
2252              while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2253                     tab.length < MAXIMUM_CAPACITY) {
2254                  if (sc < 0) {
# Line 1945 | Line 2266 | public class ConcurrentHashMapV8<K, V>
2266      }
2267  
2268      /**
2269 +     * Helps transfer if a resize is in progress.
2270 +     */
2271 +    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2272 +        Node<K,V>[] nextTab; int sc;
2273 +        if ((f instanceof ForwardingNode) &&
2274 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2275 +            if (nextTab == nextTable && tab == table &&
2276 +                transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
2277 +                U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2278 +                transfer(tab, nextTab);
2279 +            return nextTab;
2280 +        }
2281 +        return table;
2282 +    }
2283 +
2284 +    /**
2285       * Tries to presize table to accommodate the given number of elements.
2286       *
2287       * @param size number of elements (doesn't need to be perfectly accurate)
2288       */
2289 <    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
2289 >    private final void tryPresize(int size) {
2290          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2291              tableSizeFor(size + (size >>> 1) + 1);
2292          int sc;
2293          while ((sc = sizeCtl) >= 0) {
2294 <            Node<V>[] tab = table; int n;
2294 >            Node<K,V>[] tab = table; int n;
2295              if (tab == null || (n = tab.length) == 0) {
2296                  n = (sc > c) ? sc : c;
2297                  if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2298                      try {
2299                          if (table == tab) {
2300 <                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2301 <                            table = (Node<V>[])tb;
2300 >                            @SuppressWarnings({"rawtypes","unchecked"})
2301 >                                Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2302 >                            table = nt;
2303                              sc = n - (n >>> 2);
2304                          }
2305                      } finally {
# Line 1981 | Line 2319 | public class ConcurrentHashMapV8<K, V>
2319       * Moves and/or copies the nodes in each bin to new table. See
2320       * above for explanation.
2321       */
2322 <    @SuppressWarnings("unchecked") private final void transfer
1985 <        (Node<V>[] tab, Node<V>[] nextTab) {
2322 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2323          int n = tab.length, stride;
2324          if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2325              stride = MIN_TRANSFER_STRIDE; // subdivide range
2326          if (nextTab == null) {            // initiating
2327              try {
2328 <                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
2329 <                nextTab = (Node<V>[])tb;
2328 >                @SuppressWarnings({"rawtypes","unchecked"})
2329 >                    Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
2330 >                nextTab = nt;
2331              } catch (Throwable ex) {      // try to cope with OOME
2332                  sizeCtl = Integer.MAX_VALUE;
2333                  return;
# Line 1997 | Line 2335 | public class ConcurrentHashMapV8<K, V>
2335              nextTable = nextTab;
2336              transferOrigin = n;
2337              transferIndex = n;
2338 <            Node<V> rev = new Node<V>(MOVED, tab, null, null);
2338 >            ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
2339              for (int k = n; k > 0;) {    // progressively reveal ready slots
2340                  int nextk = (k > stride) ? k - stride : 0;
2341                  for (int m = nextk; m < k; ++m)
# Line 2008 | Line 2346 | public class ConcurrentHashMapV8<K, V>
2346              }
2347          }
2348          int nextn = nextTab.length;
2349 <        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2349 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2350          boolean advance = true;
2351 +        boolean finishing = false; // to ensure sweep before committing nextTab
2352          for (int i = 0, bound = 0;;) {
2353 <            int nextIndex, nextBound; Node<V> f; Object fk;
2353 >            int nextIndex, nextBound, fh; Node<K,V> f;
2354              while (advance) {
2355 <                if (--i >= bound)
2355 >                if (--i >= bound || finishing)
2356                      advance = false;
2357                  else if ((nextIndex = transferIndex) <= transferOrigin) {
2358                      i = -1;
# Line 2029 | Line 2368 | public class ConcurrentHashMapV8<K, V>
2368                  }
2369              }
2370              if (i < 0 || i >= n || i + n >= nextn) {
2371 +                if (finishing) {
2372 +                    nextTable = null;
2373 +                    table = nextTab;
2374 +                    sizeCtl = (n << 1) - (n >>> 1);
2375 +                    return;
2376 +                }
2377                  for (int sc;;) {
2378                      if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2379 <                        if (sc == -1) {
2380 <                            nextTable = null;
2381 <                            table = nextTab;
2382 <                            sizeCtl = (n << 1) - (n >>> 1);
2383 <                        }
2039 <                        return;
2379 >                        if (sc != -1)
2380 >                            return;
2381 >                        finishing = advance = true;
2382 >                        i = n; // recheck before commit
2383 >                        break;
2384                      }
2385                  }
2386              }
# Line 2047 | Line 2391 | public class ConcurrentHashMapV8<K, V>
2391                      advance = true;
2392                  }
2393              }
2394 <            else if (f.hash >= 0) {
2394 >            else if ((fh = f.hash) == MOVED)
2395 >                advance = true; // already processed
2396 >            else {
2397                  synchronized (f) {
2398                      if (tabAt(tab, i) == f) {
2399 <                        int runBit = f.hash & n;
2400 <                        Node<V> lastRun = f, lo = null, hi = null;
2401 <                        for (Node<V> p = f.next; p != null; p = p.next) {
2402 <                            int b = p.hash & n;
2403 <                            if (b != runBit) {
2404 <                                runBit = b;
2405 <                                lastRun = p;
2399 >                        Node<K,V> ln, hn;
2400 >                        if (fh >= 0) {
2401 >                            int runBit = fh & n;
2402 >                            Node<K,V> lastRun = f;
2403 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2404 >                                int b = p.hash & n;
2405 >                                if (b != runBit) {
2406 >                                    runBit = b;
2407 >                                    lastRun = p;
2408 >                                }
2409                              }
2410 <                        }
2411 <                        if (runBit == 0)
2412 <                            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);
2410 >                            if (runBit == 0) {
2411 >                                ln = lastRun;
2412 >                                hn = null;
2413                              }
2414                              else {
2415 <                                ++hc;
2416 <                                ht.putTreeNode(h, k, v);
2415 >                                hn = lastRun;
2416 >                                ln = null;
2417                              }
2418 +                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2419 +                                int ph = p.hash; K pk = p.key; V pv = p.val;
2420 +                                if ((ph & n) == 0)
2421 +                                    ln = new Node<K,V>(ph, pk, pv, ln);
2422 +                                else
2423 +                                    hn = new Node<K,V>(ph, pk, pv, hn);
2424 +                            }
2425 +                            setTabAt(nextTab, i, ln);
2426 +                            setTabAt(nextTab, i + n, hn);
2427 +                            setTabAt(tab, i, fwd);
2428 +                            advance = true;
2429                          }
2430 <                        Node<V> ln, hn; // throw away trees if too small
2431 <                        if (lc < TREE_THRESHOLD) {
2432 <                            ln = null;
2433 <                            for (Node<V> p = lt.first; p != null; p = p.next)
2434 <                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2435 <                        }
2436 <                        else
2437 <                            ln = new Node<V>(MOVED, lt, null, null);
2438 <                        setTabAt(nextTab, i, ln);
2439 <                        if (hc < TREE_THRESHOLD) {
2440 <                            hn = null;
2441 <                            for (Node<V> p = ht.first; p != null; p = p.next)
2442 <                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2430 >                        else if (f instanceof TreeBin) {
2431 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2432 >                            TreeNode<K,V> lo = null, loTail = null;
2433 >                            TreeNode<K,V> hi = null, hiTail = null;
2434 >                            int lc = 0, hc = 0;
2435 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2436 >                                int h = e.hash;
2437 >                                TreeNode<K,V> p = new TreeNode<K,V>
2438 >                                    (h, e.key, e.val, null, null);
2439 >                                if ((h & n) == 0) {
2440 >                                    if ((p.prev = loTail) == null)
2441 >                                        lo = p;
2442 >                                    else
2443 >                                        loTail.next = p;
2444 >                                    loTail = p;
2445 >                                    ++lc;
2446 >                                }
2447 >                                else {
2448 >                                    if ((p.prev = hiTail) == null)
2449 >                                        hi = p;
2450 >                                    else
2451 >                                        hiTail.next = p;
2452 >                                    hiTail = p;
2453 >                                    ++hc;
2454 >                                }
2455 >                            }
2456 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2457 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2458 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2459 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2460 >                            setTabAt(nextTab, i, ln);
2461 >                            setTabAt(nextTab, i + n, hn);
2462 >                            setTabAt(tab, i, fwd);
2463 >                            advance = true;
2464                          }
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;
2465                      }
2121                } finally {
2122                    t.release(0);
2466                  }
2467              }
2125            else
2126                advance = true; // already processed
2468          }
2469      }
2470  
2471 <    /* ---------------- Counter support -------------- */
2471 >    /* ---------------- Conversion from/to TreeBins -------------- */
2472  
2473 <    final long sumCount() {
2474 <        CounterCell[] as = counterCells; CounterCell a;
2475 <        long sum = baseCount;
2476 <        if (as != null) {
2477 <            for (int i = 0; i < as.length; ++i) {
2478 <                if ((a = as[i]) != null)
2479 <                    sum += a.value;
2473 >    /**
2474 >     * Replaces all linked nodes in bin at given index unless table is
2475 >     * too small, in which case resizes instead.
2476 >     */
2477 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2478 >        Node<K,V> b; int n, sc;
2479 >        if (tab != null) {
2480 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2481 >                if (tab == table && (sc = sizeCtl) >= 0 &&
2482 >                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
2483 >                    transfer(tab, null);
2484              }
2485 <        }
2486 <        return sum;
2487 <    }
2488 <
2489 <    // See LongAdder version for explanation
2490 <    private final void fullAddCount(long x, CounterHashCode hc,
2491 <                                    boolean wasUncontended) {
2492 <        int h;
2493 <        if (hc == null) {
2494 <            hc = new CounterHashCode();
2495 <            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
2496 <            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
2497 <            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;
2485 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2486 >                synchronized (b) {
2487 >                    if (tabAt(tab, index) == b) {
2488 >                        TreeNode<K,V> hd = null, tl = null;
2489 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2490 >                            TreeNode<K,V> p =
2491 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2492 >                                                  null, null);
2493 >                            if ((p.prev = tl) == null)
2494 >                                hd = p;
2495 >                            else
2496 >                                tl.next = p;
2497 >                            tl = p;
2498                          }
2499 <                    } finally {
2202 <                        counterBusy = 0;
2499 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2500                      }
2204                    collide = false;
2205                    continue;                   // Retry with expanded table
2501                  }
2207                h ^= h << 13;                   // Rehash
2208                h ^= h >>> 17;
2209                h ^= h << 5;
2210            }
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;
2502              }
2227            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2228                break;                          // Fall back on using base
2503          }
2230        hc.code = h;                            // Record index for next time
2504      }
2505  
2506 <    /* ----------------Table Traversal -------------- */
2506 >    /**
2507 >     * Returns a list on non-TreeNodes replacing those in given list.
2508 >     */
2509 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2510 >        Node<K,V> hd = null, tl = null;
2511 >        for (Node<K,V> q = b; q != null; q = q.next) {
2512 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2513 >            if (tl == null)
2514 >                hd = p;
2515 >            else
2516 >                tl.next = p;
2517 >            tl = p;
2518 >        }
2519 >        return hd;
2520 >    }
2521 >
2522 >    /* ---------------- TreeNodes -------------- */
2523  
2524      /**
2525 <     * Encapsulates traversal for methods such as containsValue; also
2526 <     * serves as a base class for other iterators and bulk tasks.
2527 <     *
2528 <     * At each step, the iterator snapshots the key ("nextKey") and
2529 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2530 <     * snapshot, has a non-null user value). Because val fields can
2531 <     * change (including to null, indicating deletion), field nextVal
2532 <     * 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.
2279 <     */
2280 <    @SuppressWarnings("serial") static class Traverser<K,V,R>
2281 <        extends CountedCompleter<R> {
2282 <        final ConcurrentHashMapV8<K, V> map;
2283 <        Node<V> next;        // the next entry to use
2284 <        Object nextKey;      // cached key field of next
2285 <        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
2525 >     * Nodes for use in TreeBins
2526 >     */
2527 >    static final class TreeNode<K,V> extends Node<K,V> {
2528 >        TreeNode<K,V> parent;  // red-black tree links
2529 >        TreeNode<K,V> left;
2530 >        TreeNode<K,V> right;
2531 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2532 >        boolean red;
2533  
2534 <        /** Creates iterator for all entries in the table. */
2535 <        Traverser(ConcurrentHashMapV8<K, V> map) {
2536 <            this.map = map;
2534 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2535 >                 TreeNode<K,V> parent) {
2536 >            super(hash, key, val, next);
2537 >            this.parent = parent;
2538          }
2539  
2540 <        /** Creates iterator for split() methods and task constructors */
2541 <        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 <            }
2540 >        Node<K,V> find(int h, Object k) {
2541 >            return findTreeNode(h, k, null);
2542          }
2543  
2544          /**
2545 <         * Advances next; returns nextVal or null if terminated.
2546 <         * See above for explanation.
2545 >         * Returns the TreeNode (or null if not found) for the given key
2546 >         * starting at given root.
2547           */
2548 <        @SuppressWarnings("unchecked") final V advance() {
2549 <            Node<V> e = next;
2550 <            V ev = null;
2551 <            outer: do {
2552 <                if (e != null)                  // advance past used/skipped node
2553 <                    e = e.next;
2554 <                while (e == null) {             // get to next non-null bin
2555 <                    ConcurrentHashMapV8<K, V> m;
2556 <                    Node<V>[] t; int b, i, n; Object ek; //  must use locals
2557 <                    if ((t = tab) != null)
2558 <                        n = t.length;
2559 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2560 <                        n = baseLimit = baseSize = t.length;
2548 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2549 >            if (k != null) {
2550 >                TreeNode<K,V> p = this;
2551 >                do  {
2552 >                    int ph, dir; K pk; TreeNode<K,V> q;
2553 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2554 >                    if ((ph = p.hash) > h)
2555 >                        p = pl;
2556 >                    else if (ph < h)
2557 >                        p = pr;
2558 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2559 >                        return p;
2560 >                    else if (pl == null)
2561 >                        p = pr;
2562 >                    else if (pr == null)
2563 >                        p = pl;
2564 >                    else if ((kc != null ||
2565 >                              (kc = comparableClassFor(k)) != null) &&
2566 >                             (dir = compareComparables(kc, k, pk)) != 0)
2567 >                        p = (dir < 0) ? pl : pr;
2568 >                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
2569 >                        return q;
2570                      else
2571 <                        break outer;
2572 <                    if ((b = baseIndex) >= baseLimit ||
2573 <                        (i = index) < 0 || i >= n)
2574 <                        break outer;
2337 <                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2338 <                        if ((ek = e.key) instanceof TreeBin)
2339 <                            e = ((TreeBin<V>)ek).first;
2340 <                        else {
2341 <                            tab = (Node<V>[])ek;
2342 <                            continue;           // restarts due to null val
2343 <                        }
2344 <                    }                           // visit upper slots if present
2345 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2346 <                }
2347 <                nextKey = e.key;
2348 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2349 <            next = e;
2350 <            return nextVal = ev;
2571 >                        p = pl;
2572 >                } while (p != null);
2573 >            }
2574 >            return null;
2575          }
2576 +    }
2577  
2578 <        public final void remove() {
2354 <            Object k = nextKey;
2355 <            if (k == null && (advance() == null || (k = nextKey) == null))
2356 <                throw new IllegalStateException();
2357 <            map.internalReplace(k, null, null);
2358 <        }
2578 >    /* ---------------- TreeBins -------------- */
2579  
2580 <        public final boolean hasNext() {
2581 <            return nextVal != null || advance() != null;
2580 >    /**
2581 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2582 >     * keys or values, but instead point to list of TreeNodes and
2583 >     * their root. They also maintain a parasitic read-write lock
2584 >     * forcing writers (who hold bin lock) to wait for readers (who do
2585 >     * not) to complete before tree restructuring operations.
2586 >     */
2587 >    static final class TreeBin<K,V> extends Node<K,V> {
2588 >        TreeNode<K,V> root;
2589 >        volatile TreeNode<K,V> first;
2590 >        volatile Thread waiter;
2591 >        volatile int lockState;
2592 >        // values for lockState
2593 >        static final int WRITER = 1; // set while holding write lock
2594 >        static final int WAITER = 2; // set when waiting for write lock
2595 >        static final int READER = 4; // increment value for setting read lock
2596 >
2597 >        /**
2598 >         * Tie-breaking utility for ordering insertions when equal
2599 >         * hashCodes and non-comparable. We don't require a total
2600 >         * order, just a consistent insertion rule to maintain
2601 >         * equivalence across rebalancings. Tie-breaking further than
2602 >         * necessary simplifies testing a bit.
2603 >         */
2604 >        static int tieBreakOrder(Object a, Object b) {
2605 >            int d;
2606 >            if (a == null || b == null ||
2607 >                (d = a.getClass().getName().
2608 >                 compareTo(b.getClass().getName())) == 0)
2609 >                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2610 >                     -1 : 1);
2611 >            return d;
2612          }
2613  
2614 <        public final boolean hasMoreElements() { return hasNext(); }
2615 <
2616 <        public void compute() { } // default no-op CountedCompleter body
2614 >        /**
2615 >         * Creates bin with initial set of nodes headed by b.
2616 >         */
2617 >        TreeBin(TreeNode<K,V> b) {
2618 >            super(TREEBIN, null, null, null);
2619 >            this.first = b;
2620 >            TreeNode<K,V> r = null;
2621 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2622 >                next = (TreeNode<K,V>)x.next;
2623 >                x.left = x.right = null;
2624 >                if (r == null) {
2625 >                    x.parent = null;
2626 >                    x.red = false;
2627 >                    r = x;
2628 >                }
2629 >                else {
2630 >                    K k = x.key;
2631 >                    int h = x.hash;
2632 >                    Class<?> kc = null;
2633 >                    for (TreeNode<K,V> p = r;;) {
2634 >                        int dir, ph;
2635 >                        K pk = p.key;
2636 >                        if ((ph = p.hash) > h)
2637 >                            dir = -1;
2638 >                        else if (ph < h)
2639 >                            dir = 1;
2640 >                        else if ((kc == null &&
2641 >                                  (kc = comparableClassFor(k)) == null) ||
2642 >                                 (dir = compareComparables(kc, k, pk)) == 0)
2643 >                            dir = tieBreakOrder(k, pk);
2644 >                            TreeNode<K,V> xp = p;
2645 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2646 >                            x.parent = xp;
2647 >                            if (dir <= 0)
2648 >                                xp.left = x;
2649 >                            else
2650 >                                xp.right = x;
2651 >                            r = balanceInsertion(r, x);
2652 >                            break;
2653 >                        }
2654 >                    }
2655 >                }
2656 >            }
2657 >            this.root = r;
2658 >            assert checkInvariants(root);
2659 >        }
2660  
2661          /**
2662 <         * 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.
2662 >         * Acquires write lock for tree restructuring.
2663           */
2664 <        final int preSplit() {
2665 <            ConcurrentHashMapV8<K, V> m; int b; Node<V>[] t;  ForkJoinPool pool;
2666 <            if ((b = batch) < 0 && (m = map) != null) { // force initialization
2381 <                if ((t = tab) == null && (t = tab = m.table) != null)
2382 <                    baseLimit = baseSize = t.length;
2383 <                if (t != null) {
2384 <                    long n = m.sumCount();
2385 <                    int par = ((pool = getPool()) == null) ?
2386 <                        ForkJoinPool.getCommonPoolParallelism() :
2387 <                        pool.getParallelism();
2388 <                    int sp = par << 3; // slack of 8
2389 <                    b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2390 <                }
2391 <            }
2392 <            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2393 <            if ((batch = b) > 0)
2394 <                addToPendingCount(1);
2395 <            return b;
2664 >        private final void lockRoot() {
2665 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2666 >                contendedLock(); // offload to separate method
2667          }
2668  
2669 <    }
2670 <
2671 <    /* ---------------- Public operations -------------- */
2672 <
2673 <    /**
2403 <     * Creates a new, empty map with the default initial table size (16).
2404 <     */
2405 <    public ConcurrentHashMapV8() {
2406 <    }
2407 <
2408 <    /**
2409 <     * Creates a new, empty map with an initial table size
2410 <     * accommodating the specified number of elements without the need
2411 <     * to dynamically resize.
2412 <     *
2413 <     * @param initialCapacity The implementation performs internal
2414 <     * sizing to accommodate this many elements.
2415 <     * @throws IllegalArgumentException if the initial capacity of
2416 <     * elements is negative
2417 <     */
2418 <    public ConcurrentHashMapV8(int initialCapacity) {
2419 <        if (initialCapacity < 0)
2420 <            throw new IllegalArgumentException();
2421 <        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2422 <                   MAXIMUM_CAPACITY :
2423 <                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2424 <        this.sizeCtl = cap;
2425 <    }
2426 <
2427 <    /**
2428 <     * Creates a new map with the same mappings as the given map.
2429 <     *
2430 <     * @param m the map
2431 <     */
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;
2669 >        /**
2670 >         * Releases write lock for tree restructuring.
2671 >         */
2672 >        private final void unlockRoot() {
2673 >            lockState = 0;
2674          }
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    }
2675  
2676 <    /**
2677 <     * If the specified key is not already associated with a value,
2678 <     * computes its value using the given mappingFunction and enters
2679 <     * it into the map unless null.  This is equivalent to
2680 <     * <pre> {@code
2681 <     * if (map.containsKey(key))
2682 <     *   return map.get(key);
2683 <     * value = mappingFunction.apply(key);
2684 <     * if (value != null)
2685 <     *   map.put(key, value);
2686 <     * return value;}</pre>
2687 <     *
2688 <     * except that the action is performed atomically.  If the
2689 <     * function returns {@code null} no mapping is recorded. If the
2690 <     * function itself throws an (unchecked) exception, the exception
2691 <     * is rethrown to its caller, and no mapping is recorded.  Some
2692 <     * attempted update operations on this map by other threads may be
2693 <     * blocked while computation is in progress, so the computation
2694 <     * should be short and simple, and must not attempt to update any
2695 <     * other mappings of this Map. The most appropriate usage is to
2696 <     * construct a new object serving as an initial mapped value, or
2697 <     * memoized result, as in:
2698 <     *
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 <    }
2676 >        /**
2677 >         * Possibly blocks awaiting root lock.
2678 >         */
2679 >        private final void contendedLock() {
2680 >            boolean waiting = false;
2681 >            for (int s;;) {
2682 >                if (((s = lockState) & WRITER) == 0) {
2683 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2684 >                        if (waiting)
2685 >                            waiter = null;
2686 >                        return;
2687 >                    }
2688 >                }
2689 >                else if ((s & WAITER) == 0) {
2690 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2691 >                        waiting = true;
2692 >                        waiter = Thread.currentThread();
2693 >                    }
2694 >                }
2695 >                else if (waiting)
2696 >                    LockSupport.park(this);
2697 >            }
2698 >        }
2699  
2700 <    /**
2701 <     * If the specified key is not already associated
2702 <     * with a value, associate it with the given value.
2703 <     * Otherwise, replace the value with the results of
2704 <     * the given remapping function. This is equivalent to:
2705 <     *  <pre> {@code
2706 <     *   if (!map.containsKey(key))
2707 <     *     map.put(value);
2708 <     *   else {
2709 <     *     newValue = remappingFunction.apply(map.get(key), value);
2710 <     *     if (value != null)
2711 <     *       map.put(key, value);
2712 <     *     else
2713 <     *       map.remove(key);
2714 <     *   }
2715 <     * }</pre>
2716 <     * except that the action is performed atomically.  If the
2717 <     * function returns {@code null}, the mapping is removed.  If the
2718 <     * function itself throws an (unchecked) exception, the exception
2719 <     * is rethrown to its caller, and the current mapping is left
2720 <     * unchanged.  Some attempted update operations on this map by
2721 <     * other threads may be blocked while computation is in progress,
2722 <     * so the computation should be short and simple, and must not
2723 <     * attempt to update any other mappings of this Map.
2724 <     */
2725 <    public V merge
2726 <        (K key, V value,
2727 <         BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2728 <        return internalMerge(key, value, remappingFunction);
2729 <    }
2700 >        /**
2701 >         * Returns matching node or null if none. Tries to search
2702 >         * using tree comparisons from root, but continues linear
2703 >         * search when lock not available.
2704 >         */
2705 > final Node<K,V> find(int h, Object k) {
2706 >            if (k != null) {
2707 >                for (Node<K,V> e = first; e != null; e = e.next) {
2708 >                    int s; K ek;
2709 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2710 >                        if (e.hash == h &&
2711 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2712 >                            return e;
2713 >                    }
2714 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2715 >                                                 s + READER)) {
2716 >                        TreeNode<K,V> r, p;
2717 >                        try {
2718 >                            p = ((r = root) == null ? null :
2719 >                                 r.findTreeNode(h, k, null));
2720 >                        } finally {
2721 >                            Thread w;
2722 >                            int ls;
2723 >                            do {} while (!U.compareAndSwapInt
2724 >                                         (this, LOCKSTATE,
2725 >                                          ls = lockState, ls - READER));
2726 >                            if (ls == (READER|WAITER) && (w = waiter) != null)
2727 >                                LockSupport.unpark(w);
2728 >                        }
2729 >                        return p;
2730 >                    }
2731 >                }
2732 >            }
2733 >            return null;
2734 >        }
2735  
2736 <    /**
2737 <     * Removes the key (and its corresponding value) from this map.
2738 <     * This method does nothing if the key is not in the map.
2739 <     *
2740 <     * @param  key the key that needs to be removed
2741 <     * @return the previous value associated with {@code key}, or
2742 <     *         {@code null} if there was no mapping for {@code key}
2743 <     * @throws NullPointerException if the specified key is null
2744 <     */
2745 <    public V remove(Object key) {
2746 <        return internalReplace(key, null, null);
2747 <    }
2736 >        /**
2737 >         * Finds or adds a node.
2738 >         * @return null if added
2739 >         */
2740 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2741 >            Class<?> kc = null;
2742 >            boolean searched = false;
2743 >            for (TreeNode<K,V> p = root;;) {
2744 >                int dir, ph; K pk;
2745 >                if (p == null) {
2746 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2747 >                    break;
2748 >                }
2749 >                else if ((ph = p.hash) > h)
2750 >                    dir = -1;
2751 >                else if (ph < h)
2752 >                    dir = 1;
2753 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2754 >                    return p;
2755 >                else if ((kc == null &&
2756 >                          (kc = comparableClassFor(k)) == null) ||
2757 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2758 >                    if (!searched) {
2759 >                        TreeNode<K,V> q, ch;
2760 >                        searched = true;
2761 >                        if (((ch = p.left) != null &&
2762 >                             (q = ch.findTreeNode(h, k, kc)) != null) ||
2763 >                            ((ch = p.right) != null &&
2764 >                             (q = ch.findTreeNode(h, k, kc)) != null))
2765 >                            return q;
2766 >                    }
2767 >                    dir = tieBreakOrder(k, pk);
2768 >                }
2769 >
2770 >                TreeNode<K,V> xp = p;
2771 >                if ((p = (dir <= 0) ? p.left : p.right) == null) {
2772 >                    TreeNode<K,V> x, f = first;
2773 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2774 >                    if (f != null)
2775 >                        f.prev = x;
2776 >                    if (dir <= 0)
2777 >                        xp.left = x;
2778 >                    else
2779 >                        xp.right = x;
2780 >                    if (!xp.red)
2781 >                        x.red = true;
2782 >                    else {
2783 >                        lockRoot();
2784 >                        try {
2785 >                            root = balanceInsertion(root, x);
2786 >                        } finally {
2787 >                            unlockRoot();
2788 >                        }
2789 >                    }
2790 >                    break;
2791 >                }
2792 >            }
2793 >            assert checkInvariants(root);
2794 >            return null;
2795 >        }
2796  
2797 <    /**
2798 <     * {@inheritDoc}
2799 <     *
2800 <     * @throws NullPointerException if the specified key is null
2801 <     */
2802 <    public boolean remove(Object key, Object value) {
2803 <        return value != null && internalReplace(key, null, value) != null;
2804 <    }
2797 >        /**
2798 >         * Removes the given node, that must be present before this
2799 >         * call.  This is messier than typical red-black deletion code
2800 >         * because we cannot swap the contents of an interior node
2801 >         * with a leaf successor that is pinned by "next" pointers
2802 >         * that are accessible independently of lock. So instead we
2803 >         * swap the tree linkages.
2804 >         *
2805 >         * @return true if now too small, so should be untreeified
2806 >         */
2807 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2808 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2809 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2810 >            TreeNode<K,V> r, rl;
2811 >            if (pred == null)
2812 >                first = next;
2813 >            else
2814 >                pred.next = next;
2815 >            if (next != null)
2816 >                next.prev = pred;
2817 >            if (first == null) {
2818 >                root = null;
2819 >                return true;
2820 >            }
2821 >            if ((r = root) == null || r.right == null || // too small
2822 >                (rl = r.left) == null || rl.left == null)
2823 >                return true;
2824 >            lockRoot();
2825 >            try {
2826 >                TreeNode<K,V> replacement;
2827 >                TreeNode<K,V> pl = p.left;
2828 >                TreeNode<K,V> pr = p.right;
2829 >                if (pl != null && pr != null) {
2830 >                    TreeNode<K,V> s = pr, sl;
2831 >                    while ((sl = s.left) != null) // find successor
2832 >                        s = sl;
2833 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2834 >                    TreeNode<K,V> sr = s.right;
2835 >                    TreeNode<K,V> pp = p.parent;
2836 >                    if (s == pr) { // p was s's direct parent
2837 >                        p.parent = s;
2838 >                        s.right = p;
2839 >                    }
2840 >                    else {
2841 >                        TreeNode<K,V> sp = s.parent;
2842 >                        if ((p.parent = sp) != null) {
2843 >                            if (s == sp.left)
2844 >                                sp.left = p;
2845 >                            else
2846 >                                sp.right = p;
2847 >                        }
2848 >                        if ((s.right = pr) != null)
2849 >                            pr.parent = s;
2850 >                    }
2851 >                    p.left = null;
2852 >                    if ((p.right = sr) != null)
2853 >                        sr.parent = p;
2854 >                    if ((s.left = pl) != null)
2855 >                        pl.parent = s;
2856 >                    if ((s.parent = pp) == null)
2857 >                        r = s;
2858 >                    else if (p == pp.left)
2859 >                        pp.left = s;
2860 >                    else
2861 >                        pp.right = s;
2862 >                    if (sr != null)
2863 >                        replacement = sr;
2864 >                    else
2865 >                        replacement = p;
2866 >                }
2867 >                else if (pl != null)
2868 >                    replacement = pl;
2869 >                else if (pr != null)
2870 >                    replacement = pr;
2871 >                else
2872 >                    replacement = p;
2873 >                if (replacement != p) {
2874 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2875 >                    if (pp == null)
2876 >                        r = replacement;
2877 >                    else if (p == pp.left)
2878 >                        pp.left = replacement;
2879 >                    else
2880 >                        pp.right = replacement;
2881 >                    p.left = p.right = p.parent = null;
2882 >                }
2883  
2884 <    /**
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 <    }
2884 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2885  
2886 <    /**
2887 <     * {@inheritDoc}
2888 <     *
2889 <     * @return the previous value associated with the specified key,
2890 <     *         or {@code null} if there was no mapping for the key
2891 <     * @throws NullPointerException if the specified key or value is null
2892 <     */
2893 <    public V replace(K key, V value) {
2894 <        if (key == null || value == null)
2895 <            throw new NullPointerException();
2896 <        return internalReplace(key, value, null);
2897 <    }
2898 <
2899 <    /**
2900 <     * Removes all of the mappings from this map.
2901 <     */
2874 <    public void clear() {
2875 <        internalClear();
2876 <    }
2886 >                if (p == replacement) {  // detach pointers
2887 >                    TreeNode<K,V> pp;
2888 >                    if ((pp = p.parent) != null) {
2889 >                        if (p == pp.left)
2890 >                            pp.left = null;
2891 >                        else if (p == pp.right)
2892 >                            pp.right = null;
2893 >                        p.parent = null;
2894 >                    }
2895 >                }
2896 >            } finally {
2897 >                unlockRoot();
2898 >            }
2899 >            assert checkInvariants(root);
2900 >            return false;
2901 >        }
2902  
2903 <    /**
2904 <     * 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 <    }
2903 >        /* ------------------------------------------------------------ */
2904 >        // Red-black tree methods, all adapted from CLR
2905  
2906 <    /**
2907 <     * Returns a {@link Set} view of the keys in this map, using the
2908 <     * given common mapped value for any additions (i.e., {@link
2909 <     * Collection#add} and {@link Collection#addAll}). This is of
2910 <     * course only appropriate if it is acceptable to use the same
2911 <     * value for all additions from this view.
2912 <     *
2913 <     * @param mappedValue the mapped value to use for any additions
2914 <     * @return the set view
2915 <     * @throws NullPointerException if the mappedValue is null
2916 <     */
2917 <    public KeySetView<K,V> keySet(V mappedValue) {
2918 <        if (mappedValue == null)
2919 <            throw new NullPointerException();
2920 <        return new KeySetView<K,V>(this, mappedValue);
2921 <    }
2906 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2907 >                                              TreeNode<K,V> p) {
2908 >            TreeNode<K,V> r, pp, rl;
2909 >            if (p != null && (r = p.right) != null) {
2910 >                if ((rl = p.right = r.left) != null)
2911 >                    rl.parent = p;
2912 >                if ((pp = r.parent = p.parent) == null)
2913 >                    (root = r).red = false;
2914 >                else if (pp.left == p)
2915 >                    pp.left = r;
2916 >                else
2917 >                    pp.right = r;
2918 >                r.left = p;
2919 >                p.parent = r;
2920 >            }
2921 >            return root;
2922 >        }
2923  
2924 <    /**
2925 <     * Returns a {@link Collection} view of the values contained in this map.
2926 <     * The collection is backed by the map, so changes to the map are
2927 <     * reflected in the collection, and vice-versa.
2928 <     */
2929 <    public ValuesView<K,V> values() {
2930 <        ValuesView<K,V> vs = values;
2931 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2932 <    }
2924 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2925 >                                               TreeNode<K,V> p) {
2926 >            TreeNode<K,V> l, pp, lr;
2927 >            if (p != null && (l = p.left) != null) {
2928 >                if ((lr = p.left = l.right) != null)
2929 >                    lr.parent = p;
2930 >                if ((pp = l.parent = p.parent) == null)
2931 >                    (root = l).red = false;
2932 >                else if (pp.right == p)
2933 >                    pp.right = l;
2934 >                else
2935 >                    pp.left = l;
2936 >                l.right = p;
2937 >                p.parent = l;
2938 >            }
2939 >            return root;
2940 >        }
2941  
2942 <    /**
2943 <     * Returns a {@link Set} view of the mappings contained in this map.
2944 <     * The set is backed by the map, so changes to the map are
2945 <     * reflected in the set, and vice-versa.  The set supports element
2946 <     * removal, which removes the corresponding mapping from the map,
2947 <     * via the {@code Iterator.remove}, {@code Set.remove},
2948 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
2949 <     * operations.  It does not support the {@code add} or
2950 <     * {@code addAll} operations.
2951 <     *
2952 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2953 <     * that will never throw {@link ConcurrentModificationException},
2954 <     * and guarantees to traverse elements as they existed upon
2955 <     * construction of the iterator, and may (but is not guaranteed to)
2956 <     * reflect any modifications subsequent to construction.
2957 <     */
2958 <    public Set<Map.Entry<K,V>> entrySet() {
2959 <        EntrySetView<K,V> es = entrySet;
2960 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2961 <    }
2942 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2943 >                                                    TreeNode<K,V> x) {
2944 >            x.red = true;
2945 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2946 >                if ((xp = x.parent) == null) {
2947 >                    x.red = false;
2948 >                    return x;
2949 >                }
2950 >                else if (!xp.red || (xpp = xp.parent) == null)
2951 >                    return root;
2952 >                if (xp == (xppl = xpp.left)) {
2953 >                    if ((xppr = xpp.right) != null && xppr.red) {
2954 >                        xppr.red = false;
2955 >                        xp.red = false;
2956 >                        xpp.red = true;
2957 >                        x = xpp;
2958 >                    }
2959 >                    else {
2960 >                        if (x == xp.right) {
2961 >                            root = rotateLeft(root, x = xp);
2962 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2963 >                        }
2964 >                        if (xp != null) {
2965 >                            xp.red = false;
2966 >                            if (xpp != null) {
2967 >                                xpp.red = true;
2968 >                                root = rotateRight(root, xpp);
2969 >                            }
2970 >                        }
2971 >                    }
2972 >                }
2973 >                else {
2974 >                    if (xppl != null && xppl.red) {
2975 >                        xppl.red = false;
2976 >                        xp.red = false;
2977 >                        xpp.red = true;
2978 >                        x = xpp;
2979 >                    }
2980 >                    else {
2981 >                        if (x == xp.left) {
2982 >                            root = rotateRight(root, x = xp);
2983 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2984 >                        }
2985 >                        if (xp != null) {
2986 >                            xp.red = false;
2987 >                            if (xpp != null) {
2988 >                                xpp.red = true;
2989 >                                root = rotateLeft(root, xpp);
2990 >                            }
2991 >                        }
2992 >                    }
2993 >                }
2994 >            }
2995 >        }
2996  
2997 <    /**
2998 <     * Returns an enumeration of the keys in this table.
2999 <     *
3000 <     * @return an enumeration of the keys in this table
3001 <     * @see #keySet()
3002 <     */
3003 <    public Enumeration<K> keys() {
3004 <        return new KeyIterator<K,V>(this);
3005 <    }
2997 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2998 >                                                   TreeNode<K,V> x) {
2999 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
3000 >                if (x == null || x == root)
3001 >                    return root;
3002 >                else if ((xp = x.parent) == null) {
3003 >                    x.red = false;
3004 >                    return x;
3005 >                }
3006 >                else if (x.red) {
3007 >                    x.red = false;
3008 >                    return root;
3009 >                }
3010 >                else if ((xpl = xp.left) == x) {
3011 >                    if ((xpr = xp.right) != null && xpr.red) {
3012 >                        xpr.red = false;
3013 >                        xp.red = true;
3014 >                        root = rotateLeft(root, xp);
3015 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3016 >                    }
3017 >                    if (xpr == null)
3018 >                        x = xp;
3019 >                    else {
3020 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3021 >                        if ((sr == null || !sr.red) &&
3022 >                            (sl == null || !sl.red)) {
3023 >                            xpr.red = true;
3024 >                            x = xp;
3025 >                        }
3026 >                        else {
3027 >                            if (sr == null || !sr.red) {
3028 >                                if (sl != null)
3029 >                                    sl.red = false;
3030 >                                xpr.red = true;
3031 >                                root = rotateRight(root, xpr);
3032 >                                xpr = (xp = x.parent) == null ?
3033 >                                    null : xp.right;
3034 >                            }
3035 >                            if (xpr != null) {
3036 >                                xpr.red = (xp == null) ? false : xp.red;
3037 >                                if ((sr = xpr.right) != null)
3038 >                                    sr.red = false;
3039 >                            }
3040 >                            if (xp != null) {
3041 >                                xp.red = false;
3042 >                                root = rotateLeft(root, xp);
3043 >                            }
3044 >                            x = root;
3045 >                        }
3046 >                    }
3047 >                }
3048 >                else { // symmetric
3049 >                    if (xpl != null && xpl.red) {
3050 >                        xpl.red = false;
3051 >                        xp.red = true;
3052 >                        root = rotateRight(root, xp);
3053 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3054 >                    }
3055 >                    if (xpl == null)
3056 >                        x = xp;
3057 >                    else {
3058 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3059 >                        if ((sl == null || !sl.red) &&
3060 >                            (sr == null || !sr.red)) {
3061 >                            xpl.red = true;
3062 >                            x = xp;
3063 >                        }
3064 >                        else {
3065 >                            if (sl == null || !sl.red) {
3066 >                                if (sr != null)
3067 >                                    sr.red = false;
3068 >                                xpl.red = true;
3069 >                                root = rotateLeft(root, xpl);
3070 >                                xpl = (xp = x.parent) == null ?
3071 >                                    null : xp.left;
3072 >                            }
3073 >                            if (xpl != null) {
3074 >                                xpl.red = (xp == null) ? false : xp.red;
3075 >                                if ((sl = xpl.left) != null)
3076 >                                    sl.red = false;
3077 >                            }
3078 >                            if (xp != null) {
3079 >                                xp.red = false;
3080 >                                root = rotateRight(root, xp);
3081 >                            }
3082 >                            x = root;
3083 >                        }
3084 >                    }
3085 >                }
3086 >            }
3087 >        }
3088  
3089 <    /**
3090 <     * Returns an enumeration of the values in this table.
3091 <     *
3092 <     * @return an enumeration of the values in this table
3093 <     * @see #values()
3094 <     */
3095 <    public Enumeration<V> elements() {
3096 <        return new ValueIterator<K,V>(this);
3097 <    }
3089 >        /**
3090 >         * Recursive invariant check
3091 >         */
3092 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3093 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3094 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3095 >            if (tb != null && tb.next != t)
3096 >                return false;
3097 >            if (tn != null && tn.prev != t)
3098 >                return false;
3099 >            if (tp != null && t != tp.left && t != tp.right)
3100 >                return false;
3101 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3102 >                return false;
3103 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3104 >                return false;
3105 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3106 >                return false;
3107 >            if (tl != null && !checkInvariants(tl))
3108 >                return false;
3109 >            if (tr != null && !checkInvariants(tr))
3110 >                return false;
3111 >            return true;
3112 >        }
3113  
3114 <    /**
3115 <     * Returns a partitionable iterator of the keys in this map.
3116 <     *
3117 <     * @return a partitionable iterator of the keys in this map
3118 <     */
3119 <    public Spliterator<K> keySpliterator() {
3120 <        return new KeyIterator<K,V>(this);
3114 >        private static final sun.misc.Unsafe U;
3115 >        private static final long LOCKSTATE;
3116 >        static {
3117 >            try {
3118 >                U = getUnsafe();
3119 >                Class<?> k = TreeBin.class;
3120 >                LOCKSTATE = U.objectFieldOffset
3121 >                    (k.getDeclaredField("lockState"));
3122 >            } catch (Exception e) {
3123 >                throw new Error(e);
3124 >            }
3125 >        }
3126      }
3127  
3128 <    /**
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 <    }
3128 >    /* ----------------Table Traversal -------------- */
3129  
3130      /**
3131 <     * Returns a partitionable iterator of the entries in this map.
3131 >     * Encapsulates traversal for methods such as containsValue; also
3132 >     * serves as a base class for other iterators and spliterators.
3133       *
3134 <     * @return a partitionable iterator of the entries in this map
3135 <     */
3136 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
3137 <        return new EntryIterator<K,V>(this);
3138 <    }
3139 <
3140 <    /**
3141 <     * 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()}.
3134 >     * Method advance visits once each still-valid node that was
3135 >     * reachable upon iterator construction. It might miss some that
3136 >     * were added to a bin after the bin was visited, which is OK wrt
3137 >     * consistency guarantees. Maintaining this property in the face
3138 >     * of possible ongoing resizes requires a fair amount of
3139 >     * bookkeeping state that is difficult to optimize away amidst
3140 >     * volatile accesses.  Even so, traversal maintains reasonable
3141 >     * throughput.
3142       *
3143 <     * @return the hash code value for this map
3143 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3144 >     * However, if the table has been resized, then all future steps
3145 >     * must traverse both the bin at the current index as well as at
3146 >     * (index + baseSize); and so on for further resizings. To
3147 >     * paranoically cope with potential sharing by users of iterators
3148 >     * across threads, iteration terminates if a bounds checks fails
3149 >     * for a table read.
3150       */
3151 <    public int hashCode() {
3152 <        int h = 0;
3153 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3154 <        V v;
3155 <        while ((v = it.advance()) != null) {
3156 <            h += it.nextKey.hashCode() ^ v.hashCode();
3151 >    static class Traverser<K,V> {
3152 >        Node<K,V>[] tab;        // current table; updated if resized
3153 >        Node<K,V> next;         // the next entry to use
3154 >        int index;              // index of bin to use next
3155 >        int baseIndex;          // current index of initial table
3156 >        int baseLimit;          // index bound for initial table
3157 >        final int baseSize;     // initial table size
3158 >
3159 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3160 >            this.tab = tab;
3161 >            this.baseSize = size;
3162 >            this.baseIndex = this.index = index;
3163 >            this.baseLimit = limit;
3164 >            this.next = null;
3165          }
2999        return h;
3000    }
3166  
3167 <    /**
3168 <     * Returns a string representation of this map.  The string
3169 <     * representation consists of a list of key-value mappings (in no
3170 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3171 <     * mappings are separated by the characters {@code ", "} (comma
3172 <     * and space).  Each key-value mapping is rendered as the key
3173 <     * 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) {
3167 >        /**
3168 >         * Advances if possible, returning next valid node, or null if none.
3169 >         */
3170 >        final Node<K,V> advance() {
3171 >            Node<K,V> e;
3172 >            if ((e = next) != null)
3173 >                e = e.next;
3174              for (;;) {
3175 <                Object k = it.nextKey;
3176 <                sb.append(k == this ? "(this Map)" : k);
3177 <                sb.append('=');
3178 <                sb.append(v == this ? "(this Map)" : v);
3179 <                if ((v = it.advance()) == null)
3180 <                    break;
3181 <                sb.append(',').append(' ');
3175 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
3176 >                if (e != null)
3177 >                    return next = e;
3178 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3179 >                    (n = t.length) <= (i = index) || i < 0)
3180 >                    return next = null;
3181 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
3182 >                    if (e instanceof ForwardingNode) {
3183 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3184 >                        e = null;
3185 >                        continue;
3186 >                    }
3187 >                    else if (e instanceof TreeBin)
3188 >                        e = ((TreeBin<K,V>)e).first;
3189 >                    else
3190 >                        e = null;
3191 >                }
3192 >                if ((index += baseSize) >= n)
3193 >                    index = ++baseIndex;    // visit upper slots if present
3194              }
3195          }
3029        return sb.append('}').toString();
3196      }
3197  
3198      /**
3199 <     * Compares the specified object with this map for equality.
3200 <     * 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
3199 >     * Base of key, value, and entry Iterators. Adds fields to
3200 >     * Traverser to support iterator.remove.
3201       */
3202 <    public boolean equals(Object o) {
3203 <        if (o != this) {
3204 <            if (!(o instanceof Map))
3205 <                return false;
3206 <            Map<?,?> m = (Map<?,?>) o;
3207 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3208 <            V val;
3209 <            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 <            }
3202 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3203 >        final ConcurrentHashMapV8<K,V> map;
3204 >        Node<K,V> lastReturned;
3205 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3206 >                    ConcurrentHashMapV8<K,V> map) {
3207 >            super(tab, size, index, limit);
3208 >            this.map = map;
3209 >            advance();
3210          }
3063        return true;
3064    }
3211  
3212 <    /* ----------------Iterators -------------- */
3212 >        public final boolean hasNext() { return next != null; }
3213 >        public final boolean hasMoreElements() { return next != null; }
3214  
3215 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3216 <        extends Traverser<K,V,Object>
3217 <        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)
3215 >        public final void remove() {
3216 >            Node<K,V> p;
3217 >            if ((p = lastReturned) == null)
3218                  throw new IllegalStateException();
3219 <            return new KeyIterator<K,V>(map, this);
3219 >            lastReturned = null;
3220 >            map.replaceNode(p.key, null, null);
3221          }
3222 <        @SuppressWarnings("unchecked") public final K next() {
3223 <            if (nextVal == null && advance() == null)
3222 >    }
3223 >
3224 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3225 >        implements Iterator<K>, Enumeration<K> {
3226 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3227 >                    ConcurrentHashMapV8<K,V> map) {
3228 >            super(tab, index, size, limit, map);
3229 >        }
3230 >
3231 >        public final K next() {
3232 >            Node<K,V> p;
3233 >            if ((p = next) == null)
3234                  throw new NoSuchElementException();
3235 <            Object k = nextKey;
3236 <            nextVal = null;
3237 <            return (K) k;
3235 >            K k = p.key;
3236 >            lastReturned = p;
3237 >            advance();
3238 >            return k;
3239          }
3240  
3241          public final K nextElement() { return next(); }
3242      }
3243  
3244 <    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3245 <        extends Traverser<K,V,Object>
3246 <        implements Spliterator<V>, Enumeration<V> {
3247 <        ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3248 <        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);
3244 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3245 >        implements Iterator<V>, Enumeration<V> {
3246 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3247 >                      ConcurrentHashMapV8<K,V> map) {
3248 >            super(tab, index, size, limit, map);
3249          }
3250  
3251          public final V next() {
3252 <            V v;
3253 <            if ((v = nextVal) == null && (v = advance()) == null)
3252 >            Node<K,V> p;
3253 >            if ((p = next) == null)
3254                  throw new NoSuchElementException();
3255 <            nextVal = null;
3255 >            V v = p.val;
3256 >            lastReturned = p;
3257 >            advance();
3258              return v;
3259          }
3260  
3261          public final V nextElement() { return next(); }
3262      }
3263  
3264 <    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3265 <        extends Traverser<K,V,Object>
3266 <        implements Spliterator<Map.Entry<K,V>> {
3267 <        EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3268 <        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);
3264 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3265 >        implements Iterator<Map.Entry<K,V>> {
3266 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3267 >                      ConcurrentHashMapV8<K,V> map) {
3268 >            super(tab, index, size, limit, map);
3269          }
3270  
3271 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3272 <            V v;
3273 <            if ((v = nextVal) == null && (v = advance()) == null)
3271 >        public final Map.Entry<K,V> next() {
3272 >            Node<K,V> p;
3273 >            if ((p = next) == null)
3274                  throw new NoSuchElementException();
3275 <            Object k = nextKey;
3276 <            nextVal = null;
3277 <            return new MapEntry<K,V>((K)k, v, map);
3275 >            K k = p.key;
3276 >            V v = p.val;
3277 >            lastReturned = p;
3278 >            advance();
3279 >            return new MapEntry<K,V>(k, v, map);
3280          }
3281      }
3282  
3283      /**
3284 <     * Exported Entry for iterators
3284 >     * Exported Entry for EntryIterator
3285       */
3286 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3286 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3287          final K key; // non-null
3288          V val;       // non-null
3289 <        final ConcurrentHashMapV8<K, V> map;
3290 <        MapEntry(K key, V val, ConcurrentHashMapV8<K, V> map) {
3289 >        final ConcurrentHashMapV8<K,V> map;
3290 >        MapEntry(K key, V val, ConcurrentHashMapV8<K,V> map) {
3291              this.key = key;
3292              this.val = val;
3293              this.map = map;
3294          }
3295 <        public final K getKey()       { return key; }
3296 <        public final V getValue()     { return val; }
3297 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3298 <        public final String toString(){ return key + "=" + val; }
3295 >        public K getKey()        { return key; }
3296 >        public V getValue()      { return val; }
3297 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3298 >        public String toString() { return key + "=" + val; }
3299  
3300 <        public final boolean equals(Object o) {
3300 >        public boolean equals(Object o) {
3301              Object k, v; Map.Entry<?,?> e;
3302              return ((o instanceof Map.Entry) &&
3303                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3166 | Line 3311 | public class ConcurrentHashMapV8<K, V>
3311           * value to return is somewhat arbitrary here. Since we do not
3312           * necessarily track asynchronous changes, the most recent
3313           * "previous" value could be different from what we return (or
3314 <         * could even have been removed in which case the put will
3314 >         * could even have been removed, in which case the put will
3315           * re-establish). We do not and cannot guarantee more.
3316           */
3317 <        public final V setValue(V value) {
3317 >        public V setValue(V value) {
3318              if (value == null) throw new NullPointerException();
3319              V v = val;
3320              val = value;
# Line 3178 | Line 3323 | public class ConcurrentHashMapV8<K, V>
3323          }
3324      }
3325  
3326 <    /**
3327 <     * Returns exportable snapshot entry for the given key and value
3328 <     * when write-through can't or shouldn't be used.
3329 <     */
3330 <    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3331 <        return new AbstractMap.SimpleEntry<K,V>(k, v);
3332 <    }
3326 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3327 >        implements ConcurrentHashMapSpliterator<K> {
3328 >        long est;               // size estimate
3329 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3330 >                       long est) {
3331 >            super(tab, size, index, limit);
3332 >            this.est = est;
3333 >        }
3334 >
3335 >        public ConcurrentHashMapSpliterator<K> trySplit() {
3336 >            int i, f, h;
3337 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3338 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3339 >                                        f, est >>>= 1);
3340 >        }
3341  
3342 <    /* ---------------- Serialization Support -------------- */
3342 >        public void forEachRemaining(Action<? super K> action) {
3343 >            if (action == null) throw new NullPointerException();
3344 >            for (Node<K,V> p; (p = advance()) != null;)
3345 >                action.apply(p.key);
3346 >        }
3347 >
3348 >        public boolean tryAdvance(Action<? super K> action) {
3349 >            if (action == null) throw new NullPointerException();
3350 >            Node<K,V> p;
3351 >            if ((p = advance()) == null)
3352 >                return false;
3353 >            action.apply(p.key);
3354 >            return true;
3355 >        }
3356 >
3357 >        public long estimateSize() { return est; }
3358  
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; }
3359      }
3360  
3361 <    /**
3362 <     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
3363 <     * stream (i.e., serializes it).
3364 <     * @param s the stream
3365 <     * @serialData
3366 <     * the key (Object) and value (Object)
3367 <     * 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);
3361 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3362 >        implements ConcurrentHashMapSpliterator<V> {
3363 >        long est;               // size estimate
3364 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3365 >                         long est) {
3366 >            super(tab, size, index, limit);
3367 >            this.est = est;
3368          }
3369 <        s.defaultWriteObject();
3370 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3371 <        V v;
3372 <        while ((v = it.advance()) != null) {
3373 <            s.writeObject(it.nextKey);
3374 <            s.writeObject(v);
3369 >
3370 >        public ConcurrentHashMapSpliterator<V> trySplit() {
3371 >            int i, f, h;
3372 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3373 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3374 >                                          f, est >>>= 1);
3375          }
3376 <        s.writeObject(null);
3377 <        s.writeObject(null);
3378 <        segments = null; // throw away
3376 >
3377 >        public void forEachRemaining(Action<? super V> action) {
3378 >            if (action == null) throw new NullPointerException();
3379 >            for (Node<K,V> p; (p = advance()) != null;)
3380 >                action.apply(p.val);
3381 >        }
3382 >
3383 >        public boolean tryAdvance(Action<? super V> action) {
3384 >            if (action == null) throw new NullPointerException();
3385 >            Node<K,V> p;
3386 >            if ((p = advance()) == null)
3387 >                return false;
3388 >            action.apply(p.val);
3389 >            return true;
3390 >        }
3391 >
3392 >        public long estimateSize() { return est; }
3393 >
3394      }
3395  
3396 <    /**
3397 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3398 <     * @param s the stream
3399 <     */
3400 <    @SuppressWarnings("unchecked") private void readObject
3401 <        (java.io.ObjectInputStream s)
3402 <        throws java.io.IOException, ClassNotFoundException {
3403 <        s.defaultReadObject();
3404 <        this.segments = null; // unneeded
3396 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3397 >        implements ConcurrentHashMapSpliterator<Map.Entry<K,V>> {
3398 >        final ConcurrentHashMapV8<K,V> map; // To export MapEntry
3399 >        long est;               // size estimate
3400 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3401 >                         long est, ConcurrentHashMapV8<K,V> map) {
3402 >            super(tab, size, index, limit);
3403 >            this.map = map;
3404 >            this.est = est;
3405 >        }
3406  
3407 <        // Create all nodes, then place in table once size is known
3408 <        long size = 0L;
3409 <        Node<V> p = null;
3410 <        for (;;) {
3411 <            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;
3407 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> trySplit() {
3408 >            int i, f, h;
3409 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3410 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3411 >                                          f, est >>>= 1, map);
3412          }
3413 <        if (p != null) {
3414 <            boolean init = false;
3415 <            int n;
3416 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3417 <                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 <            }
3413 >
3414 >        public void forEachRemaining(Action<? super Map.Entry<K,V>> action) {
3415 >            if (action == null) throw new NullPointerException();
3416 >            for (Node<K,V> p; (p = advance()) != null; )
3417 >                action.apply(new MapEntry<K,V>(p.key, p.val, map));
3418          }
3311    }
3419  
3420 <    // -------------------------------------------------------
3420 >        public boolean tryAdvance(Action<? super Map.Entry<K,V>> action) {
3421 >            if (action == null) throw new NullPointerException();
3422 >            Node<K,V> p;
3423 >            if ((p = advance()) == null)
3424 >                return false;
3425 >            action.apply(new MapEntry<K,V>(p.key, p.val, map));
3426 >            return true;
3427 >        }
3428  
3429 <    // 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); }
3429 >        public long estimateSize() { return est; }
3430  
3431 +    }
3432  
3433 <    // -------------------------------------------------------
3433 >    // Parallel bulk operations
3434  
3435 <    // Sequential bulk operations
3435 >    /**
3436 >     * Computes initial batch value for bulk tasks. The returned value
3437 >     * is approximately exp2 of the number of times (minus one) to
3438 >     * split task by two before executing leaf action. This value is
3439 >     * faster to compute and more convenient to use as a guide to
3440 >     * splitting than is the depth, since it is used while dividing by
3441 >     * two anyway.
3442 >     */
3443 >    final int batchFor(long b) {
3444 >        long n;
3445 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3446 >            return 0;
3447 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3448 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3449 >    }
3450  
3451      /**
3452       * Performs the given action for each (key, value).
3453       *
3454 +     * @param parallelismThreshold the (estimated) number of elements
3455 +     * needed for this operation to be executed in parallel
3456       * @param action the action
3457 +     * @since 1.8
3458       */
3459 <    @SuppressWarnings("unchecked") public void forEachSequentially
3460 <        (BiAction<K,V> action) {
3459 >    public void forEach(long parallelismThreshold,
3460 >                        BiAction<? super K,? super V> action) {
3461          if (action == null) throw new NullPointerException();
3462 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3463 <        V v;
3464 <        while ((v = it.advance()) != null)
3367 <            action.apply((K)it.nextKey, v);
3462 >        new ForEachMappingTask<K,V>
3463 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3464 >             action).invoke();
3465      }
3466  
3467      /**
3468       * Performs the given action for each non-null transformation
3469       * of each (key, value).
3470       *
3471 +     * @param parallelismThreshold the (estimated) number of elements
3472 +     * needed for this operation to be executed in parallel
3473       * @param transformer a function returning the transformation
3474       * for an element, or null if there is no transformation (in
3475       * which case the action is not applied)
3476       * @param action the action
3477 +     * @since 1.8
3478       */
3479 <    @SuppressWarnings("unchecked") public <U> void forEachSequentially
3480 <        (BiFun<? super K, ? super V, ? extends U> transformer,
3481 <         Action<U> action) {
3479 >    public <U> void forEach(long parallelismThreshold,
3480 >                            BiFun<? super K, ? super V, ? extends U> transformer,
3481 >                            Action<? super U> action) {
3482          if (transformer == null || action == null)
3483              throw new NullPointerException();
3484 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3485 <        V v; U u;
3486 <        while ((v = it.advance()) != null) {
3387 <            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3388 <                action.apply(u);
3389 <        }
3484 >        new ForEachTransformedMappingTask<K,V,U>
3485 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3486 >             transformer, action).invoke();
3487      }
3488  
3489      /**
3490       * Returns a non-null result from applying the given search
3491 <     * function on each (key, value), or null if none.
3491 >     * function on each (key, value), or null if none.  Upon
3492 >     * success, further element processing is suppressed and the
3493 >     * results of any other parallel invocations of the search
3494 >     * function are ignored.
3495       *
3496 +     * @param parallelismThreshold the (estimated) number of elements
3497 +     * needed for this operation to be executed in parallel
3498       * @param searchFunction a function returning a non-null
3499       * result on success, else null
3500       * @return a non-null result from applying the given search
3501       * function on each (key, value), or null if none
3502 +     * @since 1.8
3503       */
3504 <    @SuppressWarnings("unchecked") public <U> U searchSequentially
3505 <        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
3504 >    public <U> U search(long parallelismThreshold,
3505 >                        BiFun<? super K, ? super V, ? extends U> searchFunction) {
3506          if (searchFunction == null) throw new NullPointerException();
3507 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3508 <        V v; U u;
3509 <        while ((v = it.advance()) != null) {
3407 <            if ((u = searchFunction.apply((K)it.nextKey, v)) != null)
3408 <                return u;
3409 <        }
3410 <        return null;
3507 >        return new SearchMappingsTask<K,V,U>
3508 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3509 >             searchFunction, new AtomicReference<U>()).invoke();
3510      }
3511  
3512      /**
# Line 3415 | Line 3514 | public class ConcurrentHashMapV8<K, V>
3514       * of all (key, value) pairs using the given reducer to
3515       * combine values, or null if none.
3516       *
3517 +     * @param parallelismThreshold the (estimated) number of elements
3518 +     * needed for this operation to be executed in parallel
3519       * @param transformer a function returning the transformation
3520       * for an element, or null if there is no transformation (in
3521       * which case it is not combined)
3522       * @param reducer a commutative associative combining function
3523       * @return the result of accumulating the given transformation
3524       * of all (key, value) pairs
3525 +     * @since 1.8
3526       */
3527 <    @SuppressWarnings("unchecked") public <U> U reduceSequentially
3528 <        (BiFun<? super K, ? super V, ? extends U> transformer,
3529 <         BiFun<? super U, ? super U, ? extends U> reducer) {
3527 >    public <U> U reduce(long parallelismThreshold,
3528 >                        BiFun<? super K, ? super V, ? extends U> transformer,
3529 >                        BiFun<? super U, ? super U, ? extends U> reducer) {
3530          if (transformer == null || reducer == null)
3531              throw new NullPointerException();
3532 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3533 <        U r = null, u; V v;
3534 <        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;
3532 >        return new MapReduceMappingsTask<K,V,U>
3533 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3534 >             null, transformer, reducer).invoke();
3535      }
3536  
3537      /**
# Line 3441 | Line 3539 | public class ConcurrentHashMapV8<K, V>
3539       * of all (key, value) pairs using the given reducer to
3540       * combine values, and the given basis as an identity value.
3541       *
3542 +     * @param parallelismThreshold the (estimated) number of elements
3543 +     * needed for this operation to be executed in parallel
3544       * @param transformer a function returning the transformation
3545       * for an element
3546       * @param basis the identity (initial default value) for the reduction
3547       * @param reducer a commutative associative combining function
3548       * @return the result of accumulating the given transformation
3549       * of all (key, value) pairs
3550 +     * @since 1.8
3551       */
3552 <    @SuppressWarnings("unchecked") public double reduceToDoubleSequentially
3553 <        (ObjectByObjectToDouble<? super K, ? super V> transformer,
3554 <         double basis,
3555 <         DoubleByDoubleToDouble reducer) {
3552 >    public double reduceToDouble(long parallelismThreshold,
3553 >                                 ObjectByObjectToDouble<? super K, ? super V> transformer,
3554 >                                 double basis,
3555 >                                 DoubleByDoubleToDouble reducer) {
3556          if (transformer == null || reducer == null)
3557              throw new NullPointerException();
3558 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3559 <        double r = basis; V v;
3560 <        while ((v = it.advance()) != null)
3460 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3461 <        return r;
3558 >        return new MapReduceMappingsToDoubleTask<K,V>
3559 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3560 >             null, transformer, basis, reducer).invoke();
3561      }
3562  
3563      /**
# Line 3466 | Line 3565 | public class ConcurrentHashMapV8<K, V>
3565       * of all (key, value) pairs using the given reducer to
3566       * combine values, and the given basis as an identity value.
3567       *
3568 +     * @param parallelismThreshold the (estimated) number of elements
3569 +     * needed for this operation to be executed in parallel
3570       * @param transformer a function returning the transformation
3571       * for an element
3572       * @param basis the identity (initial default value) for the reduction
3573       * @param reducer a commutative associative combining function
3574       * @return the result of accumulating the given transformation
3575       * of all (key, value) pairs
3576 +     * @since 1.8
3577       */
3578 <    @SuppressWarnings("unchecked") public long reduceToLongSequentially
3579 <        (ObjectByObjectToLong<? super K, ? super V> transformer,
3580 <         long basis,
3581 <         LongByLongToLong reducer) {
3578 >    public long reduceToLong(long parallelismThreshold,
3579 >                             ObjectByObjectToLong<? super K, ? super V> transformer,
3580 >                             long basis,
3581 >                             LongByLongToLong reducer) {
3582          if (transformer == null || reducer == null)
3583              throw new NullPointerException();
3584 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3585 <        long r = basis; V v;
3586 <        while ((v = it.advance()) != null)
3485 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3486 <        return r;
3584 >        return new MapReduceMappingsToLongTask<K,V>
3585 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3586 >             null, transformer, basis, reducer).invoke();
3587      }
3588  
3589      /**
# Line 3491 | Line 3591 | public class ConcurrentHashMapV8<K, V>
3591       * of all (key, value) pairs using the given reducer to
3592       * combine values, and the given basis as an identity value.
3593       *
3594 +     * @param parallelismThreshold the (estimated) number of elements
3595 +     * needed for this operation to be executed in parallel
3596       * @param transformer a function returning the transformation
3597       * for an element
3598       * @param basis the identity (initial default value) for the reduction
3599       * @param reducer a commutative associative combining function
3600       * @return the result of accumulating the given transformation
3601       * of all (key, value) pairs
3602 +     * @since 1.8
3603       */
3604 <    @SuppressWarnings("unchecked") public int reduceToIntSequentially
3605 <        (ObjectByObjectToInt<? super K, ? super V> transformer,
3606 <         int basis,
3607 <         IntByIntToInt reducer) {
3604 >    public int reduceToInt(long parallelismThreshold,
3605 >                           ObjectByObjectToInt<? super K, ? super V> transformer,
3606 >                           int basis,
3607 >                           IntByIntToInt reducer) {
3608          if (transformer == null || reducer == null)
3609              throw new NullPointerException();
3610 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3611 <        int r = basis; V v;
3612 <        while ((v = it.advance()) != null)
3510 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3511 <        return r;
3610 >        return new MapReduceMappingsToIntTask<K,V>
3611 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3612 >             null, transformer, basis, reducer).invoke();
3613      }
3614  
3615      /**
3616       * Performs the given action for each key.
3617       *
3618 +     * @param parallelismThreshold the (estimated) number of elements
3619 +     * needed for this operation to be executed in parallel
3620       * @param action the action
3621 +     * @since 1.8
3622       */
3623 <    @SuppressWarnings("unchecked") public void forEachKeySequentially
3624 <        (Action<K> action) {
3623 >    public void forEachKey(long parallelismThreshold,
3624 >                           Action<? super K> action) {
3625          if (action == null) throw new NullPointerException();
3626 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3627 <        while (it.advance() != null)
3628 <            action.apply((K)it.nextKey);
3626 >        new ForEachKeyTask<K,V>
3627 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3628 >             action).invoke();
3629      }
3630  
3631      /**
3632       * Performs the given action for each non-null transformation
3633       * of each key.
3634       *
3635 +     * @param parallelismThreshold the (estimated) number of elements
3636 +     * needed for this operation to be executed in parallel
3637       * @param transformer a function returning the transformation
3638       * for an element, or null if there is no transformation (in
3639       * which case the action is not applied)
3640       * @param action the action
3641 +     * @since 1.8
3642       */
3643 <    @SuppressWarnings("unchecked") public <U> void forEachKeySequentially
3644 <        (Fun<? super K, ? extends U> transformer,
3645 <         Action<U> action) {
3643 >    public <U> void forEachKey(long parallelismThreshold,
3644 >                               Fun<? super K, ? extends U> transformer,
3645 >                               Action<? super U> action) {
3646          if (transformer == null || action == null)
3647              throw new NullPointerException();
3648 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3649 <        U u;
3650 <        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();
3648 >        new ForEachTransformedKeyTask<K,V,U>
3649 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3650 >             transformer, action).invoke();
3651      }
3652  
3653      /**
3654       * Returns a non-null result from applying the given search
3655 <     * function on each key, or null if none.
3655 >     * function on each key, or null if none. Upon success,
3656 >     * further element processing is suppressed and the results of
3657 >     * any other parallel invocations of the search function are
3658 >     * ignored.
3659       *
3660 +     * @param parallelismThreshold the (estimated) number of elements
3661 +     * needed for this operation to be executed in parallel
3662       * @param searchFunction a function returning a non-null
3663       * result on success, else null
3664       * @return a non-null result from applying the given search
3665       * function on each key, or null if none
3666 +     * @since 1.8
3667       */
3668 <    @SuppressWarnings("unchecked") public <U> U searchKeysSequentially
3669 <        (Fun<? super K, ? extends U> searchFunction) {
3670 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3671 <        U u;
3672 <        while (it.advance() != null) {
3673 <            if ((u = searchFunction.apply((K)it.nextKey)) != null)
3566 <                return u;
3567 <        }
3568 <        return null;
3668 >    public <U> U searchKeys(long parallelismThreshold,
3669 >                            Fun<? super K, ? extends U> searchFunction) {
3670 >        if (searchFunction == null) throw new NullPointerException();
3671 >        return new SearchKeysTask<K,V,U>
3672 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3673 >             searchFunction, new AtomicReference<U>()).invoke();
3674      }
3675  
3676      /**
3677       * Returns the result of accumulating all keys using the given
3678       * reducer to combine values, or null if none.
3679       *
3680 +     * @param parallelismThreshold the (estimated) number of elements
3681 +     * needed for this operation to be executed in parallel
3682       * @param reducer a commutative associative combining function
3683       * @return the result of accumulating all keys using the given
3684       * reducer to combine values, or null if none
3685 +     * @since 1.8
3686       */
3687 <    @SuppressWarnings("unchecked") public K reduceKeysSequentially
3688 <        (BiFun<? super K, ? super K, ? extends K> reducer) {
3687 >    public K reduceKeys(long parallelismThreshold,
3688 >                        BiFun<? super K, ? super K, ? extends K> reducer) {
3689          if (reducer == null) throw new NullPointerException();
3690 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3691 <        K r = null;
3692 <        while (it.advance() != null) {
3585 <            K u = (K)it.nextKey;
3586 <            r = (r == null) ? u : reducer.apply(r, u);
3587 <        }
3588 <        return r;
3690 >        return new ReduceKeysTask<K,V>
3691 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3692 >             null, reducer).invoke();
3693      }
3694  
3695      /**
# Line 3593 | Line 3697 | public class ConcurrentHashMapV8<K, V>
3697       * of all keys using the given reducer to combine values, or
3698       * null if none.
3699       *
3700 +     * @param parallelismThreshold the (estimated) number of elements
3701 +     * needed for this operation to be executed in parallel
3702       * @param transformer a function returning the transformation
3703       * for an element, or null if there is no transformation (in
3704       * which case it is not combined)
3705       * @param reducer a commutative associative combining function
3706       * @return the result of accumulating the given transformation
3707       * of all keys
3708 +     * @since 1.8
3709       */
3710 <    @SuppressWarnings("unchecked") public <U> U reduceKeysSequentially
3711 <        (Fun<? super K, ? extends U> transformer,
3710 >    public <U> U reduceKeys(long parallelismThreshold,
3711 >                            Fun<? super K, ? extends U> transformer,
3712           BiFun<? super U, ? super U, ? extends U> reducer) {
3713          if (transformer == null || reducer == null)
3714              throw new NullPointerException();
3715 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3716 <        U r = null, u;
3717 <        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;
3715 >        return new MapReduceKeysTask<K,V,U>
3716 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3717 >             null, transformer, reducer).invoke();
3718      }
3719  
3720      /**
# Line 3619 | Line 3722 | public class ConcurrentHashMapV8<K, V>
3722       * of all keys using the given reducer to combine values, and
3723       * the given basis as an identity value.
3724       *
3725 +     * @param parallelismThreshold the (estimated) number of elements
3726 +     * needed for this operation to be executed in parallel
3727       * @param transformer a function returning the transformation
3728       * for an element
3729       * @param basis the identity (initial default value) for the reduction
3730       * @param reducer a commutative associative combining function
3731 <     * @return  the result of accumulating the given transformation
3731 >     * @return the result of accumulating the given transformation
3732       * of all keys
3733 +     * @since 1.8
3734       */
3735 <    @SuppressWarnings("unchecked") public double reduceKeysToDoubleSequentially
3736 <        (ObjectToDouble<? super K> transformer,
3737 <         double basis,
3738 <         DoubleByDoubleToDouble reducer) {
3735 >    public double reduceKeysToDouble(long parallelismThreshold,
3736 >                                     ObjectToDouble<? super K> transformer,
3737 >                                     double basis,
3738 >                                     DoubleByDoubleToDouble reducer) {
3739          if (transformer == null || reducer == null)
3740              throw new NullPointerException();
3741 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3742 <        double r = basis;
3743 <        while (it.advance() != null)
3638 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3639 <        return r;
3741 >        return new MapReduceKeysToDoubleTask<K,V>
3742 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3743 >             null, transformer, basis, reducer).invoke();
3744      }
3745  
3746      /**
# Line 3644 | Line 3748 | public class ConcurrentHashMapV8<K, V>
3748       * of all keys using the given reducer to combine values, and
3749       * the given basis as an identity value.
3750       *
3751 +     * @param parallelismThreshold the (estimated) number of elements
3752 +     * needed for this operation to be executed in parallel
3753       * @param transformer a function returning the transformation
3754       * for an element
3755       * @param basis the identity (initial default value) for the reduction
3756       * @param reducer a commutative associative combining function
3757       * @return the result of accumulating the given transformation
3758       * of all keys
3759 +     * @since 1.8
3760       */
3761 <    @SuppressWarnings("unchecked") public long reduceKeysToLongSequentially
3762 <        (ObjectToLong<? super K> transformer,
3763 <         long basis,
3764 <         LongByLongToLong reducer) {
3761 >    public long reduceKeysToLong(long parallelismThreshold,
3762 >                                 ObjectToLong<? super K> transformer,
3763 >                                 long basis,
3764 >                                 LongByLongToLong reducer) {
3765          if (transformer == null || reducer == null)
3766              throw new NullPointerException();
3767 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3768 <        long r = basis;
3769 <        while (it.advance() != null)
3663 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3664 <        return r;
3767 >        return new MapReduceKeysToLongTask<K,V>
3768 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3769 >             null, transformer, basis, reducer).invoke();
3770      }
3771  
3772      /**
# Line 3669 | Line 3774 | public class ConcurrentHashMapV8<K, V>
3774       * of all keys using the given reducer to combine values, and
3775       * the given basis as an identity value.
3776       *
3777 +     * @param parallelismThreshold the (estimated) number of elements
3778 +     * needed for this operation to be executed in parallel
3779       * @param transformer a function returning the transformation
3780       * for an element
3781       * @param basis the identity (initial default value) for the reduction
3782       * @param reducer a commutative associative combining function
3783       * @return the result of accumulating the given transformation
3784       * of all keys
3785 +     * @since 1.8
3786       */
3787 <    @SuppressWarnings("unchecked") public int reduceKeysToIntSequentially
3788 <        (ObjectToInt<? super K> transformer,
3789 <         int basis,
3790 <         IntByIntToInt reducer) {
3787 >    public int reduceKeysToInt(long parallelismThreshold,
3788 >                               ObjectToInt<? super K> transformer,
3789 >                               int basis,
3790 >                               IntByIntToInt reducer) {
3791          if (transformer == null || reducer == null)
3792              throw new NullPointerException();
3793 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3794 <        int r = basis;
3795 <        while (it.advance() != null)
3688 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3689 <        return r;
3793 >        return new MapReduceKeysToIntTask<K,V>
3794 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3795 >             null, transformer, basis, reducer).invoke();
3796      }
3797  
3798      /**
3799       * Performs the given action for each value.
3800       *
3801 +     * @param parallelismThreshold the (estimated) number of elements
3802 +     * needed for this operation to be executed in parallel
3803       * @param action the action
3804 +     * @since 1.8
3805       */
3806 <    public void forEachValueSequentially(Action<V> action) {
3807 <        if (action == null) throw new NullPointerException();
3808 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3809 <        V v;
3810 <        while ((v = it.advance()) != null)
3811 <            action.apply(v);
3806 >    public void forEachValue(long parallelismThreshold,
3807 >                             Action<? super V> action) {
3808 >        if (action == null)
3809 >            throw new NullPointerException();
3810 >        new ForEachValueTask<K,V>
3811 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3812 >             action).invoke();
3813      }
3814  
3815      /**
3816       * Performs the given action for each non-null transformation
3817       * of each value.
3818       *
3819 +     * @param parallelismThreshold the (estimated) number of elements
3820 +     * needed for this operation to be executed in parallel
3821       * @param transformer a function returning the transformation
3822       * for an element, or null if there is no transformation (in
3823       * which case the action is not applied)
3824 +     * @param action the action
3825 +     * @since 1.8
3826       */
3827 <    public <U> void forEachValueSequentially
3828 <        (Fun<? super V, ? extends U> transformer,
3829 <         Action<U> action) {
3827 >    public <U> void forEachValue(long parallelismThreshold,
3828 >                                 Fun<? super V, ? extends U> transformer,
3829 >                                 Action<? super U> action) {
3830          if (transformer == null || action == null)
3831              throw new NullPointerException();
3832 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3833 <        V v; U u;
3834 <        while ((v = it.advance()) != null) {
3721 <            if ((u = transformer.apply(v)) != null)
3722 <                action.apply(u);
3723 <        }
3832 >        new ForEachTransformedValueTask<K,V,U>
3833 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3834 >             transformer, action).invoke();
3835      }
3836  
3837      /**
3838       * Returns a non-null result from applying the given search
3839 <     * function on each value, or null if none.
3839 >     * function on each value, or null if none.  Upon success,
3840 >     * further element processing is suppressed and the results of
3841 >     * any other parallel invocations of the search function are
3842 >     * ignored.
3843       *
3844 +     * @param parallelismThreshold the (estimated) number of elements
3845 +     * needed for this operation to be executed in parallel
3846       * @param searchFunction a function returning a non-null
3847       * result on success, else null
3848       * @return a non-null result from applying the given search
3849       * function on each value, or null if none
3850 +     * @since 1.8
3851       */
3852 <    public <U> U searchValuesSequentially
3853 <        (Fun<? super V, ? extends U> searchFunction) {
3852 >    public <U> U searchValues(long parallelismThreshold,
3853 >                              Fun<? super V, ? extends U> searchFunction) {
3854          if (searchFunction == null) throw new NullPointerException();
3855 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3856 <        V v; U u;
3857 <        while ((v = it.advance()) != null) {
3741 <            if ((u = searchFunction.apply(v)) != null)
3742 <                return u;
3743 <        }
3744 <        return null;
3855 >        return new SearchValuesTask<K,V,U>
3856 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3857 >             searchFunction, new AtomicReference<U>()).invoke();
3858      }
3859  
3860      /**
3861       * Returns the result of accumulating all values using the
3862       * given reducer to combine values, or null if none.
3863       *
3864 +     * @param parallelismThreshold the (estimated) number of elements
3865 +     * needed for this operation to be executed in parallel
3866       * @param reducer a commutative associative combining function
3867 <     * @return  the result of accumulating all values
3867 >     * @return the result of accumulating all values
3868 >     * @since 1.8
3869       */
3870 <    public V reduceValuesSequentially
3871 <        (BiFun<? super V, ? super V, ? extends V> reducer) {
3870 >    public V reduceValues(long parallelismThreshold,
3871 >                          BiFun<? super V, ? super V, ? extends V> reducer) {
3872          if (reducer == null) throw new NullPointerException();
3873 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3874 <        V r = null; V v;
3875 <        while ((v = it.advance()) != null)
3760 <            r = (r == null) ? v : reducer.apply(r, v);
3761 <        return r;
3873 >        return new ReduceValuesTask<K,V>
3874 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3875 >             null, reducer).invoke();
3876      }
3877  
3878      /**
# Line 3766 | Line 3880 | public class ConcurrentHashMapV8<K, V>
3880       * of all values using the given reducer to combine values, or
3881       * null if none.
3882       *
3883 +     * @param parallelismThreshold the (estimated) number of elements
3884 +     * needed for this operation to be executed in parallel
3885       * @param transformer a function returning the transformation
3886       * for an element, or null if there is no transformation (in
3887       * which case it is not combined)
3888       * @param reducer a commutative associative combining function
3889       * @return the result of accumulating the given transformation
3890       * of all values
3891 +     * @since 1.8
3892       */
3893 <    public <U> U reduceValuesSequentially
3894 <        (Fun<? super V, ? extends U> transformer,
3895 <         BiFun<? super U, ? super U, ? extends U> reducer) {
3893 >    public <U> U reduceValues(long parallelismThreshold,
3894 >                              Fun<? super V, ? extends U> transformer,
3895 >                              BiFun<? super U, ? super U, ? extends U> reducer) {
3896          if (transformer == null || reducer == null)
3897              throw new NullPointerException();
3898 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3899 <        U r = null, u; V v;
3900 <        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;
3898 >        return new MapReduceValuesTask<K,V,U>
3899 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3900 >             null, transformer, reducer).invoke();
3901      }
3902  
3903      /**
# Line 3792 | Line 3905 | public class ConcurrentHashMapV8<K, V>
3905       * of all values using the given reducer to combine values,
3906       * and the given basis as an identity value.
3907       *
3908 +     * @param parallelismThreshold the (estimated) number of elements
3909 +     * needed for this operation to be executed in parallel
3910       * @param transformer a function returning the transformation
3911       * for an element
3912       * @param basis the identity (initial default value) for the reduction
3913       * @param reducer a commutative associative combining function
3914       * @return the result of accumulating the given transformation
3915       * of all values
3916 +     * @since 1.8
3917       */
3918 <    public double reduceValuesToDoubleSequentially
3919 <        (ObjectToDouble<? super V> transformer,
3920 <         double basis,
3921 <         DoubleByDoubleToDouble reducer) {
3918 >    public double reduceValuesToDouble(long parallelismThreshold,
3919 >                                       ObjectToDouble<? super V> transformer,
3920 >                                       double basis,
3921 >                                       DoubleByDoubleToDouble reducer) {
3922          if (transformer == null || reducer == null)
3923              throw new NullPointerException();
3924 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3925 <        double r = basis; V v;
3926 <        while ((v = it.advance()) != null)
3811 <            r = reducer.apply(r, transformer.apply(v));
3812 <        return r;
3924 >        return new MapReduceValuesToDoubleTask<K,V>
3925 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3926 >             null, transformer, basis, reducer).invoke();
3927      }
3928  
3929      /**
# Line 3817 | Line 3931 | public class ConcurrentHashMapV8<K, V>
3931       * of all values using the given reducer to combine values,
3932       * and the given basis as an identity value.
3933       *
3934 +     * @param parallelismThreshold the (estimated) number of elements
3935 +     * needed for this operation to be executed in parallel
3936       * @param transformer a function returning the transformation
3937       * for an element
3938       * @param basis the identity (initial default value) for the reduction
3939       * @param reducer a commutative associative combining function
3940       * @return the result of accumulating the given transformation
3941       * of all values
3942 +     * @since 1.8
3943       */
3944 <    public long reduceValuesToLongSequentially
3945 <        (ObjectToLong<? super V> transformer,
3946 <         long basis,
3947 <         LongByLongToLong reducer) {
3944 >    public long reduceValuesToLong(long parallelismThreshold,
3945 >                                   ObjectToLong<? super V> transformer,
3946 >                                   long basis,
3947 >                                   LongByLongToLong reducer) {
3948          if (transformer == null || reducer == null)
3949              throw new NullPointerException();
3950 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3951 <        long r = basis; V v;
3952 <        while ((v = it.advance()) != null)
3836 <            r = reducer.apply(r, transformer.apply(v));
3837 <        return r;
3950 >        return new MapReduceValuesToLongTask<K,V>
3951 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3952 >             null, transformer, basis, reducer).invoke();
3953      }
3954  
3955      /**
# Line 3842 | Line 3957 | public class ConcurrentHashMapV8<K, V>
3957       * of all values using the given reducer to combine values,
3958       * and the given basis as an identity value.
3959       *
3960 +     * @param parallelismThreshold the (estimated) number of elements
3961 +     * needed for this operation to be executed in parallel
3962       * @param transformer a function returning the transformation
3963       * for an element
3964       * @param basis the identity (initial default value) for the reduction
3965       * @param reducer a commutative associative combining function
3966       * @return the result of accumulating the given transformation
3967       * of all values
3968 +     * @since 1.8
3969       */
3970 <    public int reduceValuesToIntSequentially
3971 <        (ObjectToInt<? super V> transformer,
3972 <         int basis,
3973 <         IntByIntToInt reducer) {
3970 >    public int reduceValuesToInt(long parallelismThreshold,
3971 >                                 ObjectToInt<? super V> transformer,
3972 >                                 int basis,
3973 >                                 IntByIntToInt reducer) {
3974          if (transformer == null || reducer == null)
3975              throw new NullPointerException();
3976 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3977 <        int r = basis; V v;
3978 <        while ((v = it.advance()) != null)
3861 <            r = reducer.apply(r, transformer.apply(v));
3862 <        return r;
3976 >        return new MapReduceValuesToIntTask<K,V>
3977 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3978 >             null, transformer, basis, reducer).invoke();
3979      }
3980  
3981      /**
3982       * Performs the given action for each entry.
3983       *
3984 +     * @param parallelismThreshold the (estimated) number of elements
3985 +     * needed for this operation to be executed in parallel
3986       * @param action the action
3987 +     * @since 1.8
3988       */
3989 <    @SuppressWarnings("unchecked") public void forEachEntrySequentially
3990 <        (Action<Map.Entry<K,V>> action) {
3989 >    public void forEachEntry(long parallelismThreshold,
3990 >                             Action<? super Map.Entry<K,V>> action) {
3991          if (action == null) throw new NullPointerException();
3992 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3993 <        V v;
3875 <        while ((v = it.advance()) != null)
3876 <            action.apply(entryFor((K)it.nextKey, v));
3992 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
3993 >                                  action).invoke();
3994      }
3995  
3996      /**
3997       * Performs the given action for each non-null transformation
3998       * of each entry.
3999       *
4000 +     * @param parallelismThreshold the (estimated) number of elements
4001 +     * needed for this operation to be executed in parallel
4002       * @param transformer a function returning the transformation
4003       * for an element, or null if there is no transformation (in
4004       * which case the action is not applied)
4005       * @param action the action
4006 +     * @since 1.8
4007       */
4008 <    @SuppressWarnings("unchecked") public <U> void forEachEntrySequentially
4009 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4010 <         Action<U> action) {
4008 >    public <U> void forEachEntry(long parallelismThreshold,
4009 >                                 Fun<Map.Entry<K,V>, ? extends U> transformer,
4010 >                                 Action<? super U> action) {
4011          if (transformer == null || action == null)
4012              throw new NullPointerException();
4013 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4014 <        V v; U u;
4015 <        while ((v = it.advance()) != null) {
3896 <            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3897 <                action.apply(u);
3898 <        }
4013 >        new ForEachTransformedEntryTask<K,V,U>
4014 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4015 >             transformer, action).invoke();
4016      }
4017  
4018      /**
4019       * Returns a non-null result from applying the given search
4020 <     * function on each entry, or null if none.
4020 >     * function on each entry, or null if none.  Upon success,
4021 >     * further element processing is suppressed and the results of
4022 >     * any other parallel invocations of the search function are
4023 >     * ignored.
4024       *
4025 +     * @param parallelismThreshold the (estimated) number of elements
4026 +     * needed for this operation to be executed in parallel
4027       * @param searchFunction a function returning a non-null
4028       * result on success, else null
4029       * @return a non-null result from applying the given search
4030       * function on each entry, or null if none
4031 +     * @since 1.8
4032       */
4033 <    @SuppressWarnings("unchecked") public <U> U searchEntriesSequentially
4034 <        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4033 >    public <U> U searchEntries(long parallelismThreshold,
4034 >                               Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4035          if (searchFunction == null) throw new NullPointerException();
4036 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4037 <        V v; U u;
4038 <        while ((v = it.advance()) != null) {
3916 <            if ((u = searchFunction.apply(entryFor((K)it.nextKey, v))) != null)
3917 <                return u;
3918 <        }
3919 <        return null;
4036 >        return new SearchEntriesTask<K,V,U>
4037 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4038 >             searchFunction, new AtomicReference<U>()).invoke();
4039      }
4040  
4041      /**
4042       * Returns the result of accumulating all entries using the
4043       * given reducer to combine values, or null if none.
4044       *
4045 +     * @param parallelismThreshold the (estimated) number of elements
4046 +     * needed for this operation to be executed in parallel
4047       * @param reducer a commutative associative combining function
4048       * @return the result of accumulating all entries
4049 +     * @since 1.8
4050       */
4051 <    @SuppressWarnings("unchecked") public Map.Entry<K,V> reduceEntriesSequentially
4052 <        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4051 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4052 >                                        BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4053          if (reducer == null) throw new NullPointerException();
4054 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4055 <        Map.Entry<K,V> r = null; V v;
4056 <        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;
4054 >        return new ReduceEntriesTask<K,V>
4055 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4056 >             null, reducer).invoke();
4057      }
4058  
4059      /**
# Line 3943 | Line 4061 | public class ConcurrentHashMapV8<K, V>
4061       * of all entries using the given reducer to combine values,
4062       * or null if none.
4063       *
4064 +     * @param parallelismThreshold the (estimated) number of elements
4065 +     * needed for this operation to be executed in parallel
4066       * @param transformer a function returning the transformation
4067       * for an element, or null if there is no transformation (in
4068       * which case it is not combined)
4069       * @param reducer a commutative associative combining function
4070       * @return the result of accumulating the given transformation
4071       * of all entries
4072 +     * @since 1.8
4073       */
4074 <    @SuppressWarnings("unchecked") public <U> U reduceEntriesSequentially
4075 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4076 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4074 >    public <U> U reduceEntries(long parallelismThreshold,
4075 >                               Fun<Map.Entry<K,V>, ? extends U> transformer,
4076 >                               BiFun<? super U, ? super U, ? extends U> reducer) {
4077          if (transformer == null || reducer == null)
4078              throw new NullPointerException();
4079 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4080 <        U r = null, u; V v;
4081 <        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;
4079 >        return new MapReduceEntriesTask<K,V,U>
4080 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4081 >             null, transformer, reducer).invoke();
4082      }
4083  
4084      /**
# Line 3969 | Line 4086 | public class ConcurrentHashMapV8<K, V>
4086       * of all entries using the given reducer to combine values,
4087       * and the given basis as an identity value.
4088       *
4089 +     * @param parallelismThreshold the (estimated) number of elements
4090 +     * needed for this operation to be executed in parallel
4091       * @param transformer a function returning the transformation
4092       * for an element
4093       * @param basis the identity (initial default value) for the reduction
4094       * @param reducer a commutative associative combining function
4095       * @return the result of accumulating the given transformation
4096       * of all entries
4097 +     * @since 1.8
4098       */
4099 <    @SuppressWarnings("unchecked") public double reduceEntriesToDoubleSequentially
4100 <        (ObjectToDouble<Map.Entry<K,V>> transformer,
4101 <         double basis,
4102 <         DoubleByDoubleToDouble reducer) {
4099 >    public double reduceEntriesToDouble(long parallelismThreshold,
4100 >                                        ObjectToDouble<Map.Entry<K,V>> transformer,
4101 >                                        double basis,
4102 >                                        DoubleByDoubleToDouble reducer) {
4103          if (transformer == null || reducer == null)
4104              throw new NullPointerException();
4105 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4106 <        double r = basis; V v;
4107 <        while ((v = it.advance()) != null)
3988 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
3989 <        return r;
4105 >        return new MapReduceEntriesToDoubleTask<K,V>
4106 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4107 >             null, transformer, basis, reducer).invoke();
4108      }
4109  
4110      /**
# Line 3994 | Line 4112 | public class ConcurrentHashMapV8<K, V>
4112       * of all entries using the given reducer to combine values,
4113       * and the given basis as an identity value.
4114       *
4115 +     * @param parallelismThreshold the (estimated) number of elements
4116 +     * needed for this operation to be executed in parallel
4117       * @param transformer a function returning the transformation
4118       * for an element
4119       * @param basis the identity (initial default value) for the reduction
4120       * @param reducer a commutative associative combining function
4121 <     * @return  the result of accumulating the given transformation
4121 >     * @return the result of accumulating the given transformation
4122       * of all entries
4123 +     * @since 1.8
4124       */
4125 <    @SuppressWarnings("unchecked") public long reduceEntriesToLongSequentially
4126 <        (ObjectToLong<Map.Entry<K,V>> transformer,
4127 <         long basis,
4128 <         LongByLongToLong reducer) {
4125 >    public long reduceEntriesToLong(long parallelismThreshold,
4126 >                                    ObjectToLong<Map.Entry<K,V>> transformer,
4127 >                                    long basis,
4128 >                                    LongByLongToLong reducer) {
4129          if (transformer == null || reducer == null)
4130              throw new NullPointerException();
4131 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4132 <        long r = basis; V v;
4133 <        while ((v = it.advance()) != null)
4013 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4014 <        return r;
4131 >        return new MapReduceEntriesToLongTask<K,V>
4132 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4133 >             null, transformer, basis, reducer).invoke();
4134      }
4135  
4136      /**
# Line 4019 | Line 4138 | public class ConcurrentHashMapV8<K, V>
4138       * of all entries using the given reducer to combine values,
4139       * and the given basis as an identity value.
4140       *
4141 +     * @param parallelismThreshold the (estimated) number of elements
4142 +     * needed for this operation to be executed in parallel
4143       * @param transformer a function returning the transformation
4144       * for an element
4145       * @param basis the identity (initial default value) for the reduction
4146       * @param reducer a commutative associative combining function
4147       * @return the result of accumulating the given transformation
4148       * of all entries
4149 +     * @since 1.8
4150       */
4151 <    @SuppressWarnings("unchecked") public int reduceEntriesToIntSequentially
4152 <        (ObjectToInt<Map.Entry<K,V>> transformer,
4153 <         int basis,
4154 <         IntByIntToInt reducer) {
4151 >    public int reduceEntriesToInt(long parallelismThreshold,
4152 >                                  ObjectToInt<Map.Entry<K,V>> transformer,
4153 >                                  int basis,
4154 >                                  IntByIntToInt reducer) {
4155          if (transformer == null || reducer == null)
4156              throw new NullPointerException();
4157 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4158 <        int r = basis; V v;
4159 <        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();
4157 >        return new MapReduceEntriesToIntTask<K,V>
4158 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4159 >             null, transformer, basis, reducer).invoke();
4160      }
4161  
4162  
# Line 4578 | Line 4165 | public class ConcurrentHashMapV8<K, V>
4165      /**
4166       * Base class for views.
4167       */
4168 <    abstract static class CHMView<K, V> {
4169 <        final ConcurrentHashMapV8<K, V> map;
4170 <        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
4168 >    abstract static class CollectionView<K,V,E>
4169 >        implements Collection<E>, java.io.Serializable {
4170 >        private static final long serialVersionUID = 7249069246763182397L;
4171 >        final ConcurrentHashMapV8<K,V> map;
4172 >        CollectionView(ConcurrentHashMapV8<K,V> map)  { this.map = map; }
4173  
4174          /**
4175           * Returns the map backing this view.
# Line 4589 | Line 4178 | public class ConcurrentHashMapV8<K, V>
4178           */
4179          public ConcurrentHashMapV8<K,V> getMap() { return map; }
4180  
4181 <        public final int size()                 { return map.size(); }
4182 <        public final boolean isEmpty()          { return map.isEmpty(); }
4183 <        public final void clear()               { map.clear(); }
4181 >        /**
4182 >         * Removes all of the elements from this view, by removing all
4183 >         * the mappings from the map backing this view.
4184 >         */
4185 >        public final void clear()      { map.clear(); }
4186 >        public final int size()        { return map.size(); }
4187 >        public final boolean isEmpty() { return map.isEmpty(); }
4188  
4189          // implementations below rely on concrete classes supplying these
4190 <        public abstract Iterator<?> iterator();
4190 >        // abstract methods
4191 >        /**
4192 >         * Returns a "weakly consistent" iterator that will never
4193 >         * throw {@link ConcurrentModificationException}, and
4194 >         * guarantees to traverse elements as they existed upon
4195 >         * construction of the iterator, and may (but is not
4196 >         * guaranteed to) reflect any modifications subsequent to
4197 >         * construction.
4198 >         */
4199 >        public abstract Iterator<E> iterator();
4200          public abstract boolean contains(Object o);
4201          public abstract boolean remove(Object o);
4202  
# Line 4602 | Line 4204 | public class ConcurrentHashMapV8<K, V>
4204  
4205          public final Object[] toArray() {
4206              long sz = map.mappingCount();
4207 <            if (sz > (long)(MAX_ARRAY_SIZE))
4207 >            if (sz > MAX_ARRAY_SIZE)
4208                  throw new OutOfMemoryError(oomeMsg);
4209              int n = (int)sz;
4210              Object[] r = new Object[n];
4211              int i = 0;
4212 <            Iterator<?> it = iterator();
4611 <            while (it.hasNext()) {
4212 >            for (E e : this) {
4213                  if (i == n) {
4214                      if (n >= MAX_ARRAY_SIZE)
4215                          throw new OutOfMemoryError(oomeMsg);
# Line 4618 | Line 4219 | public class ConcurrentHashMapV8<K, V>
4219                          n += (n >>> 1) + 1;
4220                      r = Arrays.copyOf(r, n);
4221                  }
4222 <                r[i++] = it.next();
4222 >                r[i++] = e;
4223              }
4224              return (i == n) ? r : Arrays.copyOf(r, i);
4225          }
4226  
4227 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4227 >        @SuppressWarnings("unchecked")
4228 >        public final <T> T[] toArray(T[] a) {
4229              long sz = map.mappingCount();
4230 <            if (sz > (long)(MAX_ARRAY_SIZE))
4230 >            if (sz > MAX_ARRAY_SIZE)
4231                  throw new OutOfMemoryError(oomeMsg);
4232              int m = (int)sz;
4233              T[] r = (a.length >= m) ? a :
# Line 4633 | Line 4235 | public class ConcurrentHashMapV8<K, V>
4235                  .newInstance(a.getClass().getComponentType(), m);
4236              int n = r.length;
4237              int i = 0;
4238 <            Iterator<?> it = iterator();
4637 <            while (it.hasNext()) {
4238 >            for (E e : this) {
4239                  if (i == n) {
4240                      if (n >= MAX_ARRAY_SIZE)
4241                          throw new OutOfMemoryError(oomeMsg);
# Line 4644 | Line 4245 | public class ConcurrentHashMapV8<K, V>
4245                          n += (n >>> 1) + 1;
4246                      r = Arrays.copyOf(r, n);
4247                  }
4248 <                r[i++] = (T)it.next();
4248 >                r[i++] = (T)e;
4249              }
4250              if (a == r && i < n) {
4251                  r[i] = null; // null-terminate
# Line 4653 | Line 4254 | public class ConcurrentHashMapV8<K, V>
4254              return (i == n) ? r : Arrays.copyOf(r, i);
4255          }
4256  
4257 <        public final int hashCode() {
4258 <            int h = 0;
4259 <            for (Iterator<?> it = iterator(); it.hasNext();)
4260 <                h += it.next().hashCode();
4261 <            return h;
4262 <        }
4263 <
4257 >        /**
4258 >         * Returns a string representation of this collection.
4259 >         * The string representation consists of the string representations
4260 >         * of the collection's elements in the order they are returned by
4261 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4262 >         * Adjacent elements are separated by the characters {@code ", "}
4263 >         * (comma and space).  Elements are converted to strings as by
4264 >         * {@link String#valueOf(Object)}.
4265 >         *
4266 >         * @return a string representation of this collection
4267 >         */
4268          public final String toString() {
4269              StringBuilder sb = new StringBuilder();
4270              sb.append('[');
4271 <            Iterator<?> it = iterator();
4271 >            Iterator<E> it = iterator();
4272              if (it.hasNext()) {
4273                  for (;;) {
4274                      Object e = it.next();
# Line 4678 | Line 4283 | public class ConcurrentHashMapV8<K, V>
4283  
4284          public final boolean containsAll(Collection<?> c) {
4285              if (c != this) {
4286 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4682 <                    Object e = it.next();
4286 >                for (Object e : c) {
4287                      if (e == null || !contains(e))
4288                          return false;
4289                  }
# Line 4689 | Line 4293 | public class ConcurrentHashMapV8<K, V>
4293  
4294          public final boolean removeAll(Collection<?> c) {
4295              boolean modified = false;
4296 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4296 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4297                  if (c.contains(it.next())) {
4298                      it.remove();
4299                      modified = true;
# Line 4700 | Line 4304 | public class ConcurrentHashMapV8<K, V>
4304  
4305          public final boolean retainAll(Collection<?> c) {
4306              boolean modified = false;
4307 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4307 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4308                  if (!c.contains(it.next())) {
4309                      it.remove();
4310                      modified = true;
# Line 4714 | Line 4318 | public class ConcurrentHashMapV8<K, V>
4318      /**
4319       * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4320       * which additions may optionally be enabled by mapping to a
4321 <     * common value.  This class cannot be directly instantiated. See
4322 <     * {@link #keySet()}, {@link #keySet(Object)}, {@link #newKeySet()},
4323 <     * {@link #newKeySet(int)}.
4321 >     * common value.  This class cannot be directly instantiated.
4322 >     * See {@link #keySet() keySet()},
4323 >     * {@link #keySet(Object) keySet(V)},
4324 >     * {@link #newKeySet() newKeySet()},
4325 >     * {@link #newKeySet(int) newKeySet(int)}.
4326 >     *
4327 >     * @since 1.8
4328       */
4329 <    public static class KeySetView<K,V> extends CHMView<K,V>
4329 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4330          implements Set<K>, java.io.Serializable {
4331          private static final long serialVersionUID = 7249069246763182397L;
4332          private final V value;
4333 <        KeySetView(ConcurrentHashMapV8<K, V> map, V value) {  // non-public
4333 >        KeySetView(ConcurrentHashMapV8<K,V> map, V value) {  // non-public
4334              super(map);
4335              this.value = value;
4336          }
# Line 4736 | Line 4344 | public class ConcurrentHashMapV8<K, V>
4344           */
4345          public V getMappedValue() { return value; }
4346  
4347 <        // implement Set API
4348 <
4347 >        /**
4348 >         * {@inheritDoc}
4349 >         * @throws NullPointerException if the specified key is null
4350 >         */
4351          public boolean contains(Object o) { return map.containsKey(o); }
4742        public boolean remove(Object o)   { return map.remove(o) != null; }
4352  
4353          /**
4354 <         * Returns a "weakly consistent" iterator that will never
4355 <         * throw {@link ConcurrentModificationException}, and
4356 <         * 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.
4354 >         * Removes the key from this map view, by removing the key (and its
4355 >         * corresponding value) from the backing map.  This method does
4356 >         * nothing if the key is not in the map.
4357           *
4358 <         * @return an iterator over the keys of this map
4358 >         * @param  o the key to be removed from the backing map
4359 >         * @return {@code true} if the backing map contained the specified key
4360 >         * @throws NullPointerException if the specified key is null
4361 >         */
4362 >        public boolean remove(Object o) { return map.remove(o) != null; }
4363 >
4364 >        /**
4365 >         * @return an iterator over the keys of the backing map
4366 >         */
4367 >        public Iterator<K> iterator() {
4368 >            Node<K,V>[] t;
4369 >            ConcurrentHashMapV8<K,V> m = map;
4370 >            int f = (t = m.table) == null ? 0 : t.length;
4371 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4372 >        }
4373 >
4374 >        /**
4375 >         * Adds the specified key to this set view by mapping the key to
4376 >         * the default mapped value in the backing map, if defined.
4377 >         *
4378 >         * @param e key to be added
4379 >         * @return {@code true} if this set changed as a result of the call
4380 >         * @throws NullPointerException if the specified key is null
4381 >         * @throws UnsupportedOperationException if no default mapped value
4382 >         * for additions was provided
4383           */
4754        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4384          public boolean add(K e) {
4385              V v;
4386              if ((v = value) == null)
4387                  throw new UnsupportedOperationException();
4388 <            if (e == null)
4760 <                throw new NullPointerException();
4761 <            return map.internalPut(e, v, true) == null;
4388 >            return map.putVal(e, v, true) == null;
4389          }
4390 +
4391 +        /**
4392 +         * Adds all of the elements in the specified collection to this set,
4393 +         * as if by calling {@link #add} on each one.
4394 +         *
4395 +         * @param c the elements to be inserted into this set
4396 +         * @return {@code true} if this set changed as a result of the call
4397 +         * @throws NullPointerException if the collection or any of its
4398 +         * elements are {@code null}
4399 +         * @throws UnsupportedOperationException if no default mapped value
4400 +         * for additions was provided
4401 +         */
4402          public boolean addAll(Collection<? extends K> c) {
4403              boolean added = false;
4404              V v;
4405              if ((v = value) == null)
4406                  throw new UnsupportedOperationException();
4407              for (K e : c) {
4408 <                if (e == null)
4770 <                    throw new NullPointerException();
4771 <                if (map.internalPut(e, v, true) == null)
4408 >                if (map.putVal(e, v, true) == null)
4409                      added = true;
4410              }
4411              return added;
4412          }
4413 +
4414 +        public int hashCode() {
4415 +            int h = 0;
4416 +            for (K e : this)
4417 +                h += e.hashCode();
4418 +            return h;
4419 +        }
4420 +
4421          public boolean equals(Object o) {
4422              Set<?> c;
4423              return ((o instanceof Set) &&
4424                      ((c = (Set<?>)o) == this ||
4425                       (containsAll(c) && c.containsAll(this))));
4426          }
4427 +
4428 +        public ConcurrentHashMapSpliterator<K> spliterator() {
4429 +            Node<K,V>[] t;
4430 +            ConcurrentHashMapV8<K,V> m = map;
4431 +            long n = m.sumCount();
4432 +            int f = (t = m.table) == null ? 0 : t.length;
4433 +            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4434 +        }
4435 +
4436 +        public void forEach(Action<? super K> action) {
4437 +            if (action == null) throw new NullPointerException();
4438 +            Node<K,V>[] t;
4439 +            if ((t = map.table) != null) {
4440 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4441 +                for (Node<K,V> p; (p = it.advance()) != null; )
4442 +                    action.apply(p.key);
4443 +            }
4444 +        }
4445      }
4446  
4447      /**
4448       * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4449       * values, in which additions are disabled. This class cannot be
4450       * directly instantiated. See {@link #values()}.
4788     *
4789     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4790     * that will never throw {@link ConcurrentModificationException},
4791     * and guarantees to traverse elements as they existed upon
4792     * construction of the iterator, and may (but is not guaranteed to)
4793     * reflect any modifications subsequent to construction.
4451       */
4452 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4453 <        implements Collection<V> {
4454 <        ValuesView(ConcurrentHashMapV8<K, V> map)   { super(map); }
4455 <        public final boolean contains(Object o) { return map.containsValue(o); }
4452 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4453 >        implements Collection<V>, java.io.Serializable {
4454 >        private static final long serialVersionUID = 2249069246763182397L;
4455 >        ValuesView(ConcurrentHashMapV8<K,V> map) { super(map); }
4456 >        public final boolean contains(Object o) {
4457 >            return map.containsValue(o);
4458 >        }
4459 >
4460          public final boolean remove(Object o) {
4461              if (o != null) {
4462 <                Iterator<V> it = new ValueIterator<K,V>(map);
4802 <                while (it.hasNext()) {
4462 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4463                      if (o.equals(it.next())) {
4464                          it.remove();
4465                          return true;
# Line 4809 | Line 4469 | public class ConcurrentHashMapV8<K, V>
4469              return false;
4470          }
4471  
4812        /**
4813         * Returns a "weakly consistent" iterator that will never
4814         * throw {@link ConcurrentModificationException}, and
4815         * guarantees to traverse elements as they existed upon
4816         * construction of the iterator, and may (but is not
4817         * guaranteed to) reflect any modifications subsequent to
4818         * construction.
4819         *
4820         * @return an iterator over the values of this map
4821         */
4472          public final Iterator<V> iterator() {
4473 <            return new ValueIterator<K,V>(map);
4473 >            ConcurrentHashMapV8<K,V> m = map;
4474 >            Node<K,V>[] t;
4475 >            int f = (t = m.table) == null ? 0 : t.length;
4476 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4477          }
4478 +
4479          public final boolean add(V e) {
4480              throw new UnsupportedOperationException();
4481          }
# Line 4829 | Line 4483 | public class ConcurrentHashMapV8<K, V>
4483              throw new UnsupportedOperationException();
4484          }
4485  
4486 +        public ConcurrentHashMapSpliterator<V> spliterator() {
4487 +            Node<K,V>[] t;
4488 +            ConcurrentHashMapV8<K,V> m = map;
4489 +            long n = m.sumCount();
4490 +            int f = (t = m.table) == null ? 0 : t.length;
4491 +            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4492 +        }
4493 +
4494 +        public void forEach(Action<? super V> action) {
4495 +            if (action == null) throw new NullPointerException();
4496 +            Node<K,V>[] t;
4497 +            if ((t = map.table) != null) {
4498 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4499 +                for (Node<K,V> p; (p = it.advance()) != null; )
4500 +                    action.apply(p.val);
4501 +            }
4502 +        }
4503      }
4504  
4505      /**
# Line 4836 | Line 4507 | public class ConcurrentHashMapV8<K, V>
4507       * entries.  This class cannot be directly instantiated. See
4508       * {@link #entrySet()}.
4509       */
4510 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4511 <        implements Set<Map.Entry<K,V>> {
4512 <        EntrySetView(ConcurrentHashMapV8<K, V> map) { super(map); }
4513 <        public final boolean contains(Object o) {
4510 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4511 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4512 >        private static final long serialVersionUID = 2249069246763182397L;
4513 >        EntrySetView(ConcurrentHashMapV8<K,V> map) { super(map); }
4514 >
4515 >        public boolean contains(Object o) {
4516              Object k, v, r; Map.Entry<?,?> e;
4517              return ((o instanceof Map.Entry) &&
4518                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4847 | Line 4520 | public class ConcurrentHashMapV8<K, V>
4520                      (v = e.getValue()) != null &&
4521                      (v == r || v.equals(r)));
4522          }
4523 <        public final boolean remove(Object o) {
4523 >
4524 >        public boolean remove(Object o) {
4525              Object k, v; Map.Entry<?,?> e;
4526              return ((o instanceof Map.Entry) &&
4527                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4856 | Line 4530 | public class ConcurrentHashMapV8<K, V>
4530          }
4531  
4532          /**
4533 <         * Returns a "weakly consistent" iterator that will never
4860 <         * throw {@link ConcurrentModificationException}, and
4861 <         * guarantees to traverse elements as they existed upon
4862 <         * construction of the iterator, and may (but is not
4863 <         * guaranteed to) reflect any modifications subsequent to
4864 <         * construction.
4865 <         *
4866 <         * @return an iterator over the entries of this map
4533 >         * @return an iterator over the entries of the backing map
4534           */
4535 <        public final Iterator<Map.Entry<K,V>> iterator() {
4536 <            return new EntryIterator<K,V>(map);
4535 >        public Iterator<Map.Entry<K,V>> iterator() {
4536 >            ConcurrentHashMapV8<K,V> m = map;
4537 >            Node<K,V>[] t;
4538 >            int f = (t = m.table) == null ? 0 : t.length;
4539 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4540          }
4541  
4542 <        public final boolean add(Entry<K,V> e) {
4543 <            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4542 >        public boolean add(Entry<K,V> e) {
4543 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4544          }
4545 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4545 >
4546 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4547              boolean added = false;
4548              for (Entry<K,V> e : c) {
4549                  if (add(e))
# Line 4880 | Line 4551 | public class ConcurrentHashMapV8<K, V>
4551              }
4552              return added;
4553          }
4554 <        public boolean equals(Object o) {
4554 >
4555 >        public final int hashCode() {
4556 >            int h = 0;
4557 >            Node<K,V>[] t;
4558 >            if ((t = map.table) != null) {
4559 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4560 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4561 >                    h += p.hashCode();
4562 >                }
4563 >            }
4564 >            return h;
4565 >        }
4566 >
4567 >        public final boolean equals(Object o) {
4568              Set<?> c;
4569              return ((o instanceof Set) &&
4570                      ((c = (Set<?>)o) == this ||
4571                       (containsAll(c) && c.containsAll(this))));
4572          }
4889    }
4890
4891    // ---------------------------------------------------------------------
4892
4893    /**
4894     * Predefined tasks for performing bulk parallel operations on
4895     * ConcurrentHashMapV8s. These tasks follow the forms and rules used
4896     * for bulk operations. Each method has the same name, but returns
4897     * a task rather than invoking it. These methods may be useful in
4898     * custom applications such as submitting a task without waiting
4899     * for completion, using a custom pool, or combining with other
4900     * tasks.
4901     */
4902    public static class ForkJoinTasks {
4903        private ForkJoinTasks() {}
4573  
4574 <        /**
4575 <         * Returns a task that when invoked, performs the given
4576 <         * action for each (key, value)
4577 <         *
4578 <         * @param map the map
4579 <         * @param action the action
4911 <         * @return the task
4912 <         */
4913 <        public static <K,V> ForkJoinTask<Void> forEach
4914 <            (ConcurrentHashMapV8<K,V> map,
4915 <             BiAction<K,V> action) {
4916 <            if (action == null) throw new NullPointerException();
4917 <            return new ForEachMappingTask<K,V>(map, null, -1, action);
4918 <        }
4919 <
4920 <        /**
4921 <         * Returns a task that when invoked, performs the given
4922 <         * action for each non-null transformation of each (key, value)
4923 <         *
4924 <         * @param map the map
4925 <         * @param transformer a function returning the transformation
4926 <         * for an element, or null if there is no transformation (in
4927 <         * which case the action is not applied)
4928 <         * @param action the action
4929 <         * @return the task
4930 <         */
4931 <        public static <K,V,U> ForkJoinTask<Void> forEach
4932 <            (ConcurrentHashMapV8<K,V> map,
4933 <             BiFun<? super K, ? super V, ? extends U> transformer,
4934 <             Action<U> action) {
4935 <            if (transformer == null || action == null)
4936 <                throw new NullPointerException();
4937 <            return new ForEachTransformedMappingTask<K,V,U>
4938 <                (map, null, -1, transformer, action);
4574 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> spliterator() {
4575 >            Node<K,V>[] t;
4576 >            ConcurrentHashMapV8<K,V> m = map;
4577 >            long n = m.sumCount();
4578 >            int f = (t = m.table) == null ? 0 : t.length;
4579 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4580          }
4581  
4582 <        /**
4942 <         * Returns a task that when invoked, returns a non-null result
4943 <         * from applying the given search function on each (key,
4944 <         * value), or null if none. Upon success, further element
4945 <         * processing is suppressed and the results of any other
4946 <         * parallel invocations of the search function are ignored.
4947 <         *
4948 <         * @param map the map
4949 <         * @param searchFunction a function returning a non-null
4950 <         * result on success, else null
4951 <         * @return the task
4952 <         */
4953 <        public static <K,V,U> ForkJoinTask<U> search
4954 <            (ConcurrentHashMapV8<K,V> map,
4955 <             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4956 <            if (searchFunction == null) throw new NullPointerException();
4957 <            return new SearchMappingsTask<K,V,U>
4958 <                (map, null, -1, searchFunction,
4959 <                 new AtomicReference<U>());
4960 <        }
4961 <
4962 <        /**
4963 <         * Returns a task that when invoked, returns the result of
4964 <         * accumulating the given transformation of all (key, value) pairs
4965 <         * using the given reducer to combine values, or null if none.
4966 <         *
4967 <         * @param map the map
4968 <         * @param transformer a function returning the transformation
4969 <         * for an element, or null if there is no transformation (in
4970 <         * which case it is not combined)
4971 <         * @param reducer a commutative associative combining function
4972 <         * @return the task
4973 <         */
4974 <        public static <K,V,U> ForkJoinTask<U> reduce
4975 <            (ConcurrentHashMapV8<K,V> map,
4976 <             BiFun<? super K, ? super V, ? extends U> transformer,
4977 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4978 <            if (transformer == null || reducer == null)
4979 <                throw new NullPointerException();
4980 <            return new MapReduceMappingsTask<K,V,U>
4981 <                (map, null, -1, null, transformer, reducer);
4982 <        }
4983 <
4984 <        /**
4985 <         * Returns a task that when invoked, returns the result of
4986 <         * accumulating the given transformation of all (key, value) pairs
4987 <         * using the given reducer to combine values, and the given
4988 <         * basis as an identity value.
4989 <         *
4990 <         * @param map the map
4991 <         * @param transformer a function returning the transformation
4992 <         * for an element
4993 <         * @param basis the identity (initial default value) for the reduction
4994 <         * @param reducer a commutative associative combining function
4995 <         * @return the task
4996 <         */
4997 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4998 <            (ConcurrentHashMapV8<K,V> map,
4999 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
5000 <             double basis,
5001 <             DoubleByDoubleToDouble reducer) {
5002 <            if (transformer == null || reducer == null)
5003 <                throw new NullPointerException();
5004 <            return new MapReduceMappingsToDoubleTask<K,V>
5005 <                (map, null, -1, null, transformer, basis, reducer);
5006 <        }
5007 <
5008 <        /**
5009 <         * Returns a task that when invoked, returns the result of
5010 <         * accumulating the given transformation of all (key, value) pairs
5011 <         * using the given reducer to combine values, and the given
5012 <         * basis as an identity value.
5013 <         *
5014 <         * @param map the map
5015 <         * @param transformer a function returning the transformation
5016 <         * for an element
5017 <         * @param basis the identity (initial default value) for the reduction
5018 <         * @param reducer a commutative associative combining function
5019 <         * @return the task
5020 <         */
5021 <        public static <K,V> ForkJoinTask<Long> reduceToLong
5022 <            (ConcurrentHashMapV8<K,V> map,
5023 <             ObjectByObjectToLong<? super K, ? super V> transformer,
5024 <             long basis,
5025 <             LongByLongToLong reducer) {
5026 <            if (transformer == null || reducer == null)
5027 <                throw new NullPointerException();
5028 <            return new MapReduceMappingsToLongTask<K,V>
5029 <                (map, null, -1, null, transformer, basis, reducer);
5030 <        }
5031 <
5032 <        /**
5033 <         * Returns a task that when invoked, returns the result of
5034 <         * accumulating the given transformation of all (key, value) pairs
5035 <         * using the given reducer to combine values, and the given
5036 <         * basis as an identity value.
5037 <         *
5038 <         * @param transformer a function returning the transformation
5039 <         * for an element
5040 <         * @param basis the identity (initial default value) for the reduction
5041 <         * @param reducer a commutative associative combining function
5042 <         * @return the task
5043 <         */
5044 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
5045 <            (ConcurrentHashMapV8<K,V> map,
5046 <             ObjectByObjectToInt<? super K, ? super V> transformer,
5047 <             int basis,
5048 <             IntByIntToInt reducer) {
5049 <            if (transformer == null || reducer == null)
5050 <                throw new NullPointerException();
5051 <            return new MapReduceMappingsToIntTask<K,V>
5052 <                (map, null, -1, null, transformer, basis, reducer);
5053 <        }
5054 <
5055 <        /**
5056 <         * Returns a task that when invoked, performs the given action
5057 <         * for each key.
5058 <         *
5059 <         * @param map the map
5060 <         * @param action the action
5061 <         * @return the task
5062 <         */
5063 <        public static <K,V> ForkJoinTask<Void> forEachKey
5064 <            (ConcurrentHashMapV8<K,V> map,
5065 <             Action<K> action) {
4582 >        public void forEach(Action<? super Map.Entry<K,V>> action) {
4583              if (action == null) throw new NullPointerException();
4584 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
4585 <        }
4586 <
4587 <        /**
4588 <         * Returns a task that when invoked, performs the given action
4589 <         * for each non-null transformation of each key.
5073 <         *
5074 <         * @param map the map
5075 <         * @param transformer a function returning the transformation
5076 <         * for an element, or null if there is no transformation (in
5077 <         * which case the action is not applied)
5078 <         * @param action the action
5079 <         * @return the task
5080 <         */
5081 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
5082 <            (ConcurrentHashMapV8<K,V> map,
5083 <             Fun<? super K, ? extends U> transformer,
5084 <             Action<U> action) {
5085 <            if (transformer == null || action == null)
5086 <                throw new NullPointerException();
5087 <            return new ForEachTransformedKeyTask<K,V,U>
5088 <                (map, null, -1, transformer, action);
5089 <        }
5090 <
5091 <        /**
5092 <         * Returns a task that when invoked, returns a non-null result
5093 <         * from applying the given search function on each key, or
5094 <         * null if none.  Upon success, further element processing is
5095 <         * suppressed and the results of any other parallel
5096 <         * invocations of the search function are ignored.
5097 <         *
5098 <         * @param map the map
5099 <         * @param searchFunction a function returning a non-null
5100 <         * result on success, else null
5101 <         * @return the task
5102 <         */
5103 <        public static <K,V,U> ForkJoinTask<U> searchKeys
5104 <            (ConcurrentHashMapV8<K,V> map,
5105 <             Fun<? super K, ? extends U> searchFunction) {
5106 <            if (searchFunction == null) throw new NullPointerException();
5107 <            return new SearchKeysTask<K,V,U>
5108 <                (map, null, -1, searchFunction,
5109 <                 new AtomicReference<U>());
5110 <        }
5111 <
5112 <        /**
5113 <         * Returns a task that when invoked, returns the result of
5114 <         * accumulating all keys using the given reducer to combine
5115 <         * values, or null if none.
5116 <         *
5117 <         * @param map the map
5118 <         * @param reducer a commutative associative combining function
5119 <         * @return the task
5120 <         */
5121 <        public static <K,V> ForkJoinTask<K> reduceKeys
5122 <            (ConcurrentHashMapV8<K,V> map,
5123 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5124 <            if (reducer == null) throw new NullPointerException();
5125 <            return new ReduceKeysTask<K,V>
5126 <                (map, null, -1, null, reducer);
5127 <        }
5128 <
5129 <        /**
5130 <         * Returns a task that when invoked, returns the result of
5131 <         * accumulating the given transformation of all keys using the given
5132 <         * reducer to combine values, or null if none.
5133 <         *
5134 <         * @param map the map
5135 <         * @param transformer a function returning the transformation
5136 <         * for an element, or null if there is no transformation (in
5137 <         * which case it is not combined)
5138 <         * @param reducer a commutative associative combining function
5139 <         * @return the task
5140 <         */
5141 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
5142 <            (ConcurrentHashMapV8<K,V> map,
5143 <             Fun<? super K, ? extends U> transformer,
5144 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5145 <            if (transformer == null || reducer == null)
5146 <                throw new NullPointerException();
5147 <            return new MapReduceKeysTask<K,V,U>
5148 <                (map, null, -1, null, transformer, reducer);
5149 <        }
5150 <
5151 <        /**
5152 <         * Returns a task that when invoked, returns the result of
5153 <         * accumulating the given transformation of all keys using the given
5154 <         * reducer to combine values, and the given basis as an
5155 <         * identity value.
5156 <         *
5157 <         * @param map the map
5158 <         * @param transformer a function returning the transformation
5159 <         * for an element
5160 <         * @param basis the identity (initial default value) for the reduction
5161 <         * @param reducer a commutative associative combining function
5162 <         * @return the task
5163 <         */
5164 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5165 <            (ConcurrentHashMapV8<K,V> map,
5166 <             ObjectToDouble<? super K> transformer,
5167 <             double basis,
5168 <             DoubleByDoubleToDouble reducer) {
5169 <            if (transformer == null || reducer == null)
5170 <                throw new NullPointerException();
5171 <            return new MapReduceKeysToDoubleTask<K,V>
5172 <                (map, null, -1, null, transformer, basis, reducer);
5173 <        }
5174 <
5175 <        /**
5176 <         * Returns a task that when invoked, returns the result of
5177 <         * accumulating the given transformation of all keys using the given
5178 <         * reducer to combine values, and the given basis as an
5179 <         * identity value.
5180 <         *
5181 <         * @param map the map
5182 <         * @param transformer a function returning the transformation
5183 <         * for an element
5184 <         * @param basis the identity (initial default value) for the reduction
5185 <         * @param reducer a commutative associative combining function
5186 <         * @return the task
5187 <         */
5188 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5189 <            (ConcurrentHashMapV8<K,V> map,
5190 <             ObjectToLong<? super K> transformer,
5191 <             long basis,
5192 <             LongByLongToLong reducer) {
5193 <            if (transformer == null || reducer == null)
5194 <                throw new NullPointerException();
5195 <            return new MapReduceKeysToLongTask<K,V>
5196 <                (map, null, -1, null, transformer, basis, reducer);
5197 <        }
5198 <
5199 <        /**
5200 <         * Returns a task that when invoked, returns the result of
5201 <         * accumulating the given transformation of all keys using the given
5202 <         * reducer to combine values, and the given basis as an
5203 <         * identity value.
5204 <         *
5205 <         * @param map the map
5206 <         * @param transformer a function returning the transformation
5207 <         * for an element
5208 <         * @param basis the identity (initial default value) for the reduction
5209 <         * @param reducer a commutative associative combining function
5210 <         * @return the task
5211 <         */
5212 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5213 <            (ConcurrentHashMapV8<K,V> map,
5214 <             ObjectToInt<? super K> transformer,
5215 <             int basis,
5216 <             IntByIntToInt reducer) {
5217 <            if (transformer == null || reducer == null)
5218 <                throw new NullPointerException();
5219 <            return new MapReduceKeysToIntTask<K,V>
5220 <                (map, null, -1, null, transformer, basis, reducer);
5221 <        }
5222 <
5223 <        /**
5224 <         * Returns a task that when invoked, performs the given action
5225 <         * for each value.
5226 <         *
5227 <         * @param map the map
5228 <         * @param action the action
5229 <         */
5230 <        public static <K,V> ForkJoinTask<Void> forEachValue
5231 <            (ConcurrentHashMapV8<K,V> map,
5232 <             Action<V> action) {
5233 <            if (action == null) throw new NullPointerException();
5234 <            return new ForEachValueTask<K,V>(map, null, -1, action);
5235 <        }
5236 <
5237 <        /**
5238 <         * Returns a task that when invoked, performs the given action
5239 <         * for each non-null transformation of each value.
5240 <         *
5241 <         * @param map the map
5242 <         * @param transformer a function returning the transformation
5243 <         * for an element, or null if there is no transformation (in
5244 <         * which case the action is not applied)
5245 <         * @param action the action
5246 <         */
5247 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
5248 <            (ConcurrentHashMapV8<K,V> map,
5249 <             Fun<? super V, ? extends U> transformer,
5250 <             Action<U> action) {
5251 <            if (transformer == null || action == null)
5252 <                throw new NullPointerException();
5253 <            return new ForEachTransformedValueTask<K,V,U>
5254 <                (map, null, -1, transformer, action);
5255 <        }
5256 <
5257 <        /**
5258 <         * Returns a task that when invoked, returns a non-null result
5259 <         * from applying the given search function on each value, or
5260 <         * null if none.  Upon success, further element processing is
5261 <         * suppressed and the results of any other parallel
5262 <         * invocations of the search function are ignored.
5263 <         *
5264 <         * @param map the map
5265 <         * @param searchFunction a function returning a non-null
5266 <         * result on success, else null
5267 <         * @return the task
5268 <         */
5269 <        public static <K,V,U> ForkJoinTask<U> searchValues
5270 <            (ConcurrentHashMapV8<K,V> map,
5271 <             Fun<? super V, ? extends U> searchFunction) {
5272 <            if (searchFunction == null) throw new NullPointerException();
5273 <            return new SearchValuesTask<K,V,U>
5274 <                (map, null, -1, searchFunction,
5275 <                 new AtomicReference<U>());
5276 <        }
5277 <
5278 <        /**
5279 <         * Returns a task that when invoked, returns the result of
5280 <         * accumulating all values using the given reducer to combine
5281 <         * values, or null if none.
5282 <         *
5283 <         * @param map the map
5284 <         * @param reducer a commutative associative combining function
5285 <         * @return the task
5286 <         */
5287 <        public static <K,V> ForkJoinTask<V> reduceValues
5288 <            (ConcurrentHashMapV8<K,V> map,
5289 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5290 <            if (reducer == null) throw new NullPointerException();
5291 <            return new ReduceValuesTask<K,V>
5292 <                (map, null, -1, null, reducer);
5293 <        }
5294 <
5295 <        /**
5296 <         * Returns a task that when invoked, returns the result of
5297 <         * accumulating the given transformation of all values using the
5298 <         * given reducer to combine values, or null if none.
5299 <         *
5300 <         * @param map the map
5301 <         * @param transformer a function returning the transformation
5302 <         * for an element, or null if there is no transformation (in
5303 <         * which case it is not combined)
5304 <         * @param reducer a commutative associative combining function
5305 <         * @return the task
5306 <         */
5307 <        public static <K,V,U> ForkJoinTask<U> reduceValues
5308 <            (ConcurrentHashMapV8<K,V> map,
5309 <             Fun<? super V, ? extends U> transformer,
5310 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5311 <            if (transformer == null || reducer == null)
5312 <                throw new NullPointerException();
5313 <            return new MapReduceValuesTask<K,V,U>
5314 <                (map, null, -1, null, transformer, reducer);
5315 <        }
5316 <
5317 <        /**
5318 <         * Returns a task that when invoked, returns the result of
5319 <         * accumulating the given transformation of all values using the
5320 <         * given reducer to combine values, and the given basis as an
5321 <         * identity value.
5322 <         *
5323 <         * @param map the map
5324 <         * @param transformer a function returning the transformation
5325 <         * for an element
5326 <         * @param basis the identity (initial default value) for the reduction
5327 <         * @param reducer a commutative associative combining function
5328 <         * @return the task
5329 <         */
5330 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5331 <            (ConcurrentHashMapV8<K,V> map,
5332 <             ObjectToDouble<? super V> transformer,
5333 <             double basis,
5334 <             DoubleByDoubleToDouble reducer) {
5335 <            if (transformer == null || reducer == null)
5336 <                throw new NullPointerException();
5337 <            return new MapReduceValuesToDoubleTask<K,V>
5338 <                (map, null, -1, null, transformer, basis, reducer);
5339 <        }
5340 <
5341 <        /**
5342 <         * Returns a task that when invoked, returns the result of
5343 <         * accumulating the given transformation of all values using the
5344 <         * given reducer to combine values, and the given basis as an
5345 <         * identity value.
5346 <         *
5347 <         * @param map the map
5348 <         * @param transformer a function returning the transformation
5349 <         * for an element
5350 <         * @param basis the identity (initial default value) for the reduction
5351 <         * @param reducer a commutative associative combining function
5352 <         * @return the task
5353 <         */
5354 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5355 <            (ConcurrentHashMapV8<K,V> map,
5356 <             ObjectToLong<? super V> transformer,
5357 <             long basis,
5358 <             LongByLongToLong reducer) {
5359 <            if (transformer == null || reducer == null)
5360 <                throw new NullPointerException();
5361 <            return new MapReduceValuesToLongTask<K,V>
5362 <                (map, null, -1, null, transformer, basis, reducer);
5363 <        }
5364 <
5365 <        /**
5366 <         * Returns a task that when invoked, returns the result of
5367 <         * accumulating the given transformation of all values using the
5368 <         * given reducer to combine values, and the given basis as an
5369 <         * identity value.
5370 <         *
5371 <         * @param map the map
5372 <         * @param transformer a function returning the transformation
5373 <         * for an element
5374 <         * @param basis the identity (initial default value) for the reduction
5375 <         * @param reducer a commutative associative combining function
5376 <         * @return the task
5377 <         */
5378 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5379 <            (ConcurrentHashMapV8<K,V> map,
5380 <             ObjectToInt<? super V> transformer,
5381 <             int basis,
5382 <             IntByIntToInt reducer) {
5383 <            if (transformer == null || reducer == null)
5384 <                throw new NullPointerException();
5385 <            return new MapReduceValuesToIntTask<K,V>
5386 <                (map, null, -1, null, transformer, basis, reducer);
5387 <        }
5388 <
5389 <        /**
5390 <         * Returns a task that when invoked, perform the given action
5391 <         * for each entry.
5392 <         *
5393 <         * @param map the map
5394 <         * @param action the action
5395 <         */
5396 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5397 <            (ConcurrentHashMapV8<K,V> map,
5398 <             Action<Map.Entry<K,V>> action) {
5399 <            if (action == null) throw new NullPointerException();
5400 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
5401 <        }
5402 <
5403 <        /**
5404 <         * Returns a task that when invoked, perform the given action
5405 <         * for each non-null transformation of each entry.
5406 <         *
5407 <         * @param map the map
5408 <         * @param transformer a function returning the transformation
5409 <         * for an element, or null if there is no transformation (in
5410 <         * which case the action is not applied)
5411 <         * @param action the action
5412 <         */
5413 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5414 <            (ConcurrentHashMapV8<K,V> map,
5415 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5416 <             Action<U> action) {
5417 <            if (transformer == null || action == null)
5418 <                throw new NullPointerException();
5419 <            return new ForEachTransformedEntryTask<K,V,U>
5420 <                (map, null, -1, transformer, action);
5421 <        }
5422 <
5423 <        /**
5424 <         * Returns a task that when invoked, returns a non-null result
5425 <         * from applying the given search function on each entry, or
5426 <         * null if none.  Upon success, further element processing is
5427 <         * suppressed and the results of any other parallel
5428 <         * invocations of the search function are ignored.
5429 <         *
5430 <         * @param map the map
5431 <         * @param searchFunction a function returning a non-null
5432 <         * result on success, else null
5433 <         * @return the task
5434 <         */
5435 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5436 <            (ConcurrentHashMapV8<K,V> map,
5437 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5438 <            if (searchFunction == null) throw new NullPointerException();
5439 <            return new SearchEntriesTask<K,V,U>
5440 <                (map, null, -1, searchFunction,
5441 <                 new AtomicReference<U>());
5442 <        }
5443 <
5444 <        /**
5445 <         * Returns a task that when invoked, returns the result of
5446 <         * accumulating all entries using the given reducer to combine
5447 <         * values, or null if none.
5448 <         *
5449 <         * @param map the map
5450 <         * @param reducer a commutative associative combining function
5451 <         * @return the task
5452 <         */
5453 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5454 <            (ConcurrentHashMapV8<K,V> map,
5455 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5456 <            if (reducer == null) throw new NullPointerException();
5457 <            return new ReduceEntriesTask<K,V>
5458 <                (map, null, -1, null, reducer);
4584 >            Node<K,V>[] t;
4585 >            if ((t = map.table) != null) {
4586 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4587 >                for (Node<K,V> p; (p = it.advance()) != null; )
4588 >                    action.apply(new MapEntry<K,V>(p.key, p.val, map));
4589 >            }
4590          }
4591  
4592 <        /**
5462 <         * Returns a task that when invoked, returns the result of
5463 <         * accumulating the given transformation of all entries using the
5464 <         * given reducer to combine values, or null if none.
5465 <         *
5466 <         * @param map the map
5467 <         * @param transformer a function returning the transformation
5468 <         * for an element, or null if there is no transformation (in
5469 <         * which case it is not combined)
5470 <         * @param reducer a commutative associative combining function
5471 <         * @return the task
5472 <         */
5473 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5474 <            (ConcurrentHashMapV8<K,V> map,
5475 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5476 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5477 <            if (transformer == null || reducer == null)
5478 <                throw new NullPointerException();
5479 <            return new MapReduceEntriesTask<K,V,U>
5480 <                (map, null, -1, null, transformer, reducer);
5481 <        }
4592 >    }
4593  
4594 <        /**
5484 <         * Returns a task that when invoked, returns the result of
5485 <         * accumulating the given transformation of all entries using the
5486 <         * given reducer to combine values, and the given basis as an
5487 <         * identity value.
5488 <         *
5489 <         * @param map the map
5490 <         * @param transformer a function returning the transformation
5491 <         * for an element
5492 <         * @param basis the identity (initial default value) for the reduction
5493 <         * @param reducer a commutative associative combining function
5494 <         * @return the task
5495 <         */
5496 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5497 <            (ConcurrentHashMapV8<K,V> map,
5498 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5499 <             double basis,
5500 <             DoubleByDoubleToDouble reducer) {
5501 <            if (transformer == null || reducer == null)
5502 <                throw new NullPointerException();
5503 <            return new MapReduceEntriesToDoubleTask<K,V>
5504 <                (map, null, -1, null, transformer, basis, reducer);
5505 <        }
4594 >    // -------------------------------------------------------
4595  
4596 <        /**
4597 <         * Returns a task that when invoked, returns the result of
4598 <         * accumulating the given transformation of all entries using the
4599 <         * given reducer to combine values, and the given basis as an
4600 <         * identity value.
4601 <         *
4602 <         * @param map the map
4603 <         * @param transformer a function returning the transformation
4604 <         * for an element
4605 <         * @param basis the identity (initial default value) for the reduction
4606 <         * @param reducer a commutative associative combining function
4607 <         * @return the task
4608 <         */
4609 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4610 <            (ConcurrentHashMapV8<K,V> map,
4611 <             ObjectToLong<Map.Entry<K,V>> transformer,
4612 <             long basis,
4613 <             LongByLongToLong reducer) {
4614 <            if (transformer == null || reducer == null)
4615 <                throw new NullPointerException();
4616 <            return new MapReduceEntriesToLongTask<K,V>
4617 <                (map, null, -1, null, transformer, basis, reducer);
4596 >    /**
4597 >     * Base class for bulk tasks. Repeats some fields and code from
4598 >     * class Traverser, because we need to subclass CountedCompleter.
4599 >     */
4600 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4601 >        Node<K,V>[] tab;        // same as Traverser
4602 >        Node<K,V> next;
4603 >        int index;
4604 >        int baseIndex;
4605 >        int baseLimit;
4606 >        final int baseSize;
4607 >        int batch;              // split control
4608 >
4609 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4610 >            super(par);
4611 >            this.batch = b;
4612 >            this.index = this.baseIndex = i;
4613 >            if ((this.tab = t) == null)
4614 >                this.baseSize = this.baseLimit = 0;
4615 >            else if (par == null)
4616 >                this.baseSize = this.baseLimit = t.length;
4617 >            else {
4618 >                this.baseLimit = f;
4619 >                this.baseSize = par.baseSize;
4620 >            }
4621          }
4622  
4623          /**
4624 <         * Returns a task that when invoked, returns the result of
5533 <         * accumulating the given transformation of all entries using the
5534 <         * given reducer to combine values, and the given basis as an
5535 <         * identity value.
5536 <         *
5537 <         * @param map the map
5538 <         * @param transformer a function returning the transformation
5539 <         * for an element
5540 <         * @param basis the identity (initial default value) for the reduction
5541 <         * @param reducer a commutative associative combining function
5542 <         * @return the task
4624 >         * Same as Traverser version
4625           */
4626 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4627 <            (ConcurrentHashMapV8<K,V> map,
4628 <             ObjectToInt<Map.Entry<K,V>> transformer,
4629 <             int basis,
4630 <             IntByIntToInt reducer) {
4631 <            if (transformer == null || reducer == null)
4632 <                throw new NullPointerException();
4633 <            return new MapReduceEntriesToIntTask<K,V>
4634 <                (map, null, -1, null, transformer, basis, reducer);
4626 >        final Node<K,V> advance() {
4627 >            Node<K,V> e;
4628 >            if ((e = next) != null)
4629 >                e = e.next;
4630 >            for (;;) {
4631 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4632 >                if (e != null)
4633 >                    return next = e;
4634 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4635 >                    (n = t.length) <= (i = index) || i < 0)
4636 >                    return next = null;
4637 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4638 >                    if (e instanceof ForwardingNode) {
4639 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4640 >                        e = null;
4641 >                        continue;
4642 >                    }
4643 >                    else if (e instanceof TreeBin)
4644 >                        e = ((TreeBin<K,V>)e).first;
4645 >                    else
4646 >                        e = null;
4647 >                }
4648 >                if ((index += baseSize) >= n)
4649 >                    index = ++baseIndex;    // visit upper slots if present
4650 >            }
4651          }
4652      }
4653  
5556    // -------------------------------------------------------
5557
4654      /*
4655       * Task classes. Coded in a regular but ugly format/style to
4656       * simplify checks that each variant differs in the right way from
# Line 5562 | Line 4658 | public class ConcurrentHashMapV8<K, V>
4658       * that we've already null-checked task arguments, so we force
4659       * simplest hoisted bypass to help avoid convoluted traps.
4660       */
4661 <
4662 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4663 <        extends Traverser<K,V,Void> {
4664 <        final Action<K> action;
4661 >    @SuppressWarnings("serial")
4662 >    static final class ForEachKeyTask<K,V>
4663 >        extends BulkTask<K,V,Void> {
4664 >        final Action<? super K> action;
4665          ForEachKeyTask
4666 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4667 <             Action<K> action) {
4668 <            super(m, p, b);
4666 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4667 >             Action<? super K> action) {
4668 >            super(p, b, i, f, t);
4669              this.action = action;
4670          }
4671 <        @SuppressWarnings("unchecked") public final void compute() {
4672 <            final Action<K> action;
4671 >        public final void compute() {
4672 >            final Action<? super K> action;
4673              if ((action = this.action) != null) {
4674 <                for (int b; (b = preSplit()) > 0;)
4675 <                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
4676 <                while (advance() != null)
4677 <                    action.apply((K)nextKey);
4674 >                for (int i = baseIndex, f, h; batch > 0 &&
4675 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4676 >                    addToPendingCount(1);
4677 >                    new ForEachKeyTask<K,V>
4678 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4679 >                         action).fork();
4680 >                }
4681 >                for (Node<K,V> p; (p = advance()) != null;)
4682 >                    action.apply(p.key);
4683                  propagateCompletion();
4684              }
4685          }
4686      }
4687  
4688 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4689 <        extends Traverser<K,V,Void> {
4690 <        final Action<V> action;
4688 >    @SuppressWarnings("serial")
4689 >    static final class ForEachValueTask<K,V>
4690 >        extends BulkTask<K,V,Void> {
4691 >        final Action<? super V> action;
4692          ForEachValueTask
4693 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4694 <             Action<V> action) {
4695 <            super(m, p, b);
4693 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4694 >             Action<? super V> action) {
4695 >            super(p, b, i, f, t);
4696              this.action = action;
4697          }
4698 <        @SuppressWarnings("unchecked") public final void compute() {
4699 <            final Action<V> action;
4698 >        public final void compute() {
4699 >            final Action<? super V> action;
4700              if ((action = this.action) != null) {
4701 <                for (int b; (b = preSplit()) > 0;)
4702 <                    new ForEachValueTask<K,V>(map, this, b, action).fork();
4703 <                V v;
4704 <                while ((v = advance()) != null)
4705 <                    action.apply(v);
4701 >                for (int i = baseIndex, f, h; batch > 0 &&
4702 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4703 >                    addToPendingCount(1);
4704 >                    new ForEachValueTask<K,V>
4705 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4706 >                         action).fork();
4707 >                }
4708 >                for (Node<K,V> p; (p = advance()) != null;)
4709 >                    action.apply(p.val);
4710                  propagateCompletion();
4711              }
4712          }
4713      }
4714  
4715 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4716 <        extends Traverser<K,V,Void> {
4717 <        final Action<Entry<K,V>> action;
4715 >    @SuppressWarnings("serial")
4716 >    static final class ForEachEntryTask<K,V>
4717 >        extends BulkTask<K,V,Void> {
4718 >        final Action<? super Entry<K,V>> action;
4719          ForEachEntryTask
4720 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4721 <             Action<Entry<K,V>> action) {
4722 <            super(m, p, b);
4720 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4721 >             Action<? super Entry<K,V>> action) {
4722 >            super(p, b, i, f, t);
4723              this.action = action;
4724          }
4725 <        @SuppressWarnings("unchecked") public final void compute() {
4726 <            final Action<Entry<K,V>> action;
4725 >        public final void compute() {
4726 >            final Action<? super Entry<K,V>> action;
4727              if ((action = this.action) != null) {
4728 <                for (int b; (b = preSplit()) > 0;)
4729 <                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
4730 <                V v;
4731 <                while ((v = advance()) != null)
4732 <                    action.apply(entryFor((K)nextKey, v));
4728 >                for (int i = baseIndex, f, h; batch > 0 &&
4729 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4730 >                    addToPendingCount(1);
4731 >                    new ForEachEntryTask<K,V>
4732 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4733 >                         action).fork();
4734 >                }
4735 >                for (Node<K,V> p; (p = advance()) != null; )
4736 >                    action.apply(p);
4737                  propagateCompletion();
4738              }
4739          }
4740      }
4741  
4742 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4743 <        extends Traverser<K,V,Void> {
4744 <        final BiAction<K,V> action;
4742 >    @SuppressWarnings("serial")
4743 >    static final class ForEachMappingTask<K,V>
4744 >        extends BulkTask<K,V,Void> {
4745 >        final BiAction<? super K, ? super V> action;
4746          ForEachMappingTask
4747 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4748 <             BiAction<K,V> action) {
4749 <            super(m, p, b);
4747 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4748 >             BiAction<? super K,? super V> action) {
4749 >            super(p, b, i, f, t);
4750              this.action = action;
4751          }
4752 <        @SuppressWarnings("unchecked") public final void compute() {
4753 <            final BiAction<K,V> action;
4752 >        public final void compute() {
4753 >            final BiAction<? super K, ? super V> action;
4754              if ((action = this.action) != null) {
4755 <                for (int b; (b = preSplit()) > 0;)
4756 <                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
4757 <                V v;
4758 <                while ((v = advance()) != null)
4759 <                    action.apply((K)nextKey, v);
4755 >                for (int i = baseIndex, f, h; batch > 0 &&
4756 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4757 >                    addToPendingCount(1);
4758 >                    new ForEachMappingTask<K,V>
4759 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4760 >                         action).fork();
4761 >                }
4762 >                for (Node<K,V> p; (p = advance()) != null; )
4763 >                    action.apply(p.key, p.val);
4764                  propagateCompletion();
4765              }
4766          }
4767      }
4768  
4769 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4770 <        extends Traverser<K,V,Void> {
4769 >    @SuppressWarnings("serial")
4770 >    static final class ForEachTransformedKeyTask<K,V,U>
4771 >        extends BulkTask<K,V,Void> {
4772          final Fun<? super K, ? extends U> transformer;
4773 <        final Action<U> action;
4773 >        final Action<? super U> action;
4774          ForEachTransformedKeyTask
4775 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4776 <             Fun<? super K, ? extends U> transformer, Action<U> action) {
4777 <            super(m, p, b);
4775 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4776 >             Fun<? super K, ? extends U> transformer, Action<? super U> action) {
4777 >            super(p, b, i, f, t);
4778              this.transformer = transformer; this.action = action;
4779          }
4780 <        @SuppressWarnings("unchecked") public final void compute() {
4780 >        public final void compute() {
4781              final Fun<? super K, ? extends U> transformer;
4782 <            final Action<U> action;
4782 >            final Action<? super U> action;
4783              if ((transformer = this.transformer) != null &&
4784                  (action = this.action) != null) {
4785 <                for (int b; (b = preSplit()) > 0;)
4785 >                for (int i = baseIndex, f, h; batch > 0 &&
4786 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4787 >                    addToPendingCount(1);
4788                      new ForEachTransformedKeyTask<K,V,U>
4789 <                        (map, this, b, transformer, action).fork();
4790 <                U u;
4791 <                while (advance() != null) {
4792 <                    if ((u = transformer.apply((K)nextKey)) != null)
4789 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4790 >                         transformer, action).fork();
4791 >                }
4792 >                for (Node<K,V> p; (p = advance()) != null; ) {
4793 >                    U u;
4794 >                    if ((u = transformer.apply(p.key)) != null)
4795                          action.apply(u);
4796                  }
4797                  propagateCompletion();
# Line 5678 | Line 4799 | public class ConcurrentHashMapV8<K, V>
4799          }
4800      }
4801  
4802 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
4803 <        extends Traverser<K,V,Void> {
4802 >    @SuppressWarnings("serial")
4803 >    static final class ForEachTransformedValueTask<K,V,U>
4804 >        extends BulkTask<K,V,Void> {
4805          final Fun<? super V, ? extends U> transformer;
4806 <        final Action<U> action;
4806 >        final Action<? super U> action;
4807          ForEachTransformedValueTask
4808 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4809 <             Fun<? super V, ? extends U> transformer, Action<U> action) {
4810 <            super(m, p, b);
4808 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4809 >             Fun<? super V, ? extends U> transformer, Action<? super U> action) {
4810 >            super(p, b, i, f, t);
4811              this.transformer = transformer; this.action = action;
4812          }
4813 <        @SuppressWarnings("unchecked") public final void compute() {
4813 >        public final void compute() {
4814              final Fun<? super V, ? extends U> transformer;
4815 <            final Action<U> action;
4815 >            final Action<? super U> action;
4816              if ((transformer = this.transformer) != null &&
4817                  (action = this.action) != null) {
4818 <                for (int b; (b = preSplit()) > 0;)
4818 >                for (int i = baseIndex, f, h; batch > 0 &&
4819 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4820 >                    addToPendingCount(1);
4821                      new ForEachTransformedValueTask<K,V,U>
4822 <                        (map, this, b, transformer, action).fork();
4823 <                V v; U u;
4824 <                while ((v = advance()) != null) {
4825 <                    if ((u = transformer.apply(v)) != null)
4822 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4823 >                         transformer, action).fork();
4824 >                }
4825 >                for (Node<K,V> p; (p = advance()) != null; ) {
4826 >                    U u;
4827 >                    if ((u = transformer.apply(p.val)) != null)
4828                          action.apply(u);
4829                  }
4830                  propagateCompletion();
# Line 5706 | Line 4832 | public class ConcurrentHashMapV8<K, V>
4832          }
4833      }
4834  
4835 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
4836 <        extends Traverser<K,V,Void> {
4835 >    @SuppressWarnings("serial")
4836 >    static final class ForEachTransformedEntryTask<K,V,U>
4837 >        extends BulkTask<K,V,Void> {
4838          final Fun<Map.Entry<K,V>, ? extends U> transformer;
4839 <        final Action<U> action;
4839 >        final Action<? super U> action;
4840          ForEachTransformedEntryTask
4841 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4842 <             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<U> action) {
4843 <            super(m, p, b);
4841 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4842 >             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<? super U> action) {
4843 >            super(p, b, i, f, t);
4844              this.transformer = transformer; this.action = action;
4845          }
4846 <        @SuppressWarnings("unchecked") public final void compute() {
4846 >        public final void compute() {
4847              final Fun<Map.Entry<K,V>, ? extends U> transformer;
4848 <            final Action<U> action;
4848 >            final Action<? super U> action;
4849              if ((transformer = this.transformer) != null &&
4850                  (action = this.action) != null) {
4851 <                for (int b; (b = preSplit()) > 0;)
4851 >                for (int i = baseIndex, f, h; batch > 0 &&
4852 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4853 >                    addToPendingCount(1);
4854                      new ForEachTransformedEntryTask<K,V,U>
4855 <                        (map, this, b, transformer, action).fork();
4856 <                V v; U u;
4857 <                while ((v = advance()) != null) {
4858 <                    if ((u = transformer.apply(entryFor((K)nextKey,
4859 <                                                        v))) != null)
4855 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4856 >                         transformer, action).fork();
4857 >                }
4858 >                for (Node<K,V> p; (p = advance()) != null; ) {
4859 >                    U u;
4860 >                    if ((u = transformer.apply(p)) != null)
4861                          action.apply(u);
4862                  }
4863                  propagateCompletion();
# Line 5735 | Line 4865 | public class ConcurrentHashMapV8<K, V>
4865          }
4866      }
4867  
4868 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
4869 <        extends Traverser<K,V,Void> {
4868 >    @SuppressWarnings("serial")
4869 >    static final class ForEachTransformedMappingTask<K,V,U>
4870 >        extends BulkTask<K,V,Void> {
4871          final BiFun<? super K, ? super V, ? extends U> transformer;
4872 <        final Action<U> action;
4872 >        final Action<? super U> action;
4873          ForEachTransformedMappingTask
4874 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4874 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4875               BiFun<? super K, ? super V, ? extends U> transformer,
4876 <             Action<U> action) {
4877 <            super(m, p, b);
4876 >             Action<? super U> action) {
4877 >            super(p, b, i, f, t);
4878              this.transformer = transformer; this.action = action;
4879          }
4880 <        @SuppressWarnings("unchecked") public final void compute() {
4880 >        public final void compute() {
4881              final BiFun<? super K, ? super V, ? extends U> transformer;
4882 <            final Action<U> action;
4882 >            final Action<? super U> action;
4883              if ((transformer = this.transformer) != null &&
4884                  (action = this.action) != null) {
4885 <                for (int b; (b = preSplit()) > 0;)
4885 >                for (int i = baseIndex, f, h; batch > 0 &&
4886 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4887 >                    addToPendingCount(1);
4888                      new ForEachTransformedMappingTask<K,V,U>
4889 <                        (map, this, b, transformer, action).fork();
4890 <                V v; U u;
4891 <                while ((v = advance()) != null) {
4892 <                    if ((u = transformer.apply((K)nextKey, v)) != null)
4889 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4890 >                         transformer, action).fork();
4891 >                }
4892 >                for (Node<K,V> p; (p = advance()) != null; ) {
4893 >                    U u;
4894 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4895                          action.apply(u);
4896                  }
4897                  propagateCompletion();
# Line 5764 | Line 4899 | public class ConcurrentHashMapV8<K, V>
4899          }
4900      }
4901  
4902 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
4903 <        extends Traverser<K,V,U> {
4902 >    @SuppressWarnings("serial")
4903 >    static final class SearchKeysTask<K,V,U>
4904 >        extends BulkTask<K,V,U> {
4905          final Fun<? super K, ? extends U> searchFunction;
4906          final AtomicReference<U> result;
4907          SearchKeysTask
4908 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4908 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4909               Fun<? super K, ? extends U> searchFunction,
4910               AtomicReference<U> result) {
4911 <            super(m, p, b);
4911 >            super(p, b, i, f, t);
4912              this.searchFunction = searchFunction; this.result = result;
4913          }
4914          public final U getRawResult() { return result.get(); }
4915 <        @SuppressWarnings("unchecked") public final void compute() {
4915 >        public final void compute() {
4916              final Fun<? super K, ? extends U> searchFunction;
4917              final AtomicReference<U> result;
4918              if ((searchFunction = this.searchFunction) != null &&
4919                  (result = this.result) != null) {
4920 <                for (int b;;) {
4920 >                for (int i = baseIndex, f, h; batch > 0 &&
4921 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4922                      if (result.get() != null)
4923                          return;
4924 <                    if ((b = preSplit()) <= 0)
5788 <                        break;
4924 >                    addToPendingCount(1);
4925                      new SearchKeysTask<K,V,U>
4926 <                        (map, this, b, searchFunction, result).fork();
4926 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4927 >                         searchFunction, result).fork();
4928                  }
4929                  while (result.get() == null) {
4930                      U u;
4931 <                    if (advance() == null) {
4931 >                    Node<K,V> p;
4932 >                    if ((p = advance()) == null) {
4933                          propagateCompletion();
4934                          break;
4935                      }
4936 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
4936 >                    if ((u = searchFunction.apply(p.key)) != null) {
4937                          if (result.compareAndSet(null, u))
4938                              quietlyCompleteRoot();
4939                          break;
# Line 5805 | Line 4943 | public class ConcurrentHashMapV8<K, V>
4943          }
4944      }
4945  
4946 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
4947 <        extends Traverser<K,V,U> {
4946 >    @SuppressWarnings("serial")
4947 >    static final class SearchValuesTask<K,V,U>
4948 >        extends BulkTask<K,V,U> {
4949          final Fun<? super V, ? extends U> searchFunction;
4950          final AtomicReference<U> result;
4951          SearchValuesTask
4952 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4952 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4953               Fun<? super V, ? extends U> searchFunction,
4954               AtomicReference<U> result) {
4955 <            super(m, p, b);
4955 >            super(p, b, i, f, t);
4956              this.searchFunction = searchFunction; this.result = result;
4957          }
4958          public final U getRawResult() { return result.get(); }
4959 <        @SuppressWarnings("unchecked") public final void compute() {
4959 >        public final void compute() {
4960              final Fun<? super V, ? extends U> searchFunction;
4961              final AtomicReference<U> result;
4962              if ((searchFunction = this.searchFunction) != null &&
4963                  (result = this.result) != null) {
4964 <                for (int b;;) {
4964 >                for (int i = baseIndex, f, h; batch > 0 &&
4965 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4966                      if (result.get() != null)
4967                          return;
4968 <                    if ((b = preSplit()) <= 0)
5829 <                        break;
4968 >                    addToPendingCount(1);
4969                      new SearchValuesTask<K,V,U>
4970 <                        (map, this, b, searchFunction, result).fork();
4970 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4971 >                         searchFunction, result).fork();
4972                  }
4973                  while (result.get() == null) {
4974 <                    V v; U u;
4975 <                    if ((v = advance()) == null) {
4974 >                    U u;
4975 >                    Node<K,V> p;
4976 >                    if ((p = advance()) == null) {
4977                          propagateCompletion();
4978                          break;
4979                      }
4980 <                    if ((u = searchFunction.apply(v)) != null) {
4980 >                    if ((u = searchFunction.apply(p.val)) != null) {
4981                          if (result.compareAndSet(null, u))
4982                              quietlyCompleteRoot();
4983                          break;
# Line 5846 | Line 4987 | public class ConcurrentHashMapV8<K, V>
4987          }
4988      }
4989  
4990 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
4991 <        extends Traverser<K,V,U> {
4990 >    @SuppressWarnings("serial")
4991 >    static final class SearchEntriesTask<K,V,U>
4992 >        extends BulkTask<K,V,U> {
4993          final Fun<Entry<K,V>, ? extends U> searchFunction;
4994          final AtomicReference<U> result;
4995          SearchEntriesTask
4996 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4996 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4997               Fun<Entry<K,V>, ? extends U> searchFunction,
4998               AtomicReference<U> result) {
4999 <            super(m, p, b);
4999 >            super(p, b, i, f, t);
5000              this.searchFunction = searchFunction; this.result = result;
5001          }
5002          public final U getRawResult() { return result.get(); }
5003 <        @SuppressWarnings("unchecked") public final void compute() {
5003 >        public final void compute() {
5004              final Fun<Entry<K,V>, ? extends U> searchFunction;
5005              final AtomicReference<U> result;
5006              if ((searchFunction = this.searchFunction) != null &&
5007                  (result = this.result) != null) {
5008 <                for (int b;;) {
5008 >                for (int i = baseIndex, f, h; batch > 0 &&
5009 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5010                      if (result.get() != null)
5011                          return;
5012 <                    if ((b = preSplit()) <= 0)
5870 <                        break;
5012 >                    addToPendingCount(1);
5013                      new SearchEntriesTask<K,V,U>
5014 <                        (map, this, b, searchFunction, result).fork();
5014 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5015 >                         searchFunction, result).fork();
5016                  }
5017                  while (result.get() == null) {
5018 <                    V v; U u;
5019 <                    if ((v = advance()) == null) {
5018 >                    U u;
5019 >                    Node<K,V> p;
5020 >                    if ((p = advance()) == null) {
5021                          propagateCompletion();
5022                          break;
5023                      }
5024 <                    if ((u = searchFunction.apply(entryFor((K)nextKey,
5881 <                                                           v))) != null) {
5024 >                    if ((u = searchFunction.apply(p)) != null) {
5025                          if (result.compareAndSet(null, u))
5026                              quietlyCompleteRoot();
5027                          return;
# Line 5888 | Line 5031 | public class ConcurrentHashMapV8<K, V>
5031          }
5032      }
5033  
5034 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5035 <        extends Traverser<K,V,U> {
5034 >    @SuppressWarnings("serial")
5035 >    static final class SearchMappingsTask<K,V,U>
5036 >        extends BulkTask<K,V,U> {
5037          final BiFun<? super K, ? super V, ? extends U> searchFunction;
5038          final AtomicReference<U> result;
5039          SearchMappingsTask
5040 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5040 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5041               BiFun<? super K, ? super V, ? extends U> searchFunction,
5042               AtomicReference<U> result) {
5043 <            super(m, p, b);
5043 >            super(p, b, i, f, t);
5044              this.searchFunction = searchFunction; this.result = result;
5045          }
5046          public final U getRawResult() { return result.get(); }
5047 <        @SuppressWarnings("unchecked") public final void compute() {
5047 >        public final void compute() {
5048              final BiFun<? super K, ? super V, ? extends U> searchFunction;
5049              final AtomicReference<U> result;
5050              if ((searchFunction = this.searchFunction) != null &&
5051                  (result = this.result) != null) {
5052 <                for (int b;;) {
5052 >                for (int i = baseIndex, f, h; batch > 0 &&
5053 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5054                      if (result.get() != null)
5055                          return;
5056 <                    if ((b = preSplit()) <= 0)
5912 <                        break;
5056 >                    addToPendingCount(1);
5057                      new SearchMappingsTask<K,V,U>
5058 <                        (map, this, b, searchFunction, result).fork();
5058 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5059 >                         searchFunction, result).fork();
5060                  }
5061                  while (result.get() == null) {
5062 <                    V v; U u;
5063 <                    if ((v = advance()) == null) {
5062 >                    U u;
5063 >                    Node<K,V> p;
5064 >                    if ((p = advance()) == null) {
5065                          propagateCompletion();
5066                          break;
5067                      }
5068 <                    if ((u = searchFunction.apply((K)nextKey, v)) != null) {
5068 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5069                          if (result.compareAndSet(null, u))
5070                              quietlyCompleteRoot();
5071                          break;
# Line 5929 | Line 5075 | public class ConcurrentHashMapV8<K, V>
5075          }
5076      }
5077  
5078 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5079 <        extends Traverser<K,V,K> {
5078 >    @SuppressWarnings("serial")
5079 >    static final class ReduceKeysTask<K,V>
5080 >        extends BulkTask<K,V,K> {
5081          final BiFun<? super K, ? super K, ? extends K> reducer;
5082          K result;
5083          ReduceKeysTask<K,V> rights, nextRight;
5084          ReduceKeysTask
5085 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5085 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5086               ReduceKeysTask<K,V> nextRight,
5087               BiFun<? super K, ? super K, ? extends K> reducer) {
5088 <            super(m, p, b); this.nextRight = nextRight;
5088 >            super(p, b, i, f, t); this.nextRight = nextRight;
5089              this.reducer = reducer;
5090          }
5091          public final K getRawResult() { return result; }
5092 <        @SuppressWarnings("unchecked") public final void compute() {
5092 >        public final void compute() {
5093              final BiFun<? super K, ? super K, ? extends K> reducer;
5094              if ((reducer = this.reducer) != null) {
5095 <                for (int b; (b = preSplit()) > 0;)
5095 >                for (int i = baseIndex, f, h; batch > 0 &&
5096 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5097 >                    addToPendingCount(1);
5098                      (rights = new ReduceKeysTask<K,V>
5099 <                     (map, this, b, rights, reducer)).fork();
5099 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5100 >                      rights, reducer)).fork();
5101 >                }
5102                  K r = null;
5103 <                while (advance() != null) {
5104 <                    K u = (K)nextKey;
5105 <                    r = (r == null) ? u : reducer.apply(r, u);
5103 >                for (Node<K,V> p; (p = advance()) != null; ) {
5104 >                    K u = p.key;
5105 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5106                  }
5107                  result = r;
5108                  CountedCompleter<?> c;
5109                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5110 <                    ReduceKeysTask<K,V>
5110 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5111                          t = (ReduceKeysTask<K,V>)c,
5112                          s = t.rights;
5113                      while (s != null) {
# Line 5971 | Line 5122 | public class ConcurrentHashMapV8<K, V>
5122          }
5123      }
5124  
5125 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5126 <        extends Traverser<K,V,V> {
5125 >    @SuppressWarnings("serial")
5126 >    static final class ReduceValuesTask<K,V>
5127 >        extends BulkTask<K,V,V> {
5128          final BiFun<? super V, ? super V, ? extends V> reducer;
5129          V result;
5130          ReduceValuesTask<K,V> rights, nextRight;
5131          ReduceValuesTask
5132 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5132 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5133               ReduceValuesTask<K,V> nextRight,
5134               BiFun<? super V, ? super V, ? extends V> reducer) {
5135 <            super(m, p, b); this.nextRight = nextRight;
5135 >            super(p, b, i, f, t); this.nextRight = nextRight;
5136              this.reducer = reducer;
5137          }
5138          public final V getRawResult() { return result; }
5139 <        @SuppressWarnings("unchecked") public final void compute() {
5139 >        public final void compute() {
5140              final BiFun<? super V, ? super V, ? extends V> reducer;
5141              if ((reducer = this.reducer) != null) {
5142 <                for (int b; (b = preSplit()) > 0;)
5142 >                for (int i = baseIndex, f, h; batch > 0 &&
5143 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5144 >                    addToPendingCount(1);
5145                      (rights = new ReduceValuesTask<K,V>
5146 <                     (map, this, b, rights, reducer)).fork();
5146 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5147 >                      rights, reducer)).fork();
5148 >                }
5149                  V r = null;
5150 <                V v;
5151 <                while ((v = advance()) != null) {
5152 <                    V u = v;
5997 <                    r = (r == null) ? u : reducer.apply(r, u);
5150 >                for (Node<K,V> p; (p = advance()) != null; ) {
5151 >                    V v = p.val;
5152 >                    r = (r == null) ? v : reducer.apply(r, v);
5153                  }
5154                  result = r;
5155                  CountedCompleter<?> c;
5156                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5157 <                    ReduceValuesTask<K,V>
5157 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5158                          t = (ReduceValuesTask<K,V>)c,
5159                          s = t.rights;
5160                      while (s != null) {
# Line 6014 | Line 5169 | public class ConcurrentHashMapV8<K, V>
5169          }
5170      }
5171  
5172 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5173 <        extends Traverser<K,V,Map.Entry<K,V>> {
5172 >    @SuppressWarnings("serial")
5173 >    static final class ReduceEntriesTask<K,V>
5174 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5175          final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5176          Map.Entry<K,V> result;
5177          ReduceEntriesTask<K,V> rights, nextRight;
5178          ReduceEntriesTask
5179 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5179 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5180               ReduceEntriesTask<K,V> nextRight,
5181               BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5182 <            super(m, p, b); this.nextRight = nextRight;
5182 >            super(p, b, i, f, t); this.nextRight = nextRight;
5183              this.reducer = reducer;
5184          }
5185          public final Map.Entry<K,V> getRawResult() { return result; }
5186 <        @SuppressWarnings("unchecked") public final void compute() {
5186 >        public final void compute() {
5187              final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5188              if ((reducer = this.reducer) != null) {
5189 <                for (int b; (b = preSplit()) > 0;)
5189 >                for (int i = baseIndex, f, h; batch > 0 &&
5190 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5191 >                    addToPendingCount(1);
5192                      (rights = new ReduceEntriesTask<K,V>
5193 <                     (map, this, b, rights, reducer)).fork();
5194 <                Map.Entry<K,V> r = null;
6037 <                V v;
6038 <                while ((v = advance()) != null) {
6039 <                    Map.Entry<K,V> u = entryFor((K)nextKey, v);
6040 <                    r = (r == null) ? u : reducer.apply(r, u);
5193 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5194 >                      rights, reducer)).fork();
5195                  }
5196 +                Map.Entry<K,V> r = null;
5197 +                for (Node<K,V> p; (p = advance()) != null; )
5198 +                    r = (r == null) ? p : reducer.apply(r, p);
5199                  result = r;
5200                  CountedCompleter<?> c;
5201                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5202 <                    ReduceEntriesTask<K,V>
5202 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5203                          t = (ReduceEntriesTask<K,V>)c,
5204                          s = t.rights;
5205                      while (s != null) {
# Line 6057 | Line 5214 | public class ConcurrentHashMapV8<K, V>
5214          }
5215      }
5216  
5217 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5218 <        extends Traverser<K,V,U> {
5217 >    @SuppressWarnings("serial")
5218 >    static final class MapReduceKeysTask<K,V,U>
5219 >        extends BulkTask<K,V,U> {
5220          final Fun<? super K, ? extends U> transformer;
5221          final BiFun<? super U, ? super U, ? extends U> reducer;
5222          U result;
5223          MapReduceKeysTask<K,V,U> rights, nextRight;
5224          MapReduceKeysTask
5225 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5225 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5226               MapReduceKeysTask<K,V,U> nextRight,
5227               Fun<? super K, ? extends U> transformer,
5228               BiFun<? super U, ? super U, ? extends U> reducer) {
5229 <            super(m, p, b); this.nextRight = nextRight;
5229 >            super(p, b, i, f, t); this.nextRight = nextRight;
5230              this.transformer = transformer;
5231              this.reducer = reducer;
5232          }
5233          public final U getRawResult() { return result; }
5234 <        @SuppressWarnings("unchecked") public final void compute() {
5234 >        public final void compute() {
5235              final Fun<? super K, ? extends U> transformer;
5236              final BiFun<? super U, ? super U, ? extends U> reducer;
5237              if ((transformer = this.transformer) != null &&
5238                  (reducer = this.reducer) != null) {
5239 <                for (int b; (b = preSplit()) > 0;)
5239 >                for (int i = baseIndex, f, h; batch > 0 &&
5240 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5241 >                    addToPendingCount(1);
5242                      (rights = new MapReduceKeysTask<K,V,U>
5243 <                     (map, this, b, rights, transformer, reducer)).fork();
5244 <                U r = null, u;
5245 <                while (advance() != null) {
5246 <                    if ((u = transformer.apply((K)nextKey)) != null)
5243 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5244 >                      rights, transformer, reducer)).fork();
5245 >                }
5246 >                U r = null;
5247 >                for (Node<K,V> p; (p = advance()) != null; ) {
5248 >                    U u;
5249 >                    if ((u = transformer.apply(p.key)) != null)
5250                          r = (r == null) ? u : reducer.apply(r, u);
5251                  }
5252                  result = r;
5253                  CountedCompleter<?> c;
5254                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5255 <                    MapReduceKeysTask<K,V,U>
5255 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5256                          t = (MapReduceKeysTask<K,V,U>)c,
5257                          s = t.rights;
5258                      while (s != null) {
# Line 6104 | Line 5267 | public class ConcurrentHashMapV8<K, V>
5267          }
5268      }
5269  
5270 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5271 <        extends Traverser<K,V,U> {
5270 >    @SuppressWarnings("serial")
5271 >    static final class MapReduceValuesTask<K,V,U>
5272 >        extends BulkTask<K,V,U> {
5273          final Fun<? super V, ? extends U> transformer;
5274          final BiFun<? super U, ? super U, ? extends U> reducer;
5275          U result;
5276          MapReduceValuesTask<K,V,U> rights, nextRight;
5277          MapReduceValuesTask
5278 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5278 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5279               MapReduceValuesTask<K,V,U> nextRight,
5280               Fun<? super V, ? extends U> transformer,
5281               BiFun<? super U, ? super U, ? extends U> reducer) {
5282 <            super(m, p, b); this.nextRight = nextRight;
5282 >            super(p, b, i, f, t); this.nextRight = nextRight;
5283              this.transformer = transformer;
5284              this.reducer = reducer;
5285          }
5286          public final U getRawResult() { return result; }
5287 <        @SuppressWarnings("unchecked") public final void compute() {
5287 >        public final void compute() {
5288              final Fun<? super V, ? extends U> transformer;
5289              final BiFun<? super U, ? super U, ? extends U> reducer;
5290              if ((transformer = this.transformer) != null &&
5291                  (reducer = this.reducer) != null) {
5292 <                for (int b; (b = preSplit()) > 0;)
5292 >                for (int i = baseIndex, f, h; batch > 0 &&
5293 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5294 >                    addToPendingCount(1);
5295                      (rights = new MapReduceValuesTask<K,V,U>
5296 <                     (map, this, b, rights, transformer, reducer)).fork();
5297 <                U r = null, u;
5298 <                V v;
5299 <                while ((v = advance()) != null) {
5300 <                    if ((u = transformer.apply(v)) != null)
5296 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5297 >                      rights, transformer, reducer)).fork();
5298 >                }
5299 >                U r = null;
5300 >                for (Node<K,V> p; (p = advance()) != null; ) {
5301 >                    U u;
5302 >                    if ((u = transformer.apply(p.val)) != null)
5303                          r = (r == null) ? u : reducer.apply(r, u);
5304                  }
5305                  result = r;
5306                  CountedCompleter<?> c;
5307                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5308 <                    MapReduceValuesTask<K,V,U>
5308 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5309                          t = (MapReduceValuesTask<K,V,U>)c,
5310                          s = t.rights;
5311                      while (s != null) {
# Line 6152 | Line 5320 | public class ConcurrentHashMapV8<K, V>
5320          }
5321      }
5322  
5323 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5324 <        extends Traverser<K,V,U> {
5323 >    @SuppressWarnings("serial")
5324 >    static final class MapReduceEntriesTask<K,V,U>
5325 >        extends BulkTask<K,V,U> {
5326          final Fun<Map.Entry<K,V>, ? extends U> transformer;
5327          final BiFun<? super U, ? super U, ? extends U> reducer;
5328          U result;
5329          MapReduceEntriesTask<K,V,U> rights, nextRight;
5330          MapReduceEntriesTask
5331 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5331 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5332               MapReduceEntriesTask<K,V,U> nextRight,
5333               Fun<Map.Entry<K,V>, ? extends U> transformer,
5334               BiFun<? super U, ? super U, ? extends U> reducer) {
5335 <            super(m, p, b); this.nextRight = nextRight;
5335 >            super(p, b, i, f, t); this.nextRight = nextRight;
5336              this.transformer = transformer;
5337              this.reducer = reducer;
5338          }
5339          public final U getRawResult() { return result; }
5340 <        @SuppressWarnings("unchecked") public final void compute() {
5340 >        public final void compute() {
5341              final Fun<Map.Entry<K,V>, ? extends U> transformer;
5342              final BiFun<? super U, ? super U, ? extends U> reducer;
5343              if ((transformer = this.transformer) != null &&
5344                  (reducer = this.reducer) != null) {
5345 <                for (int b; (b = preSplit()) > 0;)
5345 >                for (int i = baseIndex, f, h; batch > 0 &&
5346 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5347 >                    addToPendingCount(1);
5348                      (rights = new MapReduceEntriesTask<K,V,U>
5349 <                     (map, this, b, rights, transformer, reducer)).fork();
5350 <                U r = null, u;
5351 <                V v;
5352 <                while ((v = advance()) != null) {
5353 <                    if ((u = transformer.apply(entryFor((K)nextKey,
5354 <                                                        v))) != null)
5349 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5350 >                      rights, transformer, reducer)).fork();
5351 >                }
5352 >                U r = null;
5353 >                for (Node<K,V> p; (p = advance()) != null; ) {
5354 >                    U u;
5355 >                    if ((u = transformer.apply(p)) != null)
5356                          r = (r == null) ? u : reducer.apply(r, u);
5357                  }
5358                  result = r;
5359                  CountedCompleter<?> c;
5360                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5361 <                    MapReduceEntriesTask<K,V,U>
5361 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5362                          t = (MapReduceEntriesTask<K,V,U>)c,
5363                          s = t.rights;
5364                      while (s != null) {
# Line 6201 | Line 5373 | public class ConcurrentHashMapV8<K, V>
5373          }
5374      }
5375  
5376 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5377 <        extends Traverser<K,V,U> {
5376 >    @SuppressWarnings("serial")
5377 >    static final class MapReduceMappingsTask<K,V,U>
5378 >        extends BulkTask<K,V,U> {
5379          final BiFun<? super K, ? super V, ? extends U> transformer;
5380          final BiFun<? super U, ? super U, ? extends U> reducer;
5381          U result;
5382          MapReduceMappingsTask<K,V,U> rights, nextRight;
5383          MapReduceMappingsTask
5384 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5384 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5385               MapReduceMappingsTask<K,V,U> nextRight,
5386               BiFun<? super K, ? super V, ? extends U> transformer,
5387               BiFun<? super U, ? super U, ? extends U> reducer) {
5388 <            super(m, p, b); this.nextRight = nextRight;
5388 >            super(p, b, i, f, t); this.nextRight = nextRight;
5389              this.transformer = transformer;
5390              this.reducer = reducer;
5391          }
5392          public final U getRawResult() { return result; }
5393 <        @SuppressWarnings("unchecked") public final void compute() {
5393 >        public final void compute() {
5394              final BiFun<? super K, ? super V, ? extends U> transformer;
5395              final BiFun<? super U, ? super U, ? extends U> reducer;
5396              if ((transformer = this.transformer) != null &&
5397                  (reducer = this.reducer) != null) {
5398 <                for (int b; (b = preSplit()) > 0;)
5398 >                for (int i = baseIndex, f, h; batch > 0 &&
5399 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5400 >                    addToPendingCount(1);
5401                      (rights = new MapReduceMappingsTask<K,V,U>
5402 <                     (map, this, b, rights, transformer, reducer)).fork();
5403 <                U r = null, u;
5404 <                V v;
5405 <                while ((v = advance()) != null) {
5406 <                    if ((u = transformer.apply((K)nextKey, v)) != null)
5402 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5403 >                      rights, transformer, reducer)).fork();
5404 >                }
5405 >                U r = null;
5406 >                for (Node<K,V> p; (p = advance()) != null; ) {
5407 >                    U u;
5408 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5409                          r = (r == null) ? u : reducer.apply(r, u);
5410                  }
5411                  result = r;
5412                  CountedCompleter<?> c;
5413                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5414 <                    MapReduceMappingsTask<K,V,U>
5414 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5415                          t = (MapReduceMappingsTask<K,V,U>)c,
5416                          s = t.rights;
5417                      while (s != null) {
# Line 6249 | Line 5426 | public class ConcurrentHashMapV8<K, V>
5426          }
5427      }
5428  
5429 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5430 <        extends Traverser<K,V,Double> {
5429 >    @SuppressWarnings("serial")
5430 >    static final class MapReduceKeysToDoubleTask<K,V>
5431 >        extends BulkTask<K,V,Double> {
5432          final ObjectToDouble<? super K> transformer;
5433          final DoubleByDoubleToDouble reducer;
5434          final double basis;
5435          double result;
5436          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5437          MapReduceKeysToDoubleTask
5438 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5438 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5439               MapReduceKeysToDoubleTask<K,V> nextRight,
5440               ObjectToDouble<? super K> transformer,
5441               double basis,
5442               DoubleByDoubleToDouble reducer) {
5443 <            super(m, p, b); this.nextRight = nextRight;
5443 >            super(p, b, i, f, t); this.nextRight = nextRight;
5444              this.transformer = transformer;
5445              this.basis = basis; this.reducer = reducer;
5446          }
5447          public final Double getRawResult() { return result; }
5448 <        @SuppressWarnings("unchecked") public final void compute() {
5448 >        public final void compute() {
5449              final ObjectToDouble<? super K> transformer;
5450              final DoubleByDoubleToDouble reducer;
5451              if ((transformer = this.transformer) != null &&
5452                  (reducer = this.reducer) != null) {
5453                  double r = this.basis;
5454 <                for (int b; (b = preSplit()) > 0;)
5454 >                for (int i = baseIndex, f, h; batch > 0 &&
5455 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5456 >                    addToPendingCount(1);
5457                      (rights = new MapReduceKeysToDoubleTask<K,V>
5458 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5459 <                while (advance() != null)
5460 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5458 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5459 >                      rights, transformer, r, reducer)).fork();
5460 >                }
5461 >                for (Node<K,V> p; (p = advance()) != null; )
5462 >                    r = reducer.apply(r, transformer.apply(p.key));
5463                  result = r;
5464                  CountedCompleter<?> c;
5465                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5466 <                    MapReduceKeysToDoubleTask<K,V>
5466 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5467                          t = (MapReduceKeysToDoubleTask<K,V>)c,
5468                          s = t.rights;
5469                      while (s != null) {
# Line 6293 | Line 5475 | public class ConcurrentHashMapV8<K, V>
5475          }
5476      }
5477  
5478 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5479 <        extends Traverser<K,V,Double> {
5478 >    @SuppressWarnings("serial")
5479 >    static final class MapReduceValuesToDoubleTask<K,V>
5480 >        extends BulkTask<K,V,Double> {
5481          final ObjectToDouble<? super V> transformer;
5482          final DoubleByDoubleToDouble reducer;
5483          final double basis;
5484          double result;
5485          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5486          MapReduceValuesToDoubleTask
5487 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5487 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5488               MapReduceValuesToDoubleTask<K,V> nextRight,
5489               ObjectToDouble<? super V> transformer,
5490               double basis,
5491               DoubleByDoubleToDouble reducer) {
5492 <            super(m, p, b); this.nextRight = nextRight;
5492 >            super(p, b, i, f, t); this.nextRight = nextRight;
5493              this.transformer = transformer;
5494              this.basis = basis; this.reducer = reducer;
5495          }
5496          public final Double getRawResult() { return result; }
5497 <        @SuppressWarnings("unchecked") public final void compute() {
5497 >        public final void compute() {
5498              final ObjectToDouble<? super V> transformer;
5499              final DoubleByDoubleToDouble reducer;
5500              if ((transformer = this.transformer) != null &&
5501                  (reducer = this.reducer) != null) {
5502                  double r = this.basis;
5503 <                for (int b; (b = preSplit()) > 0;)
5503 >                for (int i = baseIndex, f, h; batch > 0 &&
5504 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5505 >                    addToPendingCount(1);
5506                      (rights = new MapReduceValuesToDoubleTask<K,V>
5507 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5508 <                V v;
5509 <                while ((v = advance()) != null)
5510 <                    r = reducer.apply(r, transformer.apply(v));
5507 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5508 >                      rights, transformer, r, reducer)).fork();
5509 >                }
5510 >                for (Node<K,V> p; (p = advance()) != null; )
5511 >                    r = reducer.apply(r, transformer.apply(p.val));
5512                  result = r;
5513                  CountedCompleter<?> c;
5514                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5515 <                    MapReduceValuesToDoubleTask<K,V>
5515 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5516                          t = (MapReduceValuesToDoubleTask<K,V>)c,
5517                          s = t.rights;
5518                      while (s != null) {
# Line 6338 | Line 5524 | public class ConcurrentHashMapV8<K, V>
5524          }
5525      }
5526  
5527 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5528 <        extends Traverser<K,V,Double> {
5527 >    @SuppressWarnings("serial")
5528 >    static final class MapReduceEntriesToDoubleTask<K,V>
5529 >        extends BulkTask<K,V,Double> {
5530          final ObjectToDouble<Map.Entry<K,V>> transformer;
5531          final DoubleByDoubleToDouble reducer;
5532          final double basis;
5533          double result;
5534          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5535          MapReduceEntriesToDoubleTask
5536 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5536 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5537               MapReduceEntriesToDoubleTask<K,V> nextRight,
5538               ObjectToDouble<Map.Entry<K,V>> transformer,
5539               double basis,
5540               DoubleByDoubleToDouble reducer) {
5541 <            super(m, p, b); this.nextRight = nextRight;
5541 >            super(p, b, i, f, t); this.nextRight = nextRight;
5542              this.transformer = transformer;
5543              this.basis = basis; this.reducer = reducer;
5544          }
5545          public final Double getRawResult() { return result; }
5546 <        @SuppressWarnings("unchecked") public final void compute() {
5546 >        public final void compute() {
5547              final ObjectToDouble<Map.Entry<K,V>> transformer;
5548              final DoubleByDoubleToDouble reducer;
5549              if ((transformer = this.transformer) != null &&
5550                  (reducer = this.reducer) != null) {
5551                  double r = this.basis;
5552 <                for (int b; (b = preSplit()) > 0;)
5552 >                for (int i = baseIndex, f, h; batch > 0 &&
5553 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5554 >                    addToPendingCount(1);
5555                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5556 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5557 <                V v;
5558 <                while ((v = advance()) != null)
5559 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5560 <                                                                    v)));
5556 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5557 >                      rights, transformer, r, reducer)).fork();
5558 >                }
5559 >                for (Node<K,V> p; (p = advance()) != null; )
5560 >                    r = reducer.apply(r, transformer.apply(p));
5561                  result = r;
5562                  CountedCompleter<?> c;
5563                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5564 <                    MapReduceEntriesToDoubleTask<K,V>
5564 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5565                          t = (MapReduceEntriesToDoubleTask<K,V>)c,
5566                          s = t.rights;
5567                      while (s != null) {
# Line 6384 | Line 5573 | public class ConcurrentHashMapV8<K, V>
5573          }
5574      }
5575  
5576 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5577 <        extends Traverser<K,V,Double> {
5576 >    @SuppressWarnings("serial")
5577 >    static final class MapReduceMappingsToDoubleTask<K,V>
5578 >        extends BulkTask<K,V,Double> {
5579          final ObjectByObjectToDouble<? super K, ? super V> transformer;
5580          final DoubleByDoubleToDouble reducer;
5581          final double basis;
5582          double result;
5583          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5584          MapReduceMappingsToDoubleTask
5585 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5585 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5586               MapReduceMappingsToDoubleTask<K,V> nextRight,
5587               ObjectByObjectToDouble<? super K, ? super V> transformer,
5588               double basis,
5589               DoubleByDoubleToDouble reducer) {
5590 <            super(m, p, b); this.nextRight = nextRight;
5590 >            super(p, b, i, f, t); this.nextRight = nextRight;
5591              this.transformer = transformer;
5592              this.basis = basis; this.reducer = reducer;
5593          }
5594          public final Double getRawResult() { return result; }
5595 <        @SuppressWarnings("unchecked") public final void compute() {
5595 >        public final void compute() {
5596              final ObjectByObjectToDouble<? super K, ? super V> transformer;
5597              final DoubleByDoubleToDouble reducer;
5598              if ((transformer = this.transformer) != null &&
5599                  (reducer = this.reducer) != null) {
5600                  double r = this.basis;
5601 <                for (int b; (b = preSplit()) > 0;)
5601 >                for (int i = baseIndex, f, h; batch > 0 &&
5602 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5603 >                    addToPendingCount(1);
5604                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5605 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5606 <                V v;
5607 <                while ((v = advance()) != null)
5608 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5605 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5606 >                      rights, transformer, r, reducer)).fork();
5607 >                }
5608 >                for (Node<K,V> p; (p = advance()) != null; )
5609 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5610                  result = r;
5611                  CountedCompleter<?> c;
5612                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5613 <                    MapReduceMappingsToDoubleTask<K,V>
5613 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5614                          t = (MapReduceMappingsToDoubleTask<K,V>)c,
5615                          s = t.rights;
5616                      while (s != null) {
# Line 6429 | Line 5622 | public class ConcurrentHashMapV8<K, V>
5622          }
5623      }
5624  
5625 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5626 <        extends Traverser<K,V,Long> {
5625 >    @SuppressWarnings("serial")
5626 >    static final class MapReduceKeysToLongTask<K,V>
5627 >        extends BulkTask<K,V,Long> {
5628          final ObjectToLong<? super K> transformer;
5629          final LongByLongToLong reducer;
5630          final long basis;
5631          long result;
5632          MapReduceKeysToLongTask<K,V> rights, nextRight;
5633          MapReduceKeysToLongTask
5634 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5634 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5635               MapReduceKeysToLongTask<K,V> nextRight,
5636               ObjectToLong<? super K> transformer,
5637               long basis,
5638               LongByLongToLong reducer) {
5639 <            super(m, p, b); this.nextRight = nextRight;
5639 >            super(p, b, i, f, t); this.nextRight = nextRight;
5640              this.transformer = transformer;
5641              this.basis = basis; this.reducer = reducer;
5642          }
5643          public final Long getRawResult() { return result; }
5644 <        @SuppressWarnings("unchecked") public final void compute() {
5644 >        public final void compute() {
5645              final ObjectToLong<? super K> transformer;
5646              final LongByLongToLong reducer;
5647              if ((transformer = this.transformer) != null &&
5648                  (reducer = this.reducer) != null) {
5649                  long r = this.basis;
5650 <                for (int b; (b = preSplit()) > 0;)
5650 >                for (int i = baseIndex, f, h; batch > 0 &&
5651 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5652 >                    addToPendingCount(1);
5653                      (rights = new MapReduceKeysToLongTask<K,V>
5654 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5655 <                while (advance() != null)
5656 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5654 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5655 >                      rights, transformer, r, reducer)).fork();
5656 >                }
5657 >                for (Node<K,V> p; (p = advance()) != null; )
5658 >                    r = reducer.apply(r, transformer.apply(p.key));
5659                  result = r;
5660                  CountedCompleter<?> c;
5661                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5662 <                    MapReduceKeysToLongTask<K,V>
5662 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5663                          t = (MapReduceKeysToLongTask<K,V>)c,
5664                          s = t.rights;
5665                      while (s != null) {
# Line 6473 | Line 5671 | public class ConcurrentHashMapV8<K, V>
5671          }
5672      }
5673  
5674 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5675 <        extends Traverser<K,V,Long> {
5674 >    @SuppressWarnings("serial")
5675 >    static final class MapReduceValuesToLongTask<K,V>
5676 >        extends BulkTask<K,V,Long> {
5677          final ObjectToLong<? super V> transformer;
5678          final LongByLongToLong reducer;
5679          final long basis;
5680          long result;
5681          MapReduceValuesToLongTask<K,V> rights, nextRight;
5682          MapReduceValuesToLongTask
5683 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5683 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5684               MapReduceValuesToLongTask<K,V> nextRight,
5685               ObjectToLong<? super V> transformer,
5686               long basis,
5687               LongByLongToLong reducer) {
5688 <            super(m, p, b); this.nextRight = nextRight;
5688 >            super(p, b, i, f, t); this.nextRight = nextRight;
5689              this.transformer = transformer;
5690              this.basis = basis; this.reducer = reducer;
5691          }
5692          public final Long getRawResult() { return result; }
5693 <        @SuppressWarnings("unchecked") public final void compute() {
5693 >        public final void compute() {
5694              final ObjectToLong<? super V> transformer;
5695              final LongByLongToLong reducer;
5696              if ((transformer = this.transformer) != null &&
5697                  (reducer = this.reducer) != null) {
5698                  long r = this.basis;
5699 <                for (int b; (b = preSplit()) > 0;)
5699 >                for (int i = baseIndex, f, h; batch > 0 &&
5700 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5701 >                    addToPendingCount(1);
5702                      (rights = new MapReduceValuesToLongTask<K,V>
5703 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5704 <                V v;
5705 <                while ((v = advance()) != null)
5706 <                    r = reducer.apply(r, transformer.apply(v));
5703 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5704 >                      rights, transformer, r, reducer)).fork();
5705 >                }
5706 >                for (Node<K,V> p; (p = advance()) != null; )
5707 >                    r = reducer.apply(r, transformer.apply(p.val));
5708                  result = r;
5709                  CountedCompleter<?> c;
5710                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5711 <                    MapReduceValuesToLongTask<K,V>
5711 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5712                          t = (MapReduceValuesToLongTask<K,V>)c,
5713                          s = t.rights;
5714                      while (s != null) {
# Line 6518 | Line 5720 | public class ConcurrentHashMapV8<K, V>
5720          }
5721      }
5722  
5723 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5724 <        extends Traverser<K,V,Long> {
5723 >    @SuppressWarnings("serial")
5724 >    static final class MapReduceEntriesToLongTask<K,V>
5725 >        extends BulkTask<K,V,Long> {
5726          final ObjectToLong<Map.Entry<K,V>> transformer;
5727          final LongByLongToLong reducer;
5728          final long basis;
5729          long result;
5730          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5731          MapReduceEntriesToLongTask
5732 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5732 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5733               MapReduceEntriesToLongTask<K,V> nextRight,
5734               ObjectToLong<Map.Entry<K,V>> transformer,
5735               long basis,
5736               LongByLongToLong reducer) {
5737 <            super(m, p, b); this.nextRight = nextRight;
5737 >            super(p, b, i, f, t); this.nextRight = nextRight;
5738              this.transformer = transformer;
5739              this.basis = basis; this.reducer = reducer;
5740          }
5741          public final Long getRawResult() { return result; }
5742 <        @SuppressWarnings("unchecked") public final void compute() {
5742 >        public final void compute() {
5743              final ObjectToLong<Map.Entry<K,V>> transformer;
5744              final LongByLongToLong reducer;
5745              if ((transformer = this.transformer) != null &&
5746                  (reducer = this.reducer) != null) {
5747                  long r = this.basis;
5748 <                for (int b; (b = preSplit()) > 0;)
5748 >                for (int i = baseIndex, f, h; batch > 0 &&
5749 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5750 >                    addToPendingCount(1);
5751                      (rights = new MapReduceEntriesToLongTask<K,V>
5752 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5753 <                V v;
5754 <                while ((v = advance()) != null)
5755 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5756 <                                                                    v)));
5752 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5753 >                      rights, transformer, r, reducer)).fork();
5754 >                }
5755 >                for (Node<K,V> p; (p = advance()) != null; )
5756 >                    r = reducer.apply(r, transformer.apply(p));
5757                  result = r;
5758                  CountedCompleter<?> c;
5759                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5760 <                    MapReduceEntriesToLongTask<K,V>
5760 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5761                          t = (MapReduceEntriesToLongTask<K,V>)c,
5762                          s = t.rights;
5763                      while (s != null) {
# Line 6564 | Line 5769 | public class ConcurrentHashMapV8<K, V>
5769          }
5770      }
5771  
5772 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
5773 <        extends Traverser<K,V,Long> {
5772 >    @SuppressWarnings("serial")
5773 >    static final class MapReduceMappingsToLongTask<K,V>
5774 >        extends BulkTask<K,V,Long> {
5775          final ObjectByObjectToLong<? super K, ? super V> transformer;
5776          final LongByLongToLong reducer;
5777          final long basis;
5778          long result;
5779          MapReduceMappingsToLongTask<K,V> rights, nextRight;
5780          MapReduceMappingsToLongTask
5781 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5781 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5782               MapReduceMappingsToLongTask<K,V> nextRight,
5783               ObjectByObjectToLong<? super K, ? super V> transformer,
5784               long basis,
5785               LongByLongToLong reducer) {
5786 <            super(m, p, b); this.nextRight = nextRight;
5786 >            super(p, b, i, f, t); this.nextRight = nextRight;
5787              this.transformer = transformer;
5788              this.basis = basis; this.reducer = reducer;
5789          }
5790          public final Long getRawResult() { return result; }
5791 <        @SuppressWarnings("unchecked") public final void compute() {
5791 >        public final void compute() {
5792              final ObjectByObjectToLong<? super K, ? super V> transformer;
5793              final LongByLongToLong reducer;
5794              if ((transformer = this.transformer) != null &&
5795                  (reducer = this.reducer) != null) {
5796                  long r = this.basis;
5797 <                for (int b; (b = preSplit()) > 0;)
5797 >                for (int i = baseIndex, f, h; batch > 0 &&
5798 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5799 >                    addToPendingCount(1);
5800                      (rights = new MapReduceMappingsToLongTask<K,V>
5801 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5802 <                V v;
5803 <                while ((v = advance()) != null)
5804 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5801 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5802 >                      rights, transformer, r, reducer)).fork();
5803 >                }
5804 >                for (Node<K,V> p; (p = advance()) != null; )
5805 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5806                  result = r;
5807                  CountedCompleter<?> c;
5808                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5809 <                    MapReduceMappingsToLongTask<K,V>
5809 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5810                          t = (MapReduceMappingsToLongTask<K,V>)c,
5811                          s = t.rights;
5812                      while (s != null) {
# Line 6609 | Line 5818 | public class ConcurrentHashMapV8<K, V>
5818          }
5819      }
5820  
5821 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
5822 <        extends Traverser<K,V,Integer> {
5821 >    @SuppressWarnings("serial")
5822 >    static final class MapReduceKeysToIntTask<K,V>
5823 >        extends BulkTask<K,V,Integer> {
5824          final ObjectToInt<? super K> transformer;
5825          final IntByIntToInt reducer;
5826          final int basis;
5827          int result;
5828          MapReduceKeysToIntTask<K,V> rights, nextRight;
5829          MapReduceKeysToIntTask
5830 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5830 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5831               MapReduceKeysToIntTask<K,V> nextRight,
5832               ObjectToInt<? super K> transformer,
5833               int basis,
5834               IntByIntToInt reducer) {
5835 <            super(m, p, b); this.nextRight = nextRight;
5835 >            super(p, b, i, f, t); this.nextRight = nextRight;
5836              this.transformer = transformer;
5837              this.basis = basis; this.reducer = reducer;
5838          }
5839          public final Integer getRawResult() { return result; }
5840 <        @SuppressWarnings("unchecked") public final void compute() {
5840 >        public final void compute() {
5841              final ObjectToInt<? super K> transformer;
5842              final IntByIntToInt reducer;
5843              if ((transformer = this.transformer) != null &&
5844                  (reducer = this.reducer) != null) {
5845                  int r = this.basis;
5846 <                for (int b; (b = preSplit()) > 0;)
5846 >                for (int i = baseIndex, f, h; batch > 0 &&
5847 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5848 >                    addToPendingCount(1);
5849                      (rights = new MapReduceKeysToIntTask<K,V>
5850 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5851 <                while (advance() != null)
5852 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5850 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5851 >                      rights, transformer, r, reducer)).fork();
5852 >                }
5853 >                for (Node<K,V> p; (p = advance()) != null; )
5854 >                    r = reducer.apply(r, transformer.apply(p.key));
5855                  result = r;
5856                  CountedCompleter<?> c;
5857                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5858 <                    MapReduceKeysToIntTask<K,V>
5858 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5859                          t = (MapReduceKeysToIntTask<K,V>)c,
5860                          s = t.rights;
5861                      while (s != null) {
# Line 6653 | Line 5867 | public class ConcurrentHashMapV8<K, V>
5867          }
5868      }
5869  
5870 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
5871 <        extends Traverser<K,V,Integer> {
5870 >    @SuppressWarnings("serial")
5871 >    static final class MapReduceValuesToIntTask<K,V>
5872 >        extends BulkTask<K,V,Integer> {
5873          final ObjectToInt<? super V> transformer;
5874          final IntByIntToInt reducer;
5875          final int basis;
5876          int result;
5877          MapReduceValuesToIntTask<K,V> rights, nextRight;
5878          MapReduceValuesToIntTask
5879 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5879 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5880               MapReduceValuesToIntTask<K,V> nextRight,
5881               ObjectToInt<? super V> transformer,
5882               int basis,
5883               IntByIntToInt reducer) {
5884 <            super(m, p, b); this.nextRight = nextRight;
5884 >            super(p, b, i, f, t); this.nextRight = nextRight;
5885              this.transformer = transformer;
5886              this.basis = basis; this.reducer = reducer;
5887          }
5888          public final Integer getRawResult() { return result; }
5889 <        @SuppressWarnings("unchecked") public final void compute() {
5889 >        public final void compute() {
5890              final ObjectToInt<? super V> transformer;
5891              final IntByIntToInt reducer;
5892              if ((transformer = this.transformer) != null &&
5893                  (reducer = this.reducer) != null) {
5894                  int r = this.basis;
5895 <                for (int b; (b = preSplit()) > 0;)
5895 >                for (int i = baseIndex, f, h; batch > 0 &&
5896 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5897 >                    addToPendingCount(1);
5898                      (rights = new MapReduceValuesToIntTask<K,V>
5899 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5900 <                V v;
5901 <                while ((v = advance()) != null)
5902 <                    r = reducer.apply(r, transformer.apply(v));
5899 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5900 >                      rights, transformer, r, reducer)).fork();
5901 >                }
5902 >                for (Node<K,V> p; (p = advance()) != null; )
5903 >                    r = reducer.apply(r, transformer.apply(p.val));
5904                  result = r;
5905                  CountedCompleter<?> c;
5906                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5907 <                    MapReduceValuesToIntTask<K,V>
5907 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5908                          t = (MapReduceValuesToIntTask<K,V>)c,
5909                          s = t.rights;
5910                      while (s != null) {
# Line 6698 | Line 5916 | public class ConcurrentHashMapV8<K, V>
5916          }
5917      }
5918  
5919 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
5920 <        extends Traverser<K,V,Integer> {
5919 >    @SuppressWarnings("serial")
5920 >    static final class MapReduceEntriesToIntTask<K,V>
5921 >        extends BulkTask<K,V,Integer> {
5922          final ObjectToInt<Map.Entry<K,V>> transformer;
5923          final IntByIntToInt reducer;
5924          final int basis;
5925          int result;
5926          MapReduceEntriesToIntTask<K,V> rights, nextRight;
5927          MapReduceEntriesToIntTask
5928 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5928 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5929               MapReduceEntriesToIntTask<K,V> nextRight,
5930               ObjectToInt<Map.Entry<K,V>> transformer,
5931               int basis,
5932               IntByIntToInt reducer) {
5933 <            super(m, p, b); this.nextRight = nextRight;
5933 >            super(p, b, i, f, t); this.nextRight = nextRight;
5934              this.transformer = transformer;
5935              this.basis = basis; this.reducer = reducer;
5936          }
5937          public final Integer getRawResult() { return result; }
5938 <        @SuppressWarnings("unchecked") public final void compute() {
5938 >        public final void compute() {
5939              final ObjectToInt<Map.Entry<K,V>> transformer;
5940              final IntByIntToInt reducer;
5941              if ((transformer = this.transformer) != null &&
5942                  (reducer = this.reducer) != null) {
5943                  int r = this.basis;
5944 <                for (int b; (b = preSplit()) > 0;)
5944 >                for (int i = baseIndex, f, h; batch > 0 &&
5945 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5946 >                    addToPendingCount(1);
5947                      (rights = new MapReduceEntriesToIntTask<K,V>
5948 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5949 <                V v;
5950 <                while ((v = advance()) != null)
5951 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5952 <                                                                    v)));
5948 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5949 >                      rights, transformer, r, reducer)).fork();
5950 >                }
5951 >                for (Node<K,V> p; (p = advance()) != null; )
5952 >                    r = reducer.apply(r, transformer.apply(p));
5953                  result = r;
5954                  CountedCompleter<?> c;
5955                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5956 <                    MapReduceEntriesToIntTask<K,V>
5956 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5957                          t = (MapReduceEntriesToIntTask<K,V>)c,
5958                          s = t.rights;
5959                      while (s != null) {
# Line 6744 | Line 5965 | public class ConcurrentHashMapV8<K, V>
5965          }
5966      }
5967  
5968 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
5969 <        extends Traverser<K,V,Integer> {
5968 >    @SuppressWarnings("serial")
5969 >    static final class MapReduceMappingsToIntTask<K,V>
5970 >        extends BulkTask<K,V,Integer> {
5971          final ObjectByObjectToInt<? super K, ? super V> transformer;
5972          final IntByIntToInt reducer;
5973          final int basis;
5974          int result;
5975          MapReduceMappingsToIntTask<K,V> rights, nextRight;
5976          MapReduceMappingsToIntTask
5977 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5977 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5978               MapReduceMappingsToIntTask<K,V> nextRight,
5979               ObjectByObjectToInt<? super K, ? super V> transformer,
5980               int basis,
5981               IntByIntToInt reducer) {
5982 <            super(m, p, b); this.nextRight = nextRight;
5982 >            super(p, b, i, f, t); this.nextRight = nextRight;
5983              this.transformer = transformer;
5984              this.basis = basis; this.reducer = reducer;
5985          }
5986          public final Integer getRawResult() { return result; }
5987 <        @SuppressWarnings("unchecked") public final void compute() {
5987 >        public final void compute() {
5988              final ObjectByObjectToInt<? super K, ? super V> transformer;
5989              final IntByIntToInt reducer;
5990              if ((transformer = this.transformer) != null &&
5991                  (reducer = this.reducer) != null) {
5992                  int r = this.basis;
5993 <                for (int b; (b = preSplit()) > 0;)
5993 >                for (int i = baseIndex, f, h; batch > 0 &&
5994 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5995 >                    addToPendingCount(1);
5996                      (rights = new MapReduceMappingsToIntTask<K,V>
5997 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5998 <                V v;
5999 <                while ((v = advance()) != null)
6000 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5997 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5998 >                      rights, transformer, r, reducer)).fork();
5999 >                }
6000 >                for (Node<K,V> p; (p = advance()) != null; )
6001 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
6002                  result = r;
6003                  CountedCompleter<?> c;
6004                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6005 <                    MapReduceMappingsToIntTask<K,V>
6005 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
6006                          t = (MapReduceMappingsToIntTask<K,V>)c,
6007                          s = t.rights;
6008                      while (s != null) {
# Line 6789 | Line 6014 | public class ConcurrentHashMapV8<K, V>
6014          }
6015      }
6016  
6017 +    /* ---------------- Counters -------------- */
6018 +
6019 +    // Adapted from LongAdder and Striped64.
6020 +    // See their internal docs for explanation.
6021 +
6022 +    // A padded cell for distributing counts
6023 +    static final class CounterCell {
6024 +        volatile long p0, p1, p2, p3, p4, p5, p6;
6025 +        volatile long value;
6026 +        volatile long q0, q1, q2, q3, q4, q5, q6;
6027 +        CounterCell(long x) { value = x; }
6028 +    }
6029 +
6030 +    /**
6031 +     * Holder for the thread-local hash code determining which
6032 +     * CounterCell to use. The code is initialized via the
6033 +     * counterHashCodeGenerator, but may be moved upon collisions.
6034 +     */
6035 +    static final class CounterHashCode {
6036 +        int code;
6037 +    }
6038 +
6039 +    /**
6040 +     * Generates initial value for per-thread CounterHashCodes.
6041 +     */
6042 +    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
6043 +
6044 +    /**
6045 +     * Increment for counterHashCodeGenerator. See class ThreadLocal
6046 +     * for explanation.
6047 +     */
6048 +    static final int SEED_INCREMENT = 0x61c88647;
6049 +
6050 +    /**
6051 +     * Per-thread counter hash codes. Shared across all instances.
6052 +     */
6053 +    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
6054 +        new ThreadLocal<CounterHashCode>();
6055 +
6056 +
6057 +    final long sumCount() {
6058 +        CounterCell[] as = counterCells; CounterCell a;
6059 +        long sum = baseCount;
6060 +        if (as != null) {
6061 +            for (int i = 0; i < as.length; ++i) {
6062 +                if ((a = as[i]) != null)
6063 +                    sum += a.value;
6064 +            }
6065 +        }
6066 +        return sum;
6067 +    }
6068 +
6069 +    // See LongAdder version for explanation
6070 +    private final void fullAddCount(long x, CounterHashCode hc,
6071 +                                    boolean wasUncontended) {
6072 +        int h;
6073 +        if (hc == null) {
6074 +            hc = new CounterHashCode();
6075 +            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
6076 +            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
6077 +            threadCounterHashCode.set(hc);
6078 +        }
6079 +        else
6080 +            h = hc.code;
6081 +        boolean collide = false;                // True if last slot nonempty
6082 +        for (;;) {
6083 +            CounterCell[] as; CounterCell a; int n; long v;
6084 +            if ((as = counterCells) != null && (n = as.length) > 0) {
6085 +                if ((a = as[(n - 1) & h]) == null) {
6086 +                    if (cellsBusy == 0) {            // Try to attach new Cell
6087 +                        CounterCell r = new CounterCell(x); // Optimistic create
6088 +                        if (cellsBusy == 0 &&
6089 +                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6090 +                            boolean created = false;
6091 +                            try {               // Recheck under lock
6092 +                                CounterCell[] rs; int m, j;
6093 +                                if ((rs = counterCells) != null &&
6094 +                                    (m = rs.length) > 0 &&
6095 +                                    rs[j = (m - 1) & h] == null) {
6096 +                                    rs[j] = r;
6097 +                                    created = true;
6098 +                                }
6099 +                            } finally {
6100 +                                cellsBusy = 0;
6101 +                            }
6102 +                            if (created)
6103 +                                break;
6104 +                            continue;           // Slot is now non-empty
6105 +                        }
6106 +                    }
6107 +                    collide = false;
6108 +                }
6109 +                else if (!wasUncontended)       // CAS already known to fail
6110 +                    wasUncontended = true;      // Continue after rehash
6111 +                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
6112 +                    break;
6113 +                else if (counterCells != as || n >= NCPU)
6114 +                    collide = false;            // At max size or stale
6115 +                else if (!collide)
6116 +                    collide = true;
6117 +                else if (cellsBusy == 0 &&
6118 +                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6119 +                    try {
6120 +                        if (counterCells == as) {// Expand table unless stale
6121 +                            CounterCell[] rs = new CounterCell[n << 1];
6122 +                            for (int i = 0; i < n; ++i)
6123 +                                rs[i] = as[i];
6124 +                            counterCells = rs;
6125 +                        }
6126 +                    } finally {
6127 +                        cellsBusy = 0;
6128 +                    }
6129 +                    collide = false;
6130 +                    continue;                   // Retry with expanded table
6131 +                }
6132 +                h ^= h << 13;                   // Rehash
6133 +                h ^= h >>> 17;
6134 +                h ^= h << 5;
6135 +            }
6136 +            else if (cellsBusy == 0 && counterCells == as &&
6137 +                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6138 +                boolean init = false;
6139 +                try {                           // Initialize table
6140 +                    if (counterCells == as) {
6141 +                        CounterCell[] rs = new CounterCell[2];
6142 +                        rs[h & 1] = new CounterCell(x);
6143 +                        counterCells = rs;
6144 +                        init = true;
6145 +                    }
6146 +                } finally {
6147 +                    cellsBusy = 0;
6148 +                }
6149 +                if (init)
6150 +                    break;
6151 +            }
6152 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
6153 +                break;                          // Fall back on using base
6154 +        }
6155 +        hc.code = h;                            // Record index for next time
6156 +    }
6157 +
6158      // Unsafe mechanics
6159      private static final sun.misc.Unsafe U;
6160      private static final long SIZECTL;
6161      private static final long TRANSFERINDEX;
6162      private static final long TRANSFERORIGIN;
6163      private static final long BASECOUNT;
6164 <    private static final long COUNTERBUSY;
6164 >    private static final long CELLSBUSY;
6165      private static final long CELLVALUE;
6166      private static final long ABASE;
6167      private static final int ASHIFT;
# Line 6812 | Line 6178 | public class ConcurrentHashMapV8<K, V>
6178                  (k.getDeclaredField("transferOrigin"));
6179              BASECOUNT = U.objectFieldOffset
6180                  (k.getDeclaredField("baseCount"));
6181 <            COUNTERBUSY = U.objectFieldOffset
6182 <                (k.getDeclaredField("counterBusy"));
6181 >            CELLSBUSY = U.objectFieldOffset
6182 >                (k.getDeclaredField("cellsBusy"));
6183              Class<?> ck = CounterCell.class;
6184              CELLVALUE = U.objectFieldOffset
6185                  (ck.getDeclaredField("value"));
6186 <            Class<?> sc = Node[].class;
6187 <            ABASE = U.arrayBaseOffset(sc);
6188 <            int scale = U.arrayIndexScale(sc);
6186 >            Class<?> ak = Node[].class;
6187 >            ABASE = U.arrayBaseOffset(ak);
6188 >            int scale = U.arrayIndexScale(ak);
6189              if ((scale & (scale - 1)) != 0)
6190                  throw new Error("data type scale not a power of two");
6191              ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines