ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
(Generate patch)

Comparing jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java (file contents):
Revision 1.176 by jsr166, Mon Feb 11 08:45:31 2013 UTC vs.
Revision 1.252 by dl, Sun Dec 1 13:38:58 2013 UTC

# Line 5 | Line 5
5   */
6  
7   package java.util.concurrent;
8 import java.util.concurrent.ForkJoinPool;
9 import java.util.concurrent.CountedCompleter;
10 import java.util.function.*;
11 import java.util.Spliterator;
12 import java.util.stream.Stream;
13 import java.util.stream.Streams;
8  
9 < import java.util.Comparator;
9 > import java.io.ObjectStreamField;
10 > import java.io.Serializable;
11 > import java.lang.reflect.ParameterizedType;
12 > import java.lang.reflect.Type;
13 > import java.util.AbstractMap;
14   import java.util.Arrays;
17 import java.util.Map;
18 import java.util.Set;
15   import java.util.Collection;
16 < import java.util.AbstractMap;
17 < import java.util.AbstractSet;
22 < import java.util.AbstractCollection;
23 < import java.util.Hashtable;
16 > import java.util.Comparator;
17 > import java.util.Enumeration;
18   import java.util.HashMap;
19 + import java.util.Hashtable;
20   import java.util.Iterator;
21 < import java.util.Enumeration;
27 < import java.util.ConcurrentModificationException;
21 > import java.util.Map;
22   import java.util.NoSuchElementException;
23 + import java.util.Set;
24 + import java.util.Spliterator;
25   import java.util.concurrent.ConcurrentMap;
26 < import java.util.concurrent.locks.AbstractQueuedSynchronizer;
31 < import java.util.concurrent.atomic.AtomicInteger;
26 > import java.util.concurrent.ForkJoinPool;
27   import java.util.concurrent.atomic.AtomicReference;
28 < import java.io.Serializable;
28 > import java.util.concurrent.locks.LockSupport;
29 > import java.util.concurrent.locks.ReentrantLock;
30 > import java.util.function.BiConsumer;
31 > import java.util.function.BiFunction;
32 > import java.util.function.BinaryOperator;
33 > import java.util.function.Consumer;
34 > import java.util.function.DoubleBinaryOperator;
35 > import java.util.function.Function;
36 > import java.util.function.IntBinaryOperator;
37 > import java.util.function.LongBinaryOperator;
38 > import java.util.function.ToDoubleBiFunction;
39 > import java.util.function.ToDoubleFunction;
40 > import java.util.function.ToIntBiFunction;
41 > import java.util.function.ToIntFunction;
42 > import java.util.function.ToLongBiFunction;
43 > import java.util.function.ToLongFunction;
44 > import java.util.stream.Stream;
45  
46   /**
47   * A hash table supporting full concurrency of retrievals and
# Line 53 | Line 64 | import java.io.Serializable;
64   * that key reporting the updated value.)  For aggregate operations
65   * such as {@code putAll} and {@code clear}, concurrent retrievals may
66   * reflect insertion or removal of only some entries.  Similarly,
67 < * Iterators and Enumerations return elements reflecting the state of
68 < * the hash table at some point at or since the creation of the
67 > * Iterators, Spliterators and Enumerations return elements reflecting the
68 > * state of the hash table at some point at or since the creation of the
69   * iterator/enumeration.  They do <em>not</em> throw {@link
70 < * ConcurrentModificationException}.  However, iterators are designed
71 < * to be used by only one thread at a time.  Bear in mind that the
72 < * results of aggregate status methods including {@code size}, {@code
73 < * isEmpty}, and {@code containsValue} are typically useful only when
74 < * a map is not undergoing concurrent updates in other threads.
70 > * java.util.ConcurrentModificationException ConcurrentModificationException}.
71 > * However, iterators are designed to be used by only one thread at a time.
72 > * Bear in mind that the results of aggregate status methods including
73 > * {@code size}, {@code isEmpty}, and {@code containsValue} are typically
74 > * useful only when a map is not undergoing concurrent updates in other threads.
75   * Otherwise the results of these methods reflect transient states
76   * that may be adequate for monitoring or estimation purposes, but not
77   * for program control.
# Line 84 | Line 95 | import java.io.Serializable;
95   * expected {@code concurrencyLevel} as an additional hint for
96   * internal sizing.  Note that using many keys with exactly the same
97   * {@code hashCode()} is a sure way to slow down performance of any
98 < * hash table.
98 > * hash table. To ameliorate impact, when keys are {@link Comparable},
99 > * this class may use comparison order among keys to help break ties.
100   *
101   * <p>A {@link Set} projection of a ConcurrentHashMap may be created
102   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
# Line 106 | Line 118 | import java.io.Serializable;
118   * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
119   * does <em>not</em> allow {@code null} to be used as a key or value.
120   *
121 < * <p>ConcurrentHashMaps support sequential and parallel operations
122 < * bulk operations. (Parallel forms use the {@link
123 < * ForkJoinPool#commonPool()}). Tasks that may be used in other
124 < * contexts are available in class {@link ForkJoinTasks}. These
125 < * operations are designed to be safely, and often sensibly, applied
126 < * even with maps that are being concurrently updated by other
127 < * threads; for example, when computing a snapshot summary of the
128 < * values in a shared registry.  There are three kinds of operation,
129 < * each with four forms, accepting functions with Keys, Values,
130 < * Entries, and (Key, Value) arguments and/or return values. Because
131 < * the elements of a ConcurrentHashMap are not ordered in any
132 < * particular way, and may be processed in different orders in
133 < * different parallel executions, the correctness of supplied
134 < * functions should not depend on any ordering, or on any other
135 < * objects or values that may transiently change while computation is
124 < * in progress; and except for forEach actions, should ideally be
125 < * side-effect-free.
121 > * <p>ConcurrentHashMaps support a set of sequential and parallel bulk
122 > * operations that, unlike most {@link Stream} methods, are designed
123 > * to be safely, and often sensibly, applied even with maps that are
124 > * being concurrently updated by other threads; for example, when
125 > * computing a snapshot summary of the values in a shared registry.
126 > * There are three kinds of operation, each with four forms, accepting
127 > * functions with Keys, Values, Entries, and (Key, Value) arguments
128 > * and/or return values. Because the elements of a ConcurrentHashMap
129 > * are not ordered in any particular way, and may be processed in
130 > * different orders in different parallel executions, the correctness
131 > * of supplied functions should not depend on any ordering, or on any
132 > * other objects or values that may transiently change while
133 > * computation is in progress; and except for forEach actions, should
134 > * ideally be side-effect-free. Bulk operations on {@link java.util.Map.Entry}
135 > * objects do not support method {@code setValue}.
136   *
137   * <ul>
138   * <li> forEach: Perform a given action on each element.
# Line 149 | Line 159 | import java.io.Serializable;
159   * <li> Reductions to scalar doubles, longs, and ints, using a
160   * given basis value.</li>
161   *
152 * </li>
162   * </ul>
163 + * </li>
164   * </ul>
165   *
166 + * <p>These bulk operations accept a {@code parallelismThreshold}
167 + * argument. Methods proceed sequentially if the current map size is
168 + * estimated to be less than the given threshold. Using a value of
169 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
170 + * of {@code 1} results in maximal parallelism by partitioning into
171 + * enough subtasks to fully utilize the {@link
172 + * ForkJoinPool#commonPool()} that is used for all parallel
173 + * computations. Normally, you would initially choose one of these
174 + * extreme values, and then measure performance of using in-between
175 + * values that trade off overhead versus throughput.
176 + *
177   * <p>The concurrency properties of bulk operations follow
178   * from those of ConcurrentHashMap: Any non-null result returned
179   * from {@code get(key)} and related access methods bears a
# Line 214 | Line 235 | import java.io.Serializable;
235   * @param <K> the type of keys maintained by this map
236   * @param <V> the type of mapped values
237   */
238 < public class ConcurrentHashMap<K, V>
239 <    implements ConcurrentMap<K, V>, Serializable {
238 > public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
239 >    implements ConcurrentMap<K,V>, Serializable {
240      private static final long serialVersionUID = 7249069246763182397L;
241  
242      /*
# Line 228 | Line 249 | public class ConcurrentHashMap<K, V>
249       * the same or better than java.util.HashMap, and to support high
250       * initial insertion rates on an empty table by many threads.
251       *
252 <     * Each key-value mapping is held in a Node.  Because Node key
253 <     * fields can contain special values, they are defined using plain
254 <     * Object types (not type "K"). This leads to a lot of explicit
255 <     * casting (and many explicit warning suppressions to tell
256 <     * compilers not to complain about it). It also allows some of the
257 <     * public methods to be factored into a smaller number of internal
258 <     * methods (although sadly not so for the five variants of
259 <     * put-related operations). The validation-based approach
260 <     * explained below leads to a lot of code sprawl because
261 <     * retry-control precludes factoring into smaller methods.
252 >     * This map usually acts as a binned (bucketed) hash table.  Each
253 >     * key-value mapping is held in a Node.  Most nodes are instances
254 >     * of the basic Node class with hash, key, value, and next
255 >     * fields. However, various subclasses exist: TreeNodes are
256 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
257 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
258 >     * of bins during resizing. ReservationNodes are used as
259 >     * placeholders while establishing values in computeIfAbsent and
260 >     * related methods.  The types TreeBin, ForwardingNode, and
261 >     * ReservationNode do not hold normal user keys, values, or
262 >     * hashes, and are readily distinguishable during search etc
263 >     * because they have negative hash fields and null key and value
264 >     * fields. (These special nodes are either uncommon or transient,
265 >     * so the impact of carrying around some unused fields is
266 >     * insignificant.)
267       *
268       * The table is lazily initialized to a power-of-two size upon the
269       * first insertion.  Each bin in the table normally contains a
# Line 245 | Line 271 | public class ConcurrentHashMap<K, V>
271       * Table accesses require volatile/atomic reads, writes, and
272       * CASes.  Because there is no other way to arrange this without
273       * adding further indirections, we use intrinsics
274 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
249 <     * are always accurately traversable under volatile reads, so long
250 <     * as lookups check hash code and non-nullness of value before
251 <     * checking key equality.
274 >     * (sun.misc.Unsafe) operations.
275       *
276       * We use the top (sign) bit of Node hash fields for control
277       * purposes -- it is available anyway because of addressing
278 <     * constraints.  Nodes with negative hash fields are forwarding
279 <     * nodes to either TreeBins or resized tables.  The lower 31 bits
257 <     * of each normal Node's hash field contain a transformation of
258 <     * the key's hash code.
278 >     * constraints.  Nodes with negative hash fields are specially
279 >     * handled or ignored in map methods.
280       *
281       * Insertion (via put or its variants) of the first node in an
282       * empty bin is performed by just CASing it to the bin.  This is
# Line 272 | Line 293 | public class ConcurrentHashMap<K, V>
293       * validate that it is still the first node after locking it, and
294       * retry if not. Because new nodes are always appended to lists,
295       * once a node is first in a bin, it remains first until deleted
296 <     * or the bin becomes invalidated (upon resizing).  However,
276 <     * operations that only conditionally update may inspect nodes
277 <     * until the point of update. This is a converse of sorts to the
278 <     * lazy locking technique described by Herlihy & Shavit.
296 >     * or the bin becomes invalidated (upon resizing).
297       *
298       * The main disadvantage of per-bin locks is that other update
299       * operations on other nodes in a bin list protected by the same
# Line 308 | Line 326 | public class ConcurrentHashMap<K, V>
326       * sometimes deviate significantly from uniform randomness.  This
327       * includes the case when N > (1<<30), so some keys MUST collide.
328       * Similarly for dumb or hostile usages in which multiple keys are
329 <     * designed to have identical hash codes. Also, although we guard
330 <     * against the worst effects of this (see method spread), sets of
331 <     * hashes may differ only in bits that do not impact their bin
332 <     * index for a given power-of-two mask.  So we use a secondary
333 <     * strategy that applies when the number of nodes in a bin exceeds
334 <     * a threshold, and at least one of the keys implements
317 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
318 <     * (a specialized form of red-black trees), bounding search time
319 <     * to O(log N).  Each search step in a TreeBin is around twice as
329 >     * designed to have identical hash codes or ones that differs only
330 >     * in masked-out high bits. So we use a secondary strategy that
331 >     * applies when the number of nodes in a bin exceeds a
332 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
333 >     * specialized form of red-black trees), bounding search time to
334 >     * O(log N).  Each search step in a TreeBin is at least twice as
335       * slow as in a regular list, but given that N cannot exceed
336       * (1<<64) (before running out of addresses) this bounds search
337       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 329 | Line 344 | public class ConcurrentHashMap<K, V>
344       * The table is resized when occupancy exceeds a percentage
345       * threshold (nominally, 0.75, but see below).  Any thread
346       * noticing an overfull bin may assist in resizing after the
347 <     * initiating thread allocates and sets up the replacement
348 <     * array. However, rather than stalling, these other threads may
349 <     * proceed with insertions etc.  The use of TreeBins shields us
350 <     * from the worst case effects of overfilling while resizes are in
347 >     * initiating thread allocates and sets up the replacement array.
348 >     * However, rather than stalling, these other threads may proceed
349 >     * with insertions etc.  The use of TreeBins shields us from the
350 >     * worst case effects of overfilling while resizes are in
351       * progress.  Resizing proceeds by transferring bins, one by one,
352 <     * from the table to the next table. To enable concurrency, the
353 <     * next table must be (incrementally) prefilled with place-holders
354 <     * serving as reverse forwarders to the old table.  Because we are
352 >     * from the table to the next table. However, threads claim small
353 >     * blocks of indices to transfer (via field transferIndex) before
354 >     * doing so, reducing contention.  A generation stamp in field
355 >     * sizeCtl ensures that resizings do not overlap. Because we are
356       * using power-of-two expansion, the elements from each bin must
357       * either stay at same index, or move with a power of two
358       * offset. We eliminate unnecessary node creation by catching
# Line 357 | Line 373 | public class ConcurrentHashMap<K, V>
373       * locks, average aggregate waits become shorter as resizing
374       * progresses.  The transfer operation must also ensure that all
375       * accessible bins in both the old and new table are usable by any
376 <     * traversal.  This is arranged by proceeding from the last bin
377 <     * (table.length - 1) up towards the first.  Upon seeing a
378 <     * forwarding node, traversals (see class Traverser) arrange to
379 <     * move to the new table without revisiting nodes.  However, to
380 <     * ensure that no intervening nodes are skipped, bin splitting can
381 <     * only begin after the associated reverse-forwarders are in
382 <     * place.
376 >     * traversal.  This is arranged in part by proceeding from the
377 >     * last bin (table.length - 1) up towards the first.  Upon seeing
378 >     * a forwarding node, traversals (see class Traverser) arrange to
379 >     * move to the new table without revisiting nodes.  To ensure that
380 >     * no intervening nodes are skipped even when moved out of order,
381 >     * a stack (see class TableStack) is created on first encounter of
382 >     * a forwarding node during a traversal, to maintain its place if
383 >     * later processing the current table. The need for these
384 >     * save/restore mechanics is relatively rare, but when one
385 >     * forwarding node is encountered, typically many more will be.
386 >     * So Traversers use a simple caching scheme to avoid creating so
387 >     * many new TableStack nodes. (Thanks to Peter Levart for
388 >     * suggesting use of a stack here.)
389       *
390       * The traversal scheme also applies to partial traversals of
391       * ranges of bins (via an alternate Traverser constructor)
# Line 382 | Line 404 | public class ConcurrentHashMap<K, V>
404       * LongAdder. We need to incorporate a specialization rather than
405       * just use a LongAdder in order to access implicit
406       * contention-sensing that leads to creation of multiple
407 <     * Cells.  The counter mechanics avoid contention on
407 >     * CounterCells.  The counter mechanics avoid contention on
408       * updates but can encounter cache thrashing if read too
409       * frequently during concurrent access. To avoid reading so often,
410       * resizing under contention is attempted only upon adding to a
411       * bin already holding two or more nodes. Under uniform hash
412       * distributions, the probability of this occurring at threshold
413       * is around 13%, meaning that only about 1 in 8 puts check
414 <     * threshold (and after resizing, many fewer do so). The bulk
415 <     * putAll operation further reduces contention by only committing
416 <     * count updates upon these size checks.
414 >     * threshold (and after resizing, many fewer do so).
415 >     *
416 >     * TreeBins use a special form of comparison for search and
417 >     * related operations (which is the main reason we cannot use
418 >     * existing collections such as TreeMaps). TreeBins contain
419 >     * Comparable elements, but may contain others, as well as
420 >     * elements that are Comparable but not necessarily Comparable for
421 >     * the same T, so we cannot invoke compareTo among them. To handle
422 >     * this, the tree is ordered primarily by hash value, then by
423 >     * Comparable.compareTo order if applicable.  On lookup at a node,
424 >     * if elements are not comparable or compare as 0 then both left
425 >     * and right children may need to be searched in the case of tied
426 >     * hash values. (This corresponds to the full list search that
427 >     * would be necessary if all elements were non-Comparable and had
428 >     * tied hashes.) On insertion, to keep a total ordering (or as
429 >     * close as is required here) across rebalancings, we compare
430 >     * classes and identityHashCodes as tie-breakers. The red-black
431 >     * balancing code is updated from pre-jdk-collections
432 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
433 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
434 >     * Algorithms" (CLR).
435 >     *
436 >     * TreeBins also require an additional locking mechanism.  While
437 >     * list traversal is always possible by readers even during
438 >     * updates, tree traversal is not, mainly because of tree-rotations
439 >     * that may change the root node and/or its linkages.  TreeBins
440 >     * include a simple read-write lock mechanism parasitic on the
441 >     * main bin-synchronization strategy: Structural adjustments
442 >     * associated with an insertion or removal are already bin-locked
443 >     * (and so cannot conflict with other writers) but must wait for
444 >     * ongoing readers to finish. Since there can be only one such
445 >     * waiter, we use a simple scheme using a single "waiter" field to
446 >     * block writers.  However, readers need never block.  If the root
447 >     * lock is held, they proceed along the slow traversal path (via
448 >     * next-pointers) until the lock becomes available or the list is
449 >     * exhausted, whichever comes first. These cases are not fast, but
450 >     * maximize aggregate expected throughput.
451       *
452       * Maintaining API and serialization compatibility with previous
453       * versions of this class introduces several oddities. Mainly: We
# Line 401 | Line 457 | public class ConcurrentHashMap<K, V>
457       * time that we can guarantee to honor it.) We also declare an
458       * unused "Segment" class that is instantiated in minimal form
459       * only when serializing.
460 +     *
461 +     * Also, solely for compatibility with previous versions of this
462 +     * class, it extends AbstractMap, even though all of its methods
463 +     * are overridden, so it is just useless baggage.
464 +     *
465 +     * This file is organized to make things a little easier to follow
466 +     * while reading than they might otherwise: First the main static
467 +     * declarations and utilities, then fields, then main public
468 +     * methods (with a few factorings of multiple public methods into
469 +     * internal ones), then sizing methods, trees, traversers, and
470 +     * bulk operations.
471       */
472  
473      /* ---------------- Constants -------------- */
# Line 443 | Line 510 | public class ConcurrentHashMap<K, V>
510  
511      /**
512       * The bin count threshold for using a tree rather than list for a
513 <     * bin.  The value reflects the approximate break-even point for
514 <     * using tree-based operations.
513 >     * bin.  Bins are converted to trees when adding an element to a
514 >     * bin with at least this many nodes. The value must be greater
515 >     * than 2, and should be at least 8 to mesh with assumptions in
516 >     * tree removal about conversion back to plain bins upon
517 >     * shrinkage.
518       */
519 <    private static final int TREE_THRESHOLD = 8;
519 >    static final int TREEIFY_THRESHOLD = 8;
520 >
521 >    /**
522 >     * The bin count threshold for untreeifying a (split) bin during a
523 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
524 >     * most 6 to mesh with shrinkage detection under removal.
525 >     */
526 >    static final int UNTREEIFY_THRESHOLD = 6;
527 >
528 >    /**
529 >     * The smallest table capacity for which bins may be treeified.
530 >     * (Otherwise the table is resized if too many nodes in a bin.)
531 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
532 >     * conflicts between resizing and treeification thresholds.
533 >     */
534 >    static final int MIN_TREEIFY_CAPACITY = 64;
535  
536      /**
537       * Minimum number of rebinnings per transfer step. Ranges are
# Line 457 | Line 542 | public class ConcurrentHashMap<K, V>
542       */
543      private static final int MIN_TRANSFER_STRIDE = 16;
544  
545 +    /**
546 +     * The number of bits used for generation stamp in sizeCtl.
547 +     * Must be at least 6 for 32bit arrays.
548 +     */
549 +    private static int RESIZE_STAMP_BITS = 16;
550 +
551 +    /**
552 +     * The maximum number of threads that can help resize.
553 +     * Must fit in 32 - RESIZE_STAMP_BITS bits.
554 +     */
555 +    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
556 +
557 +    /**
558 +     * The bit shift for recording size stamp in sizeCtl.
559 +     */
560 +    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
561 +
562      /*
563       * Encodings for Node hash fields. See above for explanation.
564       */
565 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
565 >    static final int MOVED     = -1; // hash for forwarding nodes
566 >    static final int TREEBIN   = -2; // hash for roots of trees
567 >    static final int RESERVED  = -3; // hash for transient reservations
568      static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
569  
570      /** Number of CPUS, to place bounds on some sizings */
571      static final int NCPU = Runtime.getRuntime().availableProcessors();
572  
573 <    /* ---------------- Counters -------------- */
573 >    /** For serialization compatibility. */
574 >    private static final ObjectStreamField[] serialPersistentFields = {
575 >        new ObjectStreamField("segments", Segment[].class),
576 >        new ObjectStreamField("segmentMask", Integer.TYPE),
577 >        new ObjectStreamField("segmentShift", Integer.TYPE)
578 >    };
579  
580 <    // Adapted from LongAdder and Striped64.
472 <    // See their internal docs for explanation.
580 >    /* ---------------- Nodes -------------- */
581  
582 <    // A padded cell for distributing counts
583 <    static final class Cell {
584 <        volatile long p0, p1, p2, p3, p4, p5, p6;
585 <        volatile long value;
586 <        volatile long q0, q1, q2, q3, q4, q5, q6;
587 <        Cell(long x) { value = x; }
582 >    /**
583 >     * Key-value entry.  This class is never exported out as a
584 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
585 >     * MapEntry below), but can be used for read-only traversals used
586 >     * in bulk tasks.  Subclasses of Node with a negative hash field
587 >     * are special, and contain null keys and values (but are never
588 >     * exported).  Otherwise, keys and vals are never null.
589 >     */
590 >    static class Node<K,V> implements Map.Entry<K,V> {
591 >        final int hash;
592 >        final K key;
593 >        volatile V val;
594 >        volatile Node<K,V> next;
595 >
596 >        Node(int hash, K key, V val, Node<K,V> next) {
597 >            this.hash = hash;
598 >            this.key = key;
599 >            this.val = val;
600 >            this.next = next;
601 >        }
602 >
603 >        public final K getKey()       { return key; }
604 >        public final V getValue()     { return val; }
605 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
606 >        public final String toString(){ return key + "=" + val; }
607 >        public final V setValue(V value) {
608 >            throw new UnsupportedOperationException();
609 >        }
610 >
611 >        public final boolean equals(Object o) {
612 >            Object k, v, u; Map.Entry<?,?> e;
613 >            return ((o instanceof Map.Entry) &&
614 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
615 >                    (v = e.getValue()) != null &&
616 >                    (k == key || k.equals(key)) &&
617 >                    (v == (u = val) || v.equals(u)));
618 >        }
619 >
620 >        /**
621 >         * Virtualized support for map.get(); overridden in subclasses.
622 >         */
623 >        Node<K,V> find(int h, Object k) {
624 >            Node<K,V> e = this;
625 >            if (k != null) {
626 >                do {
627 >                    K ek;
628 >                    if (e.hash == h &&
629 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
630 >                        return e;
631 >                } while ((e = e.next) != null);
632 >            }
633 >            return null;
634 >        }
635 >    }
636 >
637 >    /* ---------------- Static utilities -------------- */
638 >
639 >    /**
640 >     * Spreads (XORs) higher bits of hash to lower and also forces top
641 >     * bit to 0. Because the table uses power-of-two masking, sets of
642 >     * hashes that vary only in bits above the current mask will
643 >     * always collide. (Among known examples are sets of Float keys
644 >     * holding consecutive whole numbers in small tables.)  So we
645 >     * apply a transform that spreads the impact of higher bits
646 >     * downward. There is a tradeoff between speed, utility, and
647 >     * quality of bit-spreading. Because many common sets of hashes
648 >     * are already reasonably distributed (so don't benefit from
649 >     * spreading), and because we use trees to handle large sets of
650 >     * collisions in bins, we just XOR some shifted bits in the
651 >     * cheapest possible way to reduce systematic lossage, as well as
652 >     * to incorporate impact of the highest bits that would otherwise
653 >     * never be used in index calculations because of table bounds.
654 >     */
655 >    static final int spread(int h) {
656 >        return (h ^ (h >>> 16)) & HASH_BITS;
657 >    }
658 >
659 >    /**
660 >     * Returns a power of two table size for the given desired capacity.
661 >     * See Hackers Delight, sec 3.2
662 >     */
663 >    private static final int tableSizeFor(int c) {
664 >        int n = c - 1;
665 >        n |= n >>> 1;
666 >        n |= n >>> 2;
667 >        n |= n >>> 4;
668 >        n |= n >>> 8;
669 >        n |= n >>> 16;
670 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
671 >    }
672 >
673 >    /**
674 >     * Returns x's Class if it is of the form "class C implements
675 >     * Comparable<C>", else null.
676 >     */
677 >    static Class<?> comparableClassFor(Object x) {
678 >        if (x instanceof Comparable) {
679 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
680 >            if ((c = x.getClass()) == String.class) // bypass checks
681 >                return c;
682 >            if ((ts = c.getGenericInterfaces()) != null) {
683 >                for (int i = 0; i < ts.length; ++i) {
684 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
685 >                        ((p = (ParameterizedType)t).getRawType() ==
686 >                         Comparable.class) &&
687 >                        (as = p.getActualTypeArguments()) != null &&
688 >                        as.length == 1 && as[0] == c) // type arg is c
689 >                        return c;
690 >                }
691 >            }
692 >        }
693 >        return null;
694 >    }
695 >
696 >    /**
697 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
698 >     * class), else 0.
699 >     */
700 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
701 >    static int compareComparables(Class<?> kc, Object k, Object x) {
702 >        return (x == null || x.getClass() != kc ? 0 :
703 >                ((Comparable)k).compareTo(x));
704 >    }
705 >
706 >    /* ---------------- Table element access -------------- */
707 >
708 >    /*
709 >     * Volatile access methods are used for table elements as well as
710 >     * elements of in-progress next table while resizing.  All uses of
711 >     * the tab arguments must be null checked by callers.  All callers
712 >     * also paranoically precheck that tab's length is not zero (or an
713 >     * equivalent check), thus ensuring that any index argument taking
714 >     * the form of a hash value anded with (length - 1) is a valid
715 >     * index.  Note that, to be correct wrt arbitrary concurrency
716 >     * errors by users, these checks must operate on local variables,
717 >     * which accounts for some odd-looking inline assignments below.
718 >     * Note that calls to setTabAt always occur within locked regions,
719 >     * and so in principle require only release ordering, not
720 >     * full volatile semantics, but are currently coded as volatile
721 >     * writes to be conservative.
722 >     */
723 >
724 >    @SuppressWarnings("unchecked")
725 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
726 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
727 >    }
728 >
729 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
730 >                                        Node<K,V> c, Node<K,V> v) {
731 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
732 >    }
733 >
734 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
735 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
736      }
737  
738      /* ---------------- Fields -------------- */
# Line 485 | Line 741 | public class ConcurrentHashMap<K, V>
741       * The array of bins. Lazily initialized upon first insertion.
742       * Size is always a power of two. Accessed directly by iterators.
743       */
744 <    transient volatile Node<V>[] table;
744 >    transient volatile Node<K,V>[] table;
745  
746      /**
747       * The next table to use; non-null only while resizing.
748       */
749 <    private transient volatile Node<V>[] nextTable;
749 >    private transient volatile Node<K,V>[] nextTable;
750  
751      /**
752       * Base counter value, used mainly when there is no contention,
# Line 515 | Line 771 | public class ConcurrentHashMap<K, V>
771      private transient volatile int transferIndex;
772  
773      /**
774 <     * The least available table index to split while resizing.
519 <     */
520 <    private transient volatile int transferOrigin;
521 <
522 <    /**
523 <     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
774 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
775       */
776      private transient volatile int cellsBusy;
777  
778      /**
779       * Table of counter cells. When non-null, size is a power of 2.
780       */
781 <    private transient volatile Cell[] counterCells;
781 >    private transient volatile CounterCell[] counterCells;
782  
783      // views
784      private transient KeySetView<K,V> keySet;
785      private transient ValuesView<K,V> values;
786      private transient EntrySetView<K,V> entrySet;
787  
537    /** For serialization compatibility. Null unless serialized; see below */
538    private Segment<K,V>[] segments;
788  
789 <    /* ---------------- Table element access -------------- */
789 >    /* ---------------- Public operations -------------- */
790  
791 <    /*
792 <     * Volatile access methods are used for table elements as well as
793 <     * elements of in-progress next table while resizing.  Uses are
794 <     * null checked by callers, and implicitly bounds-checked, relying
546 <     * on the invariants that tab arrays have non-zero size, and all
547 <     * indices are masked with (tab.length - 1) which is never
548 <     * negative and always less than length. Note that, to be correct
549 <     * wrt arbitrary concurrency errors by users, bounds checks must
550 <     * operate on local variables, which accounts for some odd-looking
551 <     * inline assignments below.
552 <     */
553 <
554 <    @SuppressWarnings("unchecked") static final <V> Node<V> tabAt
555 <        (Node<V>[] tab, int i) { // used by Traverser
556 <        return (Node<V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
791 >    /**
792 >     * Creates a new, empty map with the default initial table size (16).
793 >     */
794 >    public ConcurrentHashMap() {
795      }
796  
797 <    private static final <V> boolean casTabAt
798 <        (Node<V>[] tab, int i, Node<V> c, Node<V> v) {
799 <        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
797 >    /**
798 >     * Creates a new, empty map with an initial table size
799 >     * accommodating the specified number of elements without the need
800 >     * to dynamically resize.
801 >     *
802 >     * @param initialCapacity The implementation performs internal
803 >     * sizing to accommodate this many elements.
804 >     * @throws IllegalArgumentException if the initial capacity of
805 >     * elements is negative
806 >     */
807 >    public ConcurrentHashMap(int initialCapacity) {
808 >        if (initialCapacity < 0)
809 >            throw new IllegalArgumentException();
810 >        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
811 >                   MAXIMUM_CAPACITY :
812 >                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
813 >        this.sizeCtl = cap;
814      }
815  
816 <    private static final <V> void setTabAt
817 <        (Node<V>[] tab, int i, Node<V> v) {
818 <        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
816 >    /**
817 >     * Creates a new map with the same mappings as the given map.
818 >     *
819 >     * @param m the map
820 >     */
821 >    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
822 >        this.sizeCtl = DEFAULT_CAPACITY;
823 >        putAll(m);
824      }
825  
569    /* ---------------- Nodes -------------- */
570
826      /**
827 <     * Key-value entry. Note that this is never exported out as a
828 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
829 <     * field of MOVED are special, and do not contain user keys or
830 <     * values.  Otherwise, keys are never null, and null val fields
831 <     * indicate that a node is in the process of being deleted or
832 <     * created. For purposes of read-only access, a key may be read
833 <     * before a val, but can only be used after checking val to be
834 <     * non-null.
827 >     * Creates a new, empty map with an initial table size based on
828 >     * the given number of elements ({@code initialCapacity}) and
829 >     * initial table density ({@code loadFactor}).
830 >     *
831 >     * @param initialCapacity the initial capacity. The implementation
832 >     * performs internal sizing to accommodate this many elements,
833 >     * given the specified load factor.
834 >     * @param loadFactor the load factor (table density) for
835 >     * establishing the initial table size
836 >     * @throws IllegalArgumentException if the initial capacity of
837 >     * elements is negative or the load factor is nonpositive
838 >     *
839 >     * @since 1.6
840       */
841 <    static class Node<V> {
842 <        final int hash;
843 <        final Object key;
584 <        volatile V val;
585 <        volatile Node<V> next;
841 >    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
842 >        this(initialCapacity, loadFactor, 1);
843 >    }
844  
845 <        Node(int hash, Object key, V val, Node<V> next) {
846 <            this.hash = hash;
847 <            this.key = key;
848 <            this.val = val;
849 <            this.next = next;
850 <        }
845 >    /**
846 >     * Creates a new, empty map with an initial table size based on
847 >     * the given number of elements ({@code initialCapacity}), table
848 >     * density ({@code loadFactor}), and number of concurrently
849 >     * updating threads ({@code concurrencyLevel}).
850 >     *
851 >     * @param initialCapacity the initial capacity. The implementation
852 >     * performs internal sizing to accommodate this many elements,
853 >     * given the specified load factor.
854 >     * @param loadFactor the load factor (table density) for
855 >     * establishing the initial table size
856 >     * @param concurrencyLevel the estimated number of concurrently
857 >     * updating threads. The implementation may use this value as
858 >     * a sizing hint.
859 >     * @throws IllegalArgumentException if the initial capacity is
860 >     * negative or the load factor or concurrencyLevel are
861 >     * nonpositive
862 >     */
863 >    public ConcurrentHashMap(int initialCapacity,
864 >                             float loadFactor, int concurrencyLevel) {
865 >        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
866 >            throw new IllegalArgumentException();
867 >        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
868 >            initialCapacity = concurrencyLevel;   // as estimated threads
869 >        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
870 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
871 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
872 >        this.sizeCtl = cap;
873      }
874  
875 <    /* ---------------- TreeBins -------------- */
875 >    // Original (since JDK1.2) Map methods
876  
877      /**
878 <     * Nodes for use in TreeBins
878 >     * {@inheritDoc}
879       */
880 <    static final class TreeNode<V> extends Node<V> {
881 <        TreeNode<V> parent;  // red-black tree links
882 <        TreeNode<V> left;
883 <        TreeNode<V> right;
884 <        TreeNode<V> prev;    // needed to unlink next upon deletion
885 <        boolean red;
880 >    public int size() {
881 >        long n = sumCount();
882 >        return ((n < 0L) ? 0 :
883 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
884 >                (int)n);
885 >    }
886  
887 <        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
888 <            super(hash, key, val, next);
889 <            this.parent = parent;
890 <        }
887 >    /**
888 >     * {@inheritDoc}
889 >     */
890 >    public boolean isEmpty() {
891 >        return sumCount() <= 0L; // ignore transient negative values
892      }
893  
894      /**
895 <     * A specialized form of red-black tree for use in bins
896 <     * whose size exceeds a threshold.
895 >     * Returns the value to which the specified key is mapped,
896 >     * or {@code null} if this map contains no mapping for the key.
897       *
898 <     * TreeBins use a special form of comparison for search and
899 <     * related operations (which is the main reason we cannot use
900 <     * existing collections such as TreeMaps). TreeBins contain
901 <     * Comparable elements, but may contain others, as well as
621 <     * elements that are Comparable but not necessarily Comparable<T>
622 <     * for the same T, so we cannot invoke compareTo among them. To
623 <     * handle this, the tree is ordered primarily by hash value, then
624 <     * by getClass().getName() order, and then by Comparator order
625 <     * among elements of the same class.  On lookup at a node, if
626 <     * elements are not comparable or compare as 0, both left and
627 <     * right children may need to be searched in the case of tied hash
628 <     * values. (This corresponds to the full list search that would be
629 <     * necessary if all elements were non-Comparable and had tied
630 <     * hashes.)  The red-black balancing code is updated from
631 <     * pre-jdk-collections
632 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
633 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
634 <     * Algorithms" (CLR).
898 >     * <p>More formally, if this map contains a mapping from a key
899 >     * {@code k} to a value {@code v} such that {@code key.equals(k)},
900 >     * then this method returns {@code v}; otherwise it returns
901 >     * {@code null}.  (There can be at most one such mapping.)
902       *
903 <     * TreeBins also maintain a separate locking discipline than
637 <     * regular bins. Because they are forwarded via special MOVED
638 <     * nodes at bin heads (which can never change once established),
639 <     * we cannot use those nodes as locks. Instead, TreeBin
640 <     * extends AbstractQueuedSynchronizer to support a simple form of
641 <     * read-write lock. For update operations and table validation,
642 <     * the exclusive form of lock behaves in the same way as bin-head
643 <     * locks. However, lookups use shared read-lock mechanics to allow
644 <     * multiple readers in the absence of writers.  Additionally,
645 <     * these lookups do not ever block: While the lock is not
646 <     * available, they proceed along the slow traversal path (via
647 <     * next-pointers) until the lock becomes available or the list is
648 <     * exhausted, whichever comes first. (These cases are not fast,
649 <     * but maximize aggregate expected throughput.)  The AQS mechanics
650 <     * for doing this are straightforward.  The lock state is held as
651 <     * AQS getState().  Read counts are negative; the write count (1)
652 <     * is positive.  There are no signalling preferences among readers
653 <     * and writers. Since we don't need to export full Lock API, we
654 <     * just override the minimal AQS methods and use them directly.
903 >     * @throws NullPointerException if the specified key is null
904       */
905 <    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
906 <        private static final long serialVersionUID = 2249069246763182397L;
907 <        transient TreeNode<V> root;  // root of tree
908 <        transient TreeNode<V> first; // head of next-pointer list
909 <
910 <        /* AQS overrides */
911 <        public final boolean isHeldExclusively() { return getState() > 0; }
912 <        public final boolean tryAcquire(int ignore) {
913 <            if (compareAndSetState(0, 1)) {
914 <                setExclusiveOwnerThread(Thread.currentThread());
915 <                return true;
916 <            }
917 <            return false;
918 <        }
919 <        public final boolean tryRelease(int ignore) {
671 <            setExclusiveOwnerThread(null);
672 <            setState(0);
673 <            return true;
674 <        }
675 <        public final int tryAcquireShared(int ignore) {
676 <            for (int c;;) {
677 <                if ((c = getState()) > 0)
678 <                    return -1;
679 <                if (compareAndSetState(c, c -1))
680 <                    return 1;
681 <            }
682 <        }
683 <        public final boolean tryReleaseShared(int ignore) {
684 <            int c;
685 <            do {} while (!compareAndSetState(c = getState(), c + 1));
686 <            return c == -1;
687 <        }
688 <
689 <        /** From CLR */
690 <        private void rotateLeft(TreeNode<V> p) {
691 <            if (p != null) {
692 <                TreeNode<V> r = p.right, pp, rl;
693 <                if ((rl = p.right = r.left) != null)
694 <                    rl.parent = p;
695 <                if ((pp = r.parent = p.parent) == null)
696 <                    root = r;
697 <                else if (pp.left == p)
698 <                    pp.left = r;
699 <                else
700 <                    pp.right = r;
701 <                r.left = p;
702 <                p.parent = r;
703 <            }
704 <        }
705 <
706 <        /** From CLR */
707 <        private void rotateRight(TreeNode<V> p) {
708 <            if (p != null) {
709 <                TreeNode<V> l = p.left, pp, lr;
710 <                if ((lr = p.left = l.right) != null)
711 <                    lr.parent = p;
712 <                if ((pp = l.parent = p.parent) == null)
713 <                    root = l;
714 <                else if (pp.right == p)
715 <                    pp.right = l;
716 <                else
717 <                    pp.left = l;
718 <                l.right = p;
719 <                p.parent = l;
905 >    public V get(Object key) {
906 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
907 >        int h = spread(key.hashCode());
908 >        if ((tab = table) != null && (n = tab.length) > 0 &&
909 >            (e = tabAt(tab, (n - 1) & h)) != null) {
910 >            if ((eh = e.hash) == h) {
911 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
912 >                    return e.val;
913 >            }
914 >            else if (eh < 0)
915 >                return (p = e.find(h, key)) != null ? p.val : null;
916 >            while ((e = e.next) != null) {
917 >                if (e.hash == h &&
918 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
919 >                    return e.val;
920              }
921          }
922 +        return null;
923 +    }
924  
925 <        /**
926 <         * Returns the TreeNode (or null if not found) for the given key
927 <         * starting at given root.
928 <         */
929 <        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
930 <            (int h, Object k, TreeNode<V> p) {
931 <            Class<?> c = k.getClass();
932 <            while (p != null) {
933 <                int dir, ph;  Object pk; Class<?> pc;
934 <                if ((ph = p.hash) == h) {
935 <                    if ((pk = p.key) == k || k.equals(pk))
936 <                        return p;
735 <                    if (c != (pc = pk.getClass()) ||
736 <                        !(k instanceof Comparable) ||
737 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
738 <                        if ((dir = (c == pc) ? 0 :
739 <                             c.getName().compareTo(pc.getName())) == 0) {
740 <                            TreeNode<V> r = null, pl, pr; // check both sides
741 <                            if ((pr = p.right) != null && h >= pr.hash &&
742 <                                (r = getTreeNode(h, k, pr)) != null)
743 <                                return r;
744 <                            else if ((pl = p.left) != null && h <= pl.hash)
745 <                                dir = -1;
746 <                            else // nothing there
747 <                                return null;
748 <                        }
749 <                    }
750 <                }
751 <                else
752 <                    dir = (h < ph) ? -1 : 1;
753 <                p = (dir > 0) ? p.right : p.left;
754 <            }
755 <            return null;
756 <        }
925 >    /**
926 >     * Tests if the specified object is a key in this table.
927 >     *
928 >     * @param  key possible key
929 >     * @return {@code true} if and only if the specified object
930 >     *         is a key in this table, as determined by the
931 >     *         {@code equals} method; {@code false} otherwise
932 >     * @throws NullPointerException if the specified key is null
933 >     */
934 >    public boolean containsKey(Object key) {
935 >        return get(key) != null;
936 >    }
937  
938 <        /**
939 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
940 <         * read-lock to call getTreeNode, but during failure to get
941 <         * lock, searches along next links.
942 <         */
943 <        final V getValue(int h, Object k) {
944 <            Node<V> r = null;
945 <            int c = getState(); // Must read lock state first
946 <            for (Node<V> e = first; e != null; e = e.next) {
947 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
948 <                    try {
949 <                        r = getTreeNode(h, k, root);
950 <                    } finally {
951 <                        releaseShared(0);
952 <                    }
953 <                    break;
954 <                }
955 <                else if (e.hash == h && k.equals(e.key)) {
956 <                    r = e;
957 <                    break;
778 <                }
779 <                else
780 <                    c = getState();
938 >    /**
939 >     * Returns {@code true} if this map maps one or more keys to the
940 >     * specified value. Note: This method may require a full traversal
941 >     * of the map, and is much slower than method {@code containsKey}.
942 >     *
943 >     * @param value value whose presence in this map is to be tested
944 >     * @return {@code true} if this map maps one or more keys to the
945 >     *         specified value
946 >     * @throws NullPointerException if the specified value is null
947 >     */
948 >    public boolean containsValue(Object value) {
949 >        if (value == null)
950 >            throw new NullPointerException();
951 >        Node<K,V>[] t;
952 >        if ((t = table) != null) {
953 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
954 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
955 >                V v;
956 >                if ((v = p.val) == value || (v != null && value.equals(v)))
957 >                    return true;
958              }
782            return r == null ? null : r.val;
959          }
960 +        return false;
961 +    }
962  
963 <        /**
964 <         * Finds or adds a node.
965 <         * @return null if added
966 <         */
967 <        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
968 <            (int h, Object k, V v) {
969 <            Class<?> c = k.getClass();
970 <            TreeNode<V> pp = root, p = null;
971 <            int dir = 0;
972 <            while (pp != null) { // find existing node or leaf to insert at
973 <                int ph;  Object pk; Class<?> pc;
974 <                p = pp;
975 <                if ((ph = p.hash) == h) {
976 <                    if ((pk = p.key) == k || k.equals(pk))
977 <                        return p;
978 <                    if (c != (pc = pk.getClass()) ||
801 <                        !(k instanceof Comparable) ||
802 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
803 <                        TreeNode<V> s = null, r = null, pr;
804 <                        if ((dir = (c == pc) ? 0 :
805 <                             c.getName().compareTo(pc.getName())) == 0) {
806 <                            if ((pr = p.right) != null && h >= pr.hash &&
807 <                                (r = getTreeNode(h, k, pr)) != null)
808 <                                return r;
809 <                            else // continue left
810 <                                dir = -1;
811 <                        }
812 <                        else if ((pr = p.right) != null && h >= pr.hash)
813 <                            s = pr;
814 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
815 <                            return r;
816 <                    }
817 <                }
818 <                else
819 <                    dir = (h < ph) ? -1 : 1;
820 <                pp = (dir > 0) ? p.right : p.left;
821 <            }
822 <
823 <            TreeNode<V> f = first;
824 <            TreeNode<V> x = first = new TreeNode<V>(h, k, v, f, p);
825 <            if (p == null)
826 <                root = x;
827 <            else { // attach and rebalance; adapted from CLR
828 <                TreeNode<V> xp, xpp;
829 <                if (f != null)
830 <                    f.prev = x;
831 <                if (dir <= 0)
832 <                    p.left = x;
833 <                else
834 <                    p.right = x;
835 <                x.red = true;
836 <                while (x != null && (xp = x.parent) != null && xp.red &&
837 <                       (xpp = xp.parent) != null) {
838 <                    TreeNode<V> xppl = xpp.left;
839 <                    if (xp == xppl) {
840 <                        TreeNode<V> y = xpp.right;
841 <                        if (y != null && y.red) {
842 <                            y.red = false;
843 <                            xp.red = false;
844 <                            xpp.red = true;
845 <                            x = xpp;
846 <                        }
847 <                        else {
848 <                            if (x == xp.right) {
849 <                                rotateLeft(x = xp);
850 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
851 <                            }
852 <                            if (xp != null) {
853 <                                xp.red = false;
854 <                                if (xpp != null) {
855 <                                    xpp.red = true;
856 <                                    rotateRight(xpp);
857 <                                }
858 <                            }
859 <                        }
860 <                    }
861 <                    else {
862 <                        TreeNode<V> y = xppl;
863 <                        if (y != null && y.red) {
864 <                            y.red = false;
865 <                            xp.red = false;
866 <                            xpp.red = true;
867 <                            x = xpp;
868 <                        }
869 <                        else {
870 <                            if (x == xp.left) {
871 <                                rotateRight(x = xp);
872 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
873 <                            }
874 <                            if (xp != null) {
875 <                                xp.red = false;
876 <                                if (xpp != null) {
877 <                                    xpp.red = true;
878 <                                    rotateLeft(xpp);
879 <                                }
880 <                            }
881 <                        }
882 <                    }
883 <                }
884 <                TreeNode<V> r = root;
885 <                if (r != null && r.red)
886 <                    r.red = false;
887 <            }
888 <            return null;
889 <        }
963 >    /**
964 >     * Maps the specified key to the specified value in this table.
965 >     * Neither the key nor the value can be null.
966 >     *
967 >     * <p>The value can be retrieved by calling the {@code get} method
968 >     * with a key that is equal to the original key.
969 >     *
970 >     * @param key key with which the specified value is to be associated
971 >     * @param value value to be associated with the specified key
972 >     * @return the previous value associated with {@code key}, or
973 >     *         {@code null} if there was no mapping for {@code key}
974 >     * @throws NullPointerException if the specified key or value is null
975 >     */
976 >    public V put(K key, V value) {
977 >        return putVal(key, value, false);
978 >    }
979  
980 <        /**
981 <         * Removes the given node, that must be present before this
982 <         * call.  This is messier than typical red-black deletion code
983 <         * because we cannot swap the contents of an interior node
984 <         * with a leaf successor that is pinned by "next" pointers
985 <         * that are accessible independently of lock. So instead we
986 <         * swap the tree linkages.
987 <         */
988 <        final void deleteTreeNode(TreeNode<V> p) {
989 <            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
990 <            TreeNode<V> pred = p.prev;
991 <            if (pred == null)
992 <                first = next;
904 <            else
905 <                pred.next = next;
906 <            if (next != null)
907 <                next.prev = pred;
908 <            TreeNode<V> replacement;
909 <            TreeNode<V> pl = p.left;
910 <            TreeNode<V> pr = p.right;
911 <            if (pl != null && pr != null) {
912 <                TreeNode<V> s = pr, sl;
913 <                while ((sl = s.left) != null) // find successor
914 <                    s = sl;
915 <                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
916 <                TreeNode<V> sr = s.right;
917 <                TreeNode<V> pp = p.parent;
918 <                if (s == pr) { // p was s's direct parent
919 <                    p.parent = s;
920 <                    s.right = p;
921 <                }
922 <                else {
923 <                    TreeNode<V> sp = s.parent;
924 <                    if ((p.parent = sp) != null) {
925 <                        if (s == sp.left)
926 <                            sp.left = p;
927 <                        else
928 <                            sp.right = p;
929 <                    }
930 <                    if ((s.right = pr) != null)
931 <                        pr.parent = s;
932 <                }
933 <                p.left = null;
934 <                if ((p.right = sr) != null)
935 <                    sr.parent = p;
936 <                if ((s.left = pl) != null)
937 <                    pl.parent = s;
938 <                if ((s.parent = pp) == null)
939 <                    root = s;
940 <                else if (p == pp.left)
941 <                    pp.left = s;
942 <                else
943 <                    pp.right = s;
944 <                replacement = sr;
945 <            }
946 <            else
947 <                replacement = (pl != null) ? pl : pr;
948 <            TreeNode<V> pp = p.parent;
949 <            if (replacement == null) {
950 <                if (pp == null) {
951 <                    root = null;
952 <                    return;
953 <                }
954 <                replacement = p;
980 >    /** Implementation for put and putIfAbsent */
981 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
982 >        if (key == null || value == null) throw new NullPointerException();
983 >        int hash = spread(key.hashCode());
984 >        int binCount = 0;
985 >        for (Node<K,V>[] tab = table;;) {
986 >            Node<K,V> f; int n, i, fh;
987 >            if (tab == null || (n = tab.length) == 0)
988 >                tab = initTable();
989 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
990 >                if (casTabAt(tab, i, null,
991 >                             new Node<K,V>(hash, key, value, null)))
992 >                    break;                   // no lock when adding to empty bin
993              }
994 +            else if ((fh = f.hash) == MOVED)
995 +                tab = helpTransfer(tab, f);
996              else {
997 <                replacement.parent = pp;
998 <                if (pp == null)
999 <                    root = replacement;
1000 <                else if (p == pp.left)
1001 <                    pp.left = replacement;
1002 <                else
1003 <                    pp.right = replacement;
1004 <                p.left = p.right = p.parent = null;
1005 <            }
1006 <            if (!p.red) { // rebalance, from CLR
1007 <                TreeNode<V> x = replacement;
1008 <                while (x != null) {
1009 <                    TreeNode<V> xp, xpl;
1010 <                    if (x.red || (xp = x.parent) == null) {
971 <                        x.red = false;
972 <                        break;
973 <                    }
974 <                    if (x == (xpl = xp.left)) {
975 <                        TreeNode<V> sib = xp.right;
976 <                        if (sib != null && sib.red) {
977 <                            sib.red = false;
978 <                            xp.red = true;
979 <                            rotateLeft(xp);
980 <                            sib = (xp = x.parent) == null ? null : xp.right;
981 <                        }
982 <                        if (sib == null)
983 <                            x = xp;
984 <                        else {
985 <                            TreeNode<V> sl = sib.left, sr = sib.right;
986 <                            if ((sr == null || !sr.red) &&
987 <                                (sl == null || !sl.red)) {
988 <                                sib.red = true;
989 <                                x = xp;
990 <                            }
991 <                            else {
992 <                                if (sr == null || !sr.red) {
993 <                                    if (sl != null)
994 <                                        sl.red = false;
995 <                                    sib.red = true;
996 <                                    rotateRight(sib);
997 <                                    sib = (xp = x.parent) == null ?
998 <                                        null : xp.right;
999 <                                }
1000 <                                if (sib != null) {
1001 <                                    sib.red = (xp == null) ? false : xp.red;
1002 <                                    if ((sr = sib.right) != null)
1003 <                                        sr.red = false;
997 >                V oldVal = null;
998 >                synchronized (f) {
999 >                    if (tabAt(tab, i) == f) {
1000 >                        if (fh >= 0) {
1001 >                            binCount = 1;
1002 >                            for (Node<K,V> e = f;; ++binCount) {
1003 >                                K ek;
1004 >                                if (e.hash == hash &&
1005 >                                    ((ek = e.key) == key ||
1006 >                                     (ek != null && key.equals(ek)))) {
1007 >                                    oldVal = e.val;
1008 >                                    if (!onlyIfAbsent)
1009 >                                        e.val = value;
1010 >                                    break;
1011                                  }
1012 <                                if (xp != null) {
1013 <                                    xp.red = false;
1014 <                                    rotateLeft(xp);
1012 >                                Node<K,V> pred = e;
1013 >                                if ((e = e.next) == null) {
1014 >                                    pred.next = new Node<K,V>(hash, key,
1015 >                                                              value, null);
1016 >                                    break;
1017                                  }
1009                                x = root;
1018                              }
1019                          }
1020 <                    }
1021 <                    else { // symmetric
1022 <                        TreeNode<V> sib = xpl;
1023 <                        if (sib != null && sib.red) {
1024 <                            sib.red = false;
1025 <                            xp.red = true;
1026 <                            rotateRight(xp);
1027 <                            sib = (xp = x.parent) == null ? null : xp.left;
1020 <                        }
1021 <                        if (sib == null)
1022 <                            x = xp;
1023 <                        else {
1024 <                            TreeNode<V> sl = sib.left, sr = sib.right;
1025 <                            if ((sl == null || !sl.red) &&
1026 <                                (sr == null || !sr.red)) {
1027 <                                sib.red = true;
1028 <                                x = xp;
1029 <                            }
1030 <                            else {
1031 <                                if (sl == null || !sl.red) {
1032 <                                    if (sr != null)
1033 <                                        sr.red = false;
1034 <                                    sib.red = true;
1035 <                                    rotateLeft(sib);
1036 <                                    sib = (xp = x.parent) == null ?
1037 <                                        null : xp.left;
1038 <                                }
1039 <                                if (sib != null) {
1040 <                                    sib.red = (xp == null) ? false : xp.red;
1041 <                                    if ((sl = sib.left) != null)
1042 <                                        sl.red = false;
1043 <                                }
1044 <                                if (xp != null) {
1045 <                                    xp.red = false;
1046 <                                    rotateRight(xp);
1047 <                                }
1048 <                                x = root;
1020 >                        else if (f instanceof TreeBin) {
1021 >                            Node<K,V> p;
1022 >                            binCount = 2;
1023 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1024 >                                                           value)) != null) {
1025 >                                oldVal = p.val;
1026 >                                if (!onlyIfAbsent)
1027 >                                    p.val = value;
1028                              }
1029                          }
1030                      }
1031                  }
1032 <            }
1033 <            if (p == replacement && (pp = p.parent) != null) {
1034 <                if (p == pp.left) // detach pointers
1035 <                    pp.left = null;
1036 <                else if (p == pp.right)
1037 <                    pp.right = null;
1038 <                p.parent = null;
1032 >                if (binCount != 0) {
1033 >                    if (binCount >= TREEIFY_THRESHOLD)
1034 >                        treeifyBin(tab, i);
1035 >                    if (oldVal != null)
1036 >                        return oldVal;
1037 >                    break;
1038 >                }
1039              }
1040          }
1041 +        addCount(1L, binCount);
1042 +        return null;
1043      }
1044  
1064    /* ---------------- Collision reduction methods -------------- */
1065
1045      /**
1046 <     * Spreads higher bits to lower, and also forces top bit to 0.
1047 <     * Because the table uses power-of-two masking, sets of hashes
1048 <     * that vary only in bits above the current mask will always
1049 <     * collide. (Among known examples are sets of Float keys holding
1050 <     * consecutive whole numbers in small tables.)  To counter this,
1072 <     * we apply a transform that spreads the impact of higher bits
1073 <     * downward. There is a tradeoff between speed, utility, and
1074 <     * quality of bit-spreading. Because many common sets of hashes
1075 <     * are already reasonably distributed across bits (so don't benefit
1076 <     * from spreading), and because we use trees to handle large sets
1077 <     * of collisions in bins, we don't need excessively high quality.
1046 >     * Copies all of the mappings from the specified map to this one.
1047 >     * These mappings replace any mappings that this map had for any of the
1048 >     * keys currently in the specified map.
1049 >     *
1050 >     * @param m mappings to be stored in this map
1051       */
1052 <    private static final int spread(int h) {
1053 <        h ^= (h >>> 18) ^ (h >>> 12);
1054 <        return (h ^ (h >>> 10)) & HASH_BITS;
1052 >    public void putAll(Map<? extends K, ? extends V> m) {
1053 >        tryPresize(m.size());
1054 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1055 >            putVal(e.getKey(), e.getValue(), false);
1056      }
1057  
1058      /**
1059 <     * Replaces a list bin with a tree bin if key is comparable.  Call
1060 <     * only when locked.
1059 >     * Removes the key (and its corresponding value) from this map.
1060 >     * This method does nothing if the key is not in the map.
1061 >     *
1062 >     * @param  key the key that needs to be removed
1063 >     * @return the previous value associated with {@code key}, or
1064 >     *         {@code null} if there was no mapping for {@code key}
1065 >     * @throws NullPointerException if the specified key is null
1066       */
1067 <    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1068 <        if (key instanceof Comparable) {
1090 <            TreeBin<V> t = new TreeBin<V>();
1091 <            for (Node<V> e = tabAt(tab, index); e != null; e = e.next)
1092 <                t.putTreeNode(e.hash, e.key, e.val);
1093 <            setTabAt(tab, index, new Node<V>(MOVED, t, null, null));
1094 <        }
1095 <    }
1096 <
1097 <    /* ---------------- Internal access and update methods -------------- */
1098 <
1099 <    /** Implementation for get and containsKey */
1100 <    @SuppressWarnings("unchecked") private final V internalGet(Object k) {
1101 <        int h = spread(k.hashCode());
1102 <        retry: for (Node<V>[] tab = table; tab != null;) {
1103 <            Node<V> e; Object ek; V ev; int eh; // locals to read fields once
1104 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1105 <                if ((eh = e.hash) < 0) {
1106 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1107 <                        return ((TreeBin<V>)ek).getValue(h, k);
1108 <                    else {                      // restart with new table
1109 <                        tab = (Node<V>[])ek;
1110 <                        continue retry;
1111 <                    }
1112 <                }
1113 <                else if (eh == h && (ev = e.val) != null &&
1114 <                         ((ek = e.key) == k || k.equals(ek)))
1115 <                    return ev;
1116 <            }
1117 <            break;
1118 <        }
1119 <        return null;
1067 >    public V remove(Object key) {
1068 >        return replaceNode(key, null, null);
1069      }
1070  
1071      /**
# Line 1124 | Line 1073 | public class ConcurrentHashMap<K, V>
1073       * Replaces node value with v, conditional upon match of cv if
1074       * non-null.  If resulting value is null, delete.
1075       */
1076 <    @SuppressWarnings("unchecked") private final V internalReplace
1077 <        (Object k, V v, Object cv) {
1078 <        int h = spread(k.hashCode());
1079 <        V oldVal = null;
1080 <        for (Node<V>[] tab = table;;) {
1081 <            Node<V> f; int i, fh; Object fk;
1133 <            if (tab == null ||
1134 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1076 >    final V replaceNode(Object key, V value, Object cv) {
1077 >        int hash = spread(key.hashCode());
1078 >        for (Node<K,V>[] tab = table;;) {
1079 >            Node<K,V> f; int n, i, fh;
1080 >            if (tab == null || (n = tab.length) == 0 ||
1081 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1082                  break;
1083 <            else if ((fh = f.hash) < 0) {
1084 <                if ((fk = f.key) instanceof TreeBin) {
1085 <                    TreeBin<V> t = (TreeBin<V>)fk;
1086 <                    boolean validated = false;
1087 <                    boolean deleted = false;
1088 <                    t.acquire(0);
1089 <                    try {
1090 <                        if (tabAt(tab, i) == f) {
1083 >            else if ((fh = f.hash) == MOVED)
1084 >                tab = helpTransfer(tab, f);
1085 >            else {
1086 >                V oldVal = null;
1087 >                boolean validated = false;
1088 >                synchronized (f) {
1089 >                    if (tabAt(tab, i) == f) {
1090 >                        if (fh >= 0) {
1091                              validated = true;
1092 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1093 <                            if (p != null) {
1092 >                            for (Node<K,V> e = f, pred = null;;) {
1093 >                                K ek;
1094 >                                if (e.hash == hash &&
1095 >                                    ((ek = e.key) == key ||
1096 >                                     (ek != null && key.equals(ek)))) {
1097 >                                    V ev = e.val;
1098 >                                    if (cv == null || cv == ev ||
1099 >                                        (ev != null && cv.equals(ev))) {
1100 >                                        oldVal = ev;
1101 >                                        if (value != null)
1102 >                                            e.val = value;
1103 >                                        else if (pred != null)
1104 >                                            pred.next = e.next;
1105 >                                        else
1106 >                                            setTabAt(tab, i, e.next);
1107 >                                    }
1108 >                                    break;
1109 >                                }
1110 >                                pred = e;
1111 >                                if ((e = e.next) == null)
1112 >                                    break;
1113 >                            }
1114 >                        }
1115 >                        else if (f instanceof TreeBin) {
1116 >                            validated = true;
1117 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1118 >                            TreeNode<K,V> r, p;
1119 >                            if ((r = t.root) != null &&
1120 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1121                                  V pv = p.val;
1122 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1122 >                                if (cv == null || cv == pv ||
1123 >                                    (pv != null && cv.equals(pv))) {
1124                                      oldVal = pv;
1125 <                                    if ((p.val = v) == null) {
1126 <                                        deleted = true;
1127 <                                        t.deleteTreeNode(p);
1128 <                                    }
1125 >                                    if (value != null)
1126 >                                        p.val = value;
1127 >                                    else if (t.removeTreeNode(p))
1128 >                                        setTabAt(tab, i, untreeify(t.first));
1129                                  }
1130                              }
1131                          }
1157                    } finally {
1158                        t.release(0);
1132                      }
1133 <                    if (validated) {
1134 <                        if (deleted)
1133 >                }
1134 >                if (validated) {
1135 >                    if (oldVal != null) {
1136 >                        if (value == null)
1137                              addCount(-1L, -1);
1138 <                        break;
1138 >                        return oldVal;
1139                      }
1140 +                    break;
1141                  }
1166                else
1167                    tab = (Node<V>[])fk;
1142              }
1143 <            else if (fh != h && f.next == null) // precheck
1144 <                break;                          // rules out possible existence
1143 >        }
1144 >        return null;
1145 >    }
1146 >
1147 >    /**
1148 >     * Removes all of the mappings from this map.
1149 >     */
1150 >    public void clear() {
1151 >        long delta = 0L; // negative number of deletions
1152 >        int i = 0;
1153 >        Node<K,V>[] tab = table;
1154 >        while (tab != null && i < tab.length) {
1155 >            int fh;
1156 >            Node<K,V> f = tabAt(tab, i);
1157 >            if (f == null)
1158 >                ++i;
1159 >            else if ((fh = f.hash) == MOVED) {
1160 >                tab = helpTransfer(tab, f);
1161 >                i = 0; // restart
1162 >            }
1163              else {
1172                boolean validated = false;
1173                boolean deleted = false;
1164                  synchronized (f) {
1165                      if (tabAt(tab, i) == f) {
1166 <                        validated = true;
1167 <                        for (Node<V> e = f, pred = null;;) {
1168 <                            Object ek; V ev;
1169 <                            if (e.hash == h &&
1170 <                                ((ev = e.val) != null) &&
1171 <                                ((ek = e.key) == k || k.equals(ek))) {
1182 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1183 <                                    oldVal = ev;
1184 <                                    if ((e.val = v) == null) {
1185 <                                        deleted = true;
1186 <                                        Node<V> en = e.next;
1187 <                                        if (pred != null)
1188 <                                            pred.next = en;
1189 <                                        else
1190 <                                            setTabAt(tab, i, en);
1191 <                                    }
1192 <                                }
1193 <                                break;
1194 <                            }
1195 <                            pred = e;
1196 <                            if ((e = e.next) == null)
1197 <                                break;
1166 >                        Node<K,V> p = (fh >= 0 ? f :
1167 >                                       (f instanceof TreeBin) ?
1168 >                                       ((TreeBin<K,V>)f).first : null);
1169 >                        while (p != null) {
1170 >                            --delta;
1171 >                            p = p.next;
1172                          }
1173 +                        setTabAt(tab, i++, null);
1174                      }
1175                  }
1176 <                if (validated) {
1177 <                    if (deleted)
1178 <                        addCount(-1L, -1);
1176 >            }
1177 >        }
1178 >        if (delta != 0L)
1179 >            addCount(delta, -1);
1180 >    }
1181 >
1182 >    /**
1183 >     * Returns a {@link Set} view of the keys contained in this map.
1184 >     * The set is backed by the map, so changes to the map are
1185 >     * reflected in the set, and vice-versa. The set supports element
1186 >     * removal, which removes the corresponding mapping from this map,
1187 >     * via the {@code Iterator.remove}, {@code Set.remove},
1188 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1189 >     * operations.  It does not support the {@code add} or
1190 >     * {@code addAll} operations.
1191 >     *
1192 >     * <p>The view's iterators and spliterators are
1193 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1194 >     *
1195 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1196 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1197 >     *
1198 >     * @return the set view
1199 >     */
1200 >    public KeySetView<K,V> keySet() {
1201 >        KeySetView<K,V> ks;
1202 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1203 >    }
1204 >
1205 >    /**
1206 >     * Returns a {@link Collection} view of the values contained in this map.
1207 >     * The collection is backed by the map, so changes to the map are
1208 >     * reflected in the collection, and vice-versa.  The collection
1209 >     * supports element removal, which removes the corresponding
1210 >     * mapping from this map, via the {@code Iterator.remove},
1211 >     * {@code Collection.remove}, {@code removeAll},
1212 >     * {@code retainAll}, and {@code clear} operations.  It does not
1213 >     * support the {@code add} or {@code addAll} operations.
1214 >     *
1215 >     * <p>The view's iterators and spliterators are
1216 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1217 >     *
1218 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}
1219 >     * and {@link Spliterator#NONNULL}.
1220 >     *
1221 >     * @return the collection view
1222 >     */
1223 >    public Collection<V> values() {
1224 >        ValuesView<K,V> vs;
1225 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1226 >    }
1227 >
1228 >    /**
1229 >     * Returns a {@link Set} view of the mappings contained in this map.
1230 >     * The set is backed by the map, so changes to the map are
1231 >     * reflected in the set, and vice-versa.  The set supports element
1232 >     * removal, which removes the corresponding mapping from the map,
1233 >     * via the {@code Iterator.remove}, {@code Set.remove},
1234 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1235 >     * operations.
1236 >     *
1237 >     * <p>The view's iterators and spliterators are
1238 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1239 >     *
1240 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1241 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1242 >     *
1243 >     * @return the set view
1244 >     */
1245 >    public Set<Map.Entry<K,V>> entrySet() {
1246 >        EntrySetView<K,V> es;
1247 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1248 >    }
1249 >
1250 >    /**
1251 >     * Returns the hash code value for this {@link Map}, i.e.,
1252 >     * the sum of, for each key-value pair in the map,
1253 >     * {@code key.hashCode() ^ value.hashCode()}.
1254 >     *
1255 >     * @return the hash code value for this map
1256 >     */
1257 >    public int hashCode() {
1258 >        int h = 0;
1259 >        Node<K,V>[] t;
1260 >        if ((t = table) != null) {
1261 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1262 >            for (Node<K,V> p; (p = it.advance()) != null; )
1263 >                h += p.key.hashCode() ^ p.val.hashCode();
1264 >        }
1265 >        return h;
1266 >    }
1267 >
1268 >    /**
1269 >     * Returns a string representation of this map.  The string
1270 >     * representation consists of a list of key-value mappings (in no
1271 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1272 >     * mappings are separated by the characters {@code ", "} (comma
1273 >     * and space).  Each key-value mapping is rendered as the key
1274 >     * followed by an equals sign ("{@code =}") followed by the
1275 >     * associated value.
1276 >     *
1277 >     * @return a string representation of this map
1278 >     */
1279 >    public String toString() {
1280 >        Node<K,V>[] t;
1281 >        int f = (t = table) == null ? 0 : t.length;
1282 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1283 >        StringBuilder sb = new StringBuilder();
1284 >        sb.append('{');
1285 >        Node<K,V> p;
1286 >        if ((p = it.advance()) != null) {
1287 >            for (;;) {
1288 >                K k = p.key;
1289 >                V v = p.val;
1290 >                sb.append(k == this ? "(this Map)" : k);
1291 >                sb.append('=');
1292 >                sb.append(v == this ? "(this Map)" : v);
1293 >                if ((p = it.advance()) == null)
1294                      break;
1295 <                }
1295 >                sb.append(',').append(' ');
1296              }
1297          }
1298 <        return oldVal;
1298 >        return sb.append('}').toString();
1299      }
1300  
1301 <    /*
1302 <     * Internal versions of insertion methods
1303 <     * All have the same basic structure as the first (internalPut):
1304 <     *  1. If table uninitialized, create
1305 <     *  2. If bin empty, try to CAS new node
1306 <     *  3. If bin stale, use new table
1307 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1308 <     *  5. Lock and validate; if valid, scan and add or update
1309 <     *
1220 <     * The putAll method differs mainly in attempting to pre-allocate
1221 <     * enough table space, and also more lazily performs count updates
1222 <     * and checks.
1223 <     *
1224 <     * Most of the function-accepting methods can't be factored nicely
1225 <     * because they require different functional forms, so instead
1226 <     * sprawl out similar mechanics.
1301 >    /**
1302 >     * Compares the specified object with this map for equality.
1303 >     * Returns {@code true} if the given object is a map with the same
1304 >     * mappings as this map.  This operation may return misleading
1305 >     * results if either map is concurrently modified during execution
1306 >     * of this method.
1307 >     *
1308 >     * @param o object to be compared for equality with this map
1309 >     * @return {@code true} if the specified object is equal to this map
1310       */
1311 +    public boolean equals(Object o) {
1312 +        if (o != this) {
1313 +            if (!(o instanceof Map))
1314 +                return false;
1315 +            Map<?,?> m = (Map<?,?>) o;
1316 +            Node<K,V>[] t;
1317 +            int f = (t = table) == null ? 0 : t.length;
1318 +            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1319 +            for (Node<K,V> p; (p = it.advance()) != null; ) {
1320 +                V val = p.val;
1321 +                Object v = m.get(p.key);
1322 +                if (v == null || (v != val && !v.equals(val)))
1323 +                    return false;
1324 +            }
1325 +            for (Map.Entry<?,?> e : m.entrySet()) {
1326 +                Object mk, mv, v;
1327 +                if ((mk = e.getKey()) == null ||
1328 +                    (mv = e.getValue()) == null ||
1329 +                    (v = get(mk)) == null ||
1330 +                    (mv != v && !mv.equals(v)))
1331 +                    return false;
1332 +            }
1333 +        }
1334 +        return true;
1335 +    }
1336  
1337 <    /** Implementation for put and putIfAbsent */
1338 <    @SuppressWarnings("unchecked") private final V internalPut
1339 <        (K k, V v, boolean onlyIfAbsent) {
1340 <        if (k == null || v == null) throw new NullPointerException();
1341 <        int h = spread(k.hashCode());
1342 <        int len = 0;
1343 <        for (Node<V>[] tab = table;;) {
1344 <            int i, fh; Node<V> f; Object fk; V fv;
1345 <            if (tab == null)
1346 <                tab = initTable();
1347 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1348 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1349 <                    break;                   // no lock when adding to empty bin
1337 >    /**
1338 >     * Stripped-down version of helper class used in previous version,
1339 >     * declared for the sake of serialization compatibility
1340 >     */
1341 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1342 >        private static final long serialVersionUID = 2249069246763182397L;
1343 >        final float loadFactor;
1344 >        Segment(float lf) { this.loadFactor = lf; }
1345 >    }
1346 >
1347 >    /**
1348 >     * Saves the state of the {@code ConcurrentHashMap} instance to a
1349 >     * stream (i.e., serializes it).
1350 >     * @param s the stream
1351 >     * @throws java.io.IOException if an I/O error occurs
1352 >     * @serialData
1353 >     * the key (Object) and value (Object)
1354 >     * for each key-value mapping, followed by a null pair.
1355 >     * The key-value mappings are emitted in no particular order.
1356 >     */
1357 >    private void writeObject(java.io.ObjectOutputStream s)
1358 >        throws java.io.IOException {
1359 >        // For serialization compatibility
1360 >        // Emulate segment calculation from previous version of this class
1361 >        int sshift = 0;
1362 >        int ssize = 1;
1363 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1364 >            ++sshift;
1365 >            ssize <<= 1;
1366 >        }
1367 >        int segmentShift = 32 - sshift;
1368 >        int segmentMask = ssize - 1;
1369 >        @SuppressWarnings("unchecked")
1370 >        Segment<K,V>[] segments = (Segment<K,V>[])
1371 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1372 >        for (int i = 0; i < segments.length; ++i)
1373 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1374 >        s.putFields().put("segments", segments);
1375 >        s.putFields().put("segmentShift", segmentShift);
1376 >        s.putFields().put("segmentMask", segmentMask);
1377 >        s.writeFields();
1378 >
1379 >        Node<K,V>[] t;
1380 >        if ((t = table) != null) {
1381 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1382 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1383 >                s.writeObject(p.key);
1384 >                s.writeObject(p.val);
1385              }
1386 <            else if ((fh = f.hash) < 0) {
1387 <                if ((fk = f.key) instanceof TreeBin) {
1388 <                    TreeBin<V> t = (TreeBin<V>)fk;
1389 <                    V oldVal = null;
1390 <                    t.acquire(0);
1391 <                    try {
1392 <                        if (tabAt(tab, i) == f) {
1393 <                            len = 2;
1394 <                            TreeNode<V> p = t.putTreeNode(h, k, v);
1395 <                            if (p != null) {
1396 <                                oldVal = p.val;
1397 <                                if (!onlyIfAbsent)
1398 <                                    p.val = v;
1399 <                            }
1400 <                        }
1401 <                    } finally {
1402 <                        t.release(0);
1403 <                    }
1404 <                    if (len != 0) {
1405 <                        if (oldVal != null)
1406 <                            return oldVal;
1407 <                        break;
1408 <                    }
1409 <                }
1410 <                else
1411 <                    tab = (Node<V>[])fk;
1386 >        }
1387 >        s.writeObject(null);
1388 >        s.writeObject(null);
1389 >        segments = null; // throw away
1390 >    }
1391 >
1392 >    /**
1393 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1394 >     * @param s the stream
1395 >     * @throws ClassNotFoundException if the class of a serialized object
1396 >     *         could not be found
1397 >     * @throws java.io.IOException if an I/O error occurs
1398 >     */
1399 >    private void readObject(java.io.ObjectInputStream s)
1400 >        throws java.io.IOException, ClassNotFoundException {
1401 >        /*
1402 >         * To improve performance in typical cases, we create nodes
1403 >         * while reading, then place in table once size is known.
1404 >         * However, we must also validate uniqueness and deal with
1405 >         * overpopulated bins while doing so, which requires
1406 >         * specialized versions of putVal mechanics.
1407 >         */
1408 >        sizeCtl = -1; // force exclusion for table construction
1409 >        s.defaultReadObject();
1410 >        long size = 0L;
1411 >        Node<K,V> p = null;
1412 >        for (;;) {
1413 >            @SuppressWarnings("unchecked")
1414 >            K k = (K) s.readObject();
1415 >            @SuppressWarnings("unchecked")
1416 >            V v = (V) s.readObject();
1417 >            if (k != null && v != null) {
1418 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1419 >                ++size;
1420              }
1421 <            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1422 <                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1423 <                return fv;
1421 >            else
1422 >                break;
1423 >        }
1424 >        if (size == 0L)
1425 >            sizeCtl = 0;
1426 >        else {
1427 >            int n;
1428 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1429 >                n = MAXIMUM_CAPACITY;
1430              else {
1431 <                V oldVal = null;
1432 <                synchronized (f) {
1433 <                    if (tabAt(tab, i) == f) {
1434 <                        len = 1;
1435 <                        for (Node<V> e = f;; ++len) {
1436 <                            Object ek; V ev;
1437 <                            if (e.hash == h &&
1438 <                                (ev = e.val) != null &&
1439 <                                ((ek = e.key) == k || k.equals(ek))) {
1440 <                                oldVal = ev;
1441 <                                if (!onlyIfAbsent)
1442 <                                    e.val = v;
1431 >                int sz = (int)size;
1432 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1433 >            }
1434 >            @SuppressWarnings("unchecked")
1435 >            Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1436 >            int mask = n - 1;
1437 >            long added = 0L;
1438 >            while (p != null) {
1439 >                boolean insertAtFront;
1440 >                Node<K,V> next = p.next, first;
1441 >                int h = p.hash, j = h & mask;
1442 >                if ((first = tabAt(tab, j)) == null)
1443 >                    insertAtFront = true;
1444 >                else {
1445 >                    K k = p.key;
1446 >                    if (first.hash < 0) {
1447 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1448 >                        if (t.putTreeVal(h, k, p.val) == null)
1449 >                            ++added;
1450 >                        insertAtFront = false;
1451 >                    }
1452 >                    else {
1453 >                        int binCount = 0;
1454 >                        insertAtFront = true;
1455 >                        Node<K,V> q; K qk;
1456 >                        for (q = first; q != null; q = q.next) {
1457 >                            if (q.hash == h &&
1458 >                                ((qk = q.key) == k ||
1459 >                                 (qk != null && k.equals(qk)))) {
1460 >                                insertAtFront = false;
1461                                  break;
1462                              }
1463 <                            Node<V> last = e;
1464 <                            if ((e = e.next) == null) {
1465 <                                last.next = new Node<V>(h, k, v, null);
1466 <                                if (len >= TREE_THRESHOLD)
1467 <                                    replaceWithTreeBin(tab, i, k);
1468 <                                break;
1463 >                            ++binCount;
1464 >                        }
1465 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1466 >                            insertAtFront = false;
1467 >                            ++added;
1468 >                            p.next = first;
1469 >                            TreeNode<K,V> hd = null, tl = null;
1470 >                            for (q = p; q != null; q = q.next) {
1471 >                                TreeNode<K,V> t = new TreeNode<K,V>
1472 >                                    (q.hash, q.key, q.val, null, null);
1473 >                                if ((t.prev = tl) == null)
1474 >                                    hd = t;
1475 >                                else
1476 >                                    tl.next = t;
1477 >                                tl = t;
1478                              }
1479 +                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1480                          }
1481                      }
1482                  }
1483 <                if (len != 0) {
1484 <                    if (oldVal != null)
1485 <                        return oldVal;
1486 <                    break;
1483 >                if (insertAtFront) {
1484 >                    ++added;
1485 >                    p.next = first;
1486 >                    setTabAt(tab, j, p);
1487                  }
1488 +                p = next;
1489              }
1490 +            table = tab;
1491 +            sizeCtl = n - (n >>> 2);
1492 +            baseCount = added;
1493          }
1305        addCount(1L, len);
1306        return null;
1494      }
1495  
1496 <    /** Implementation for computeIfAbsent */
1497 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1498 <        (K k, Function<? super K, ? extends V> mf) {
1499 <        if (k == null || mf == null)
1496 >    // ConcurrentMap methods
1497 >
1498 >    /**
1499 >     * {@inheritDoc}
1500 >     *
1501 >     * @return the previous value associated with the specified key,
1502 >     *         or {@code null} if there was no mapping for the key
1503 >     * @throws NullPointerException if the specified key or value is null
1504 >     */
1505 >    public V putIfAbsent(K key, V value) {
1506 >        return putVal(key, value, true);
1507 >    }
1508 >
1509 >    /**
1510 >     * {@inheritDoc}
1511 >     *
1512 >     * @throws NullPointerException if the specified key is null
1513 >     */
1514 >    public boolean remove(Object key, Object value) {
1515 >        if (key == null)
1516 >            throw new NullPointerException();
1517 >        return value != null && replaceNode(key, null, value) != null;
1518 >    }
1519 >
1520 >    /**
1521 >     * {@inheritDoc}
1522 >     *
1523 >     * @throws NullPointerException if any of the arguments are null
1524 >     */
1525 >    public boolean replace(K key, V oldValue, V newValue) {
1526 >        if (key == null || oldValue == null || newValue == null)
1527 >            throw new NullPointerException();
1528 >        return replaceNode(key, newValue, oldValue) != null;
1529 >    }
1530 >
1531 >    /**
1532 >     * {@inheritDoc}
1533 >     *
1534 >     * @return the previous value associated with the specified key,
1535 >     *         or {@code null} if there was no mapping for the key
1536 >     * @throws NullPointerException if the specified key or value is null
1537 >     */
1538 >    public V replace(K key, V value) {
1539 >        if (key == null || value == null)
1540 >            throw new NullPointerException();
1541 >        return replaceNode(key, value, null);
1542 >    }
1543 >
1544 >    // Overrides of JDK8+ Map extension method defaults
1545 >
1546 >    /**
1547 >     * Returns the value to which the specified key is mapped, or the
1548 >     * given default value if this map contains no mapping for the
1549 >     * key.
1550 >     *
1551 >     * @param key the key whose associated value is to be returned
1552 >     * @param defaultValue the value to return if this map contains
1553 >     * no mapping for the given key
1554 >     * @return the mapping for the key, if present; else the default value
1555 >     * @throws NullPointerException if the specified key is null
1556 >     */
1557 >    public V getOrDefault(Object key, V defaultValue) {
1558 >        V v;
1559 >        return (v = get(key)) == null ? defaultValue : v;
1560 >    }
1561 >
1562 >    public void forEach(BiConsumer<? super K, ? super V> action) {
1563 >        if (action == null) throw new NullPointerException();
1564 >        Node<K,V>[] t;
1565 >        if ((t = table) != null) {
1566 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1567 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1568 >                action.accept(p.key, p.val);
1569 >            }
1570 >        }
1571 >    }
1572 >
1573 >    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1574 >        if (function == null) throw new NullPointerException();
1575 >        Node<K,V>[] t;
1576 >        if ((t = table) != null) {
1577 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1578 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1579 >                V oldValue = p.val;
1580 >                for (K key = p.key;;) {
1581 >                    V newValue = function.apply(key, oldValue);
1582 >                    if (newValue == null)
1583 >                        throw new NullPointerException();
1584 >                    if (replaceNode(key, newValue, oldValue) != null ||
1585 >                        (oldValue = get(key)) == null)
1586 >                        break;
1587 >                }
1588 >            }
1589 >        }
1590 >    }
1591 >
1592 >    /**
1593 >     * If the specified key is not already associated with a value,
1594 >     * attempts to compute its value using the given mapping function
1595 >     * and enters it into this map unless {@code null}.  The entire
1596 >     * method invocation is performed atomically, so the function is
1597 >     * applied at most once per key.  Some attempted update operations
1598 >     * on this map by other threads may be blocked while computation
1599 >     * is in progress, so the computation should be short and simple,
1600 >     * and must not attempt to update any other mappings of this map.
1601 >     *
1602 >     * @param key key with which the specified value is to be associated
1603 >     * @param mappingFunction the function to compute a value
1604 >     * @return the current (existing or computed) value associated with
1605 >     *         the specified key, or null if the computed value is null
1606 >     * @throws NullPointerException if the specified key or mappingFunction
1607 >     *         is null
1608 >     * @throws IllegalStateException if the computation detectably
1609 >     *         attempts a recursive update to this map that would
1610 >     *         otherwise never complete
1611 >     * @throws RuntimeException or Error if the mappingFunction does so,
1612 >     *         in which case the mapping is left unestablished
1613 >     */
1614 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1615 >        if (key == null || mappingFunction == null)
1616              throw new NullPointerException();
1617 <        int h = spread(k.hashCode());
1617 >        int h = spread(key.hashCode());
1618          V val = null;
1619 <        int len = 0;
1620 <        for (Node<V>[] tab = table;;) {
1621 <            Node<V> f; int i; Object fk;
1622 <            if (tab == null)
1619 >        int binCount = 0;
1620 >        for (Node<K,V>[] tab = table;;) {
1621 >            Node<K,V> f; int n, i, fh;
1622 >            if (tab == null || (n = tab.length) == 0)
1623                  tab = initTable();
1624 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1625 <                Node<V> node = new Node<V>(h, k, null, null);
1626 <                synchronized (node) {
1627 <                    if (casTabAt(tab, i, null, node)) {
1628 <                        len = 1;
1624 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1625 >                Node<K,V> r = new ReservationNode<K,V>();
1626 >                synchronized (r) {
1627 >                    if (casTabAt(tab, i, null, r)) {
1628 >                        binCount = 1;
1629 >                        Node<K,V> node = null;
1630                          try {
1631 <                            if ((val = mf.apply(k)) != null)
1632 <                                node.val = val;
1631 >                            if ((val = mappingFunction.apply(key)) != null)
1632 >                                node = new Node<K,V>(h, key, val, null);
1633                          } finally {
1634 <                            if (val == null)
1331 <                                setTabAt(tab, i, null);
1634 >                            setTabAt(tab, i, node);
1635                          }
1636                      }
1637                  }
1638 <                if (len != 0)
1638 >                if (binCount != 0)
1639                      break;
1640              }
1641 <            else if (f.hash < 0) {
1642 <                if ((fk = f.key) instanceof TreeBin) {
1643 <                    TreeBin<V> t = (TreeBin<V>)fk;
1644 <                    boolean added = false;
1645 <                    t.acquire(0);
1646 <                    try {
1647 <                        if (tabAt(tab, i) == f) {
1648 <                            len = 1;
1649 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1650 <                            if (p != null)
1641 >            else if ((fh = f.hash) == MOVED)
1642 >                tab = helpTransfer(tab, f);
1643 >            else {
1644 >                boolean added = false;
1645 >                synchronized (f) {
1646 >                    if (tabAt(tab, i) == f) {
1647 >                        if (fh >= 0) {
1648 >                            binCount = 1;
1649 >                            for (Node<K,V> e = f;; ++binCount) {
1650 >                                K ek; V ev;
1651 >                                if (e.hash == h &&
1652 >                                    ((ek = e.key) == key ||
1653 >                                     (ek != null && key.equals(ek)))) {
1654 >                                    val = e.val;
1655 >                                    break;
1656 >                                }
1657 >                                Node<K,V> pred = e;
1658 >                                if ((e = e.next) == null) {
1659 >                                    if ((val = mappingFunction.apply(key)) != null) {
1660 >                                        added = true;
1661 >                                        pred.next = new Node<K,V>(h, key, val, null);
1662 >                                    }
1663 >                                    break;
1664 >                                }
1665 >                            }
1666 >                        }
1667 >                        else if (f instanceof TreeBin) {
1668 >                            binCount = 2;
1669 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1670 >                            TreeNode<K,V> r, p;
1671 >                            if ((r = t.root) != null &&
1672 >                                (p = r.findTreeNode(h, key, null)) != null)
1673                                  val = p.val;
1674 <                            else if ((val = mf.apply(k)) != null) {
1674 >                            else if ((val = mappingFunction.apply(key)) != null) {
1675                                  added = true;
1676 <                                len = 2;
1352 <                                t.putTreeNode(h, k, val);
1676 >                                t.putTreeVal(h, key, val);
1677                              }
1678                          }
1355                    } finally {
1356                        t.release(0);
1357                    }
1358                    if (len != 0) {
1359                        if (!added)
1360                            return val;
1361                        break;
1679                      }
1680                  }
1681 <                else
1682 <                    tab = (Node<V>[])fk;
1681 >                if (binCount != 0) {
1682 >                    if (binCount >= TREEIFY_THRESHOLD)
1683 >                        treeifyBin(tab, i);
1684 >                    if (!added)
1685 >                        return val;
1686 >                    break;
1687 >                }
1688              }
1689 +        }
1690 +        if (val != null)
1691 +            addCount(1L, binCount);
1692 +        return val;
1693 +    }
1694 +
1695 +    /**
1696 +     * If the value for the specified key is present, attempts to
1697 +     * compute a new mapping given the key and its current mapped
1698 +     * value.  The entire method invocation is performed atomically.
1699 +     * Some attempted update operations on this map by other threads
1700 +     * may be blocked while computation is in progress, so the
1701 +     * computation should be short and simple, and must not attempt to
1702 +     * update any other mappings of this map.
1703 +     *
1704 +     * @param key key with which a value may be associated
1705 +     * @param remappingFunction the function to compute a value
1706 +     * @return the new value associated with the specified key, or null if none
1707 +     * @throws NullPointerException if the specified key or remappingFunction
1708 +     *         is null
1709 +     * @throws IllegalStateException if the computation detectably
1710 +     *         attempts a recursive update to this map that would
1711 +     *         otherwise never complete
1712 +     * @throws RuntimeException or Error if the remappingFunction does so,
1713 +     *         in which case the mapping is unchanged
1714 +     */
1715 +    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1716 +        if (key == null || remappingFunction == null)
1717 +            throw new NullPointerException();
1718 +        int h = spread(key.hashCode());
1719 +        V val = null;
1720 +        int delta = 0;
1721 +        int binCount = 0;
1722 +        for (Node<K,V>[] tab = table;;) {
1723 +            Node<K,V> f; int n, i, fh;
1724 +            if (tab == null || (n = tab.length) == 0)
1725 +                tab = initTable();
1726 +            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1727 +                break;
1728 +            else if ((fh = f.hash) == MOVED)
1729 +                tab = helpTransfer(tab, f);
1730              else {
1368                for (Node<V> e = f; e != null; e = e.next) { // prescan
1369                    Object ek; V ev;
1370                    if (e.hash == h && (ev = e.val) != null &&
1371                        ((ek = e.key) == k || k.equals(ek)))
1372                        return ev;
1373                }
1374                boolean added = false;
1731                  synchronized (f) {
1732                      if (tabAt(tab, i) == f) {
1733 <                        len = 1;
1734 <                        for (Node<V> e = f;; ++len) {
1735 <                            Object ek; V ev;
1736 <                            if (e.hash == h &&
1737 <                                (ev = e.val) != null &&
1738 <                                ((ek = e.key) == k || k.equals(ek))) {
1739 <                                val = ev;
1740 <                                break;
1733 >                        if (fh >= 0) {
1734 >                            binCount = 1;
1735 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1736 >                                K ek;
1737 >                                if (e.hash == h &&
1738 >                                    ((ek = e.key) == key ||
1739 >                                     (ek != null && key.equals(ek)))) {
1740 >                                    val = remappingFunction.apply(key, e.val);
1741 >                                    if (val != null)
1742 >                                        e.val = val;
1743 >                                    else {
1744 >                                        delta = -1;
1745 >                                        Node<K,V> en = e.next;
1746 >                                        if (pred != null)
1747 >                                            pred.next = en;
1748 >                                        else
1749 >                                            setTabAt(tab, i, en);
1750 >                                    }
1751 >                                    break;
1752 >                                }
1753 >                                pred = e;
1754 >                                if ((e = e.next) == null)
1755 >                                    break;
1756                              }
1757 <                            Node<V> last = e;
1758 <                            if ((e = e.next) == null) {
1759 <                                if ((val = mf.apply(k)) != null) {
1760 <                                    added = true;
1761 <                                    last.next = new Node<V>(h, k, val, null);
1762 <                                    if (len >= TREE_THRESHOLD)
1763 <                                        replaceWithTreeBin(tab, i, k);
1757 >                        }
1758 >                        else if (f instanceof TreeBin) {
1759 >                            binCount = 2;
1760 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1761 >                            TreeNode<K,V> r, p;
1762 >                            if ((r = t.root) != null &&
1763 >                                (p = r.findTreeNode(h, key, null)) != null) {
1764 >                                val = remappingFunction.apply(key, p.val);
1765 >                                if (val != null)
1766 >                                    p.val = val;
1767 >                                else {
1768 >                                    delta = -1;
1769 >                                    if (t.removeTreeNode(p))
1770 >                                        setTabAt(tab, i, untreeify(t.first));
1771                                  }
1394                                break;
1772                              }
1773                          }
1774                      }
1775                  }
1776 <                if (len != 0) {
1400 <                    if (!added)
1401 <                        return val;
1776 >                if (binCount != 0)
1777                      break;
1403                }
1778              }
1779          }
1780 <        if (val != null)
1781 <            addCount(1L, len);
1780 >        if (delta != 0)
1781 >            addCount((long)delta, binCount);
1782          return val;
1783      }
1784  
1785 <    /** Implementation for compute */
1786 <    @SuppressWarnings("unchecked") private final V internalCompute
1787 <        (K k, boolean onlyIfPresent,
1788 <         BiFunction<? super K, ? super V, ? extends V> mf) {
1789 <        if (k == null || mf == null)
1785 >    /**
1786 >     * Attempts to compute a mapping for the specified key and its
1787 >     * current mapped value (or {@code null} if there is no current
1788 >     * mapping). The entire method invocation is performed atomically.
1789 >     * Some attempted update operations on this map by other threads
1790 >     * may be blocked while computation is in progress, so the
1791 >     * computation should be short and simple, and must not attempt to
1792 >     * update any other mappings of this Map.
1793 >     *
1794 >     * @param key key with which the specified value is to be associated
1795 >     * @param remappingFunction the function to compute a value
1796 >     * @return the new value associated with the specified key, or null if none
1797 >     * @throws NullPointerException if the specified key or remappingFunction
1798 >     *         is null
1799 >     * @throws IllegalStateException if the computation detectably
1800 >     *         attempts a recursive update to this map that would
1801 >     *         otherwise never complete
1802 >     * @throws RuntimeException or Error if the remappingFunction does so,
1803 >     *         in which case the mapping is unchanged
1804 >     */
1805 >    public V compute(K key,
1806 >                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1807 >        if (key == null || remappingFunction == null)
1808              throw new NullPointerException();
1809 <        int h = spread(k.hashCode());
1809 >        int h = spread(key.hashCode());
1810          V val = null;
1811          int delta = 0;
1812 <        int len = 0;
1813 <        for (Node<V>[] tab = table;;) {
1814 <            Node<V> f; int i, fh; Object fk;
1815 <            if (tab == null)
1812 >        int binCount = 0;
1813 >        for (Node<K,V>[] tab = table;;) {
1814 >            Node<K,V> f; int n, i, fh;
1815 >            if (tab == null || (n = tab.length) == 0)
1816                  tab = initTable();
1817 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1818 <                if (onlyIfPresent)
1819 <                    break;
1820 <                Node<V> node = new Node<V>(h, k, null, null);
1821 <                synchronized (node) {
1822 <                    if (casTabAt(tab, i, null, node)) {
1817 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1818 >                Node<K,V> r = new ReservationNode<K,V>();
1819 >                synchronized (r) {
1820 >                    if (casTabAt(tab, i, null, r)) {
1821 >                        binCount = 1;
1822 >                        Node<K,V> node = null;
1823                          try {
1824 <                            len = 1;
1433 <                            if ((val = mf.apply(k, null)) != null) {
1434 <                                node.val = val;
1824 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1825                                  delta = 1;
1826 +                                node = new Node<K,V>(h, key, val, null);
1827                              }
1828                          } finally {
1829 <                            if (delta == 0)
1439 <                                setTabAt(tab, i, null);
1829 >                            setTabAt(tab, i, node);
1830                          }
1831                      }
1832                  }
1833 <                if (len != 0)
1833 >                if (binCount != 0)
1834                      break;
1835              }
1836 <            else if ((fh = f.hash) < 0) {
1837 <                if ((fk = f.key) instanceof TreeBin) {
1838 <                    TreeBin<V> t = (TreeBin<V>)fk;
1839 <                    t.acquire(0);
1840 <                    try {
1841 <                        if (tabAt(tab, i) == f) {
1842 <                            len = 1;
1843 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1844 <                            if (p == null && onlyIfPresent)
1845 <                                break;
1836 >            else if ((fh = f.hash) == MOVED)
1837 >                tab = helpTransfer(tab, f);
1838 >            else {
1839 >                synchronized (f) {
1840 >                    if (tabAt(tab, i) == f) {
1841 >                        if (fh >= 0) {
1842 >                            binCount = 1;
1843 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1844 >                                K ek;
1845 >                                if (e.hash == h &&
1846 >                                    ((ek = e.key) == key ||
1847 >                                     (ek != null && key.equals(ek)))) {
1848 >                                    val = remappingFunction.apply(key, e.val);
1849 >                                    if (val != null)
1850 >                                        e.val = val;
1851 >                                    else {
1852 >                                        delta = -1;
1853 >                                        Node<K,V> en = e.next;
1854 >                                        if (pred != null)
1855 >                                            pred.next = en;
1856 >                                        else
1857 >                                            setTabAt(tab, i, en);
1858 >                                    }
1859 >                                    break;
1860 >                                }
1861 >                                pred = e;
1862 >                                if ((e = e.next) == null) {
1863 >                                    val = remappingFunction.apply(key, null);
1864 >                                    if (val != null) {
1865 >                                        delta = 1;
1866 >                                        pred.next =
1867 >                                            new Node<K,V>(h, key, val, null);
1868 >                                    }
1869 >                                    break;
1870 >                                }
1871 >                            }
1872 >                        }
1873 >                        else if (f instanceof TreeBin) {
1874 >                            binCount = 1;
1875 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1876 >                            TreeNode<K,V> r, p;
1877 >                            if ((r = t.root) != null)
1878 >                                p = r.findTreeNode(h, key, null);
1879 >                            else
1880 >                                p = null;
1881                              V pv = (p == null) ? null : p.val;
1882 <                            if ((val = mf.apply(k, pv)) != null) {
1882 >                            val = remappingFunction.apply(key, pv);
1883 >                            if (val != null) {
1884                                  if (p != null)
1885                                      p.val = val;
1886                                  else {
1461                                    len = 2;
1887                                      delta = 1;
1888 <                                    t.putTreeNode(h, k, val);
1888 >                                    t.putTreeVal(h, key, val);
1889                                  }
1890                              }
1891                              else if (p != null) {
1892                                  delta = -1;
1893 <                                t.deleteTreeNode(p);
1894 <                            }
1470 <                        }
1471 <                    } finally {
1472 <                        t.release(0);
1473 <                    }
1474 <                    if (len != 0)
1475 <                        break;
1476 <                }
1477 <                else
1478 <                    tab = (Node<V>[])fk;
1479 <            }
1480 <            else {
1481 <                synchronized (f) {
1482 <                    if (tabAt(tab, i) == f) {
1483 <                        len = 1;
1484 <                        for (Node<V> e = f, pred = null;; ++len) {
1485 <                            Object ek; V ev;
1486 <                            if (e.hash == h &&
1487 <                                (ev = e.val) != null &&
1488 <                                ((ek = e.key) == k || k.equals(ek))) {
1489 <                                val = mf.apply(k, ev);
1490 <                                if (val != null)
1491 <                                    e.val = val;
1492 <                                else {
1493 <                                    delta = -1;
1494 <                                    Node<V> en = e.next;
1495 <                                    if (pred != null)
1496 <                                        pred.next = en;
1497 <                                    else
1498 <                                        setTabAt(tab, i, en);
1499 <                                }
1500 <                                break;
1501 <                            }
1502 <                            pred = e;
1503 <                            if ((e = e.next) == null) {
1504 <                                if (!onlyIfPresent &&
1505 <                                    (val = mf.apply(k, null)) != null) {
1506 <                                    pred.next = new Node<V>(h, k, val, null);
1507 <                                    delta = 1;
1508 <                                    if (len >= TREE_THRESHOLD)
1509 <                                        replaceWithTreeBin(tab, i, k);
1510 <                                }
1511 <                                break;
1893 >                                if (t.removeTreeNode(p))
1894 >                                    setTabAt(tab, i, untreeify(t.first));
1895                              }
1896                          }
1897                      }
1898                  }
1899 <                if (len != 0)
1899 >                if (binCount != 0) {
1900 >                    if (binCount >= TREEIFY_THRESHOLD)
1901 >                        treeifyBin(tab, i);
1902                      break;
1903 +                }
1904              }
1905          }
1906          if (delta != 0)
1907 <            addCount((long)delta, len);
1907 >            addCount((long)delta, binCount);
1908          return val;
1909      }
1910  
1911 <    /** Implementation for merge */
1912 <    @SuppressWarnings("unchecked") private final V internalMerge
1913 <        (K k, V v, BiFunction<? super V, ? super V, ? extends V> mf) {
1914 <        if (k == null || v == null || mf == null)
1911 >    /**
1912 >     * If the specified key is not already associated with a
1913 >     * (non-null) value, associates it with the given value.
1914 >     * Otherwise, replaces the value with the results of the given
1915 >     * remapping function, or removes if {@code null}. The entire
1916 >     * method invocation is performed atomically.  Some attempted
1917 >     * update operations on this map by other threads may be blocked
1918 >     * while computation is in progress, so the computation should be
1919 >     * short and simple, and must not attempt to update any other
1920 >     * mappings of this Map.
1921 >     *
1922 >     * @param key key with which the specified value is to be associated
1923 >     * @param value the value to use if absent
1924 >     * @param remappingFunction the function to recompute a value if present
1925 >     * @return the new value associated with the specified key, or null if none
1926 >     * @throws NullPointerException if the specified key or the
1927 >     *         remappingFunction is null
1928 >     * @throws RuntimeException or Error if the remappingFunction does so,
1929 >     *         in which case the mapping is unchanged
1930 >     */
1931 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1932 >        if (key == null || value == null || remappingFunction == null)
1933              throw new NullPointerException();
1934 <        int h = spread(k.hashCode());
1934 >        int h = spread(key.hashCode());
1935          V val = null;
1936          int delta = 0;
1937 <        int len = 0;
1938 <        for (Node<V>[] tab = table;;) {
1939 <            int i; Node<V> f; Object fk; V fv;
1940 <            if (tab == null)
1937 >        int binCount = 0;
1938 >        for (Node<K,V>[] tab = table;;) {
1939 >            Node<K,V> f; int n, i, fh;
1940 >            if (tab == null || (n = tab.length) == 0)
1941                  tab = initTable();
1942 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1943 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
1942 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1943 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1944                      delta = 1;
1945 <                    val = v;
1945 >                    val = value;
1946                      break;
1947                  }
1948              }
1949 <            else if (f.hash < 0) {
1950 <                if ((fk = f.key) instanceof TreeBin) {
1951 <                    TreeBin<V> t = (TreeBin<V>)fk;
1952 <                    t.acquire(0);
1953 <                    try {
1954 <                        if (tabAt(tab, i) == f) {
1955 <                            len = 1;
1956 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1957 <                            val = (p == null) ? v : mf.apply(p.val, v);
1949 >            else if ((fh = f.hash) == MOVED)
1950 >                tab = helpTransfer(tab, f);
1951 >            else {
1952 >                synchronized (f) {
1953 >                    if (tabAt(tab, i) == f) {
1954 >                        if (fh >= 0) {
1955 >                            binCount = 1;
1956 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1957 >                                K ek;
1958 >                                if (e.hash == h &&
1959 >                                    ((ek = e.key) == key ||
1960 >                                     (ek != null && key.equals(ek)))) {
1961 >                                    val = remappingFunction.apply(e.val, value);
1962 >                                    if (val != null)
1963 >                                        e.val = val;
1964 >                                    else {
1965 >                                        delta = -1;
1966 >                                        Node<K,V> en = e.next;
1967 >                                        if (pred != null)
1968 >                                            pred.next = en;
1969 >                                        else
1970 >                                            setTabAt(tab, i, en);
1971 >                                    }
1972 >                                    break;
1973 >                                }
1974 >                                pred = e;
1975 >                                if ((e = e.next) == null) {
1976 >                                    delta = 1;
1977 >                                    val = value;
1978 >                                    pred.next =
1979 >                                        new Node<K,V>(h, key, val, null);
1980 >                                    break;
1981 >                                }
1982 >                            }
1983 >                        }
1984 >                        else if (f instanceof TreeBin) {
1985 >                            binCount = 2;
1986 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1987 >                            TreeNode<K,V> r = t.root;
1988 >                            TreeNode<K,V> p = (r == null) ? null :
1989 >                                r.findTreeNode(h, key, null);
1990 >                            val = (p == null) ? value :
1991 >                                remappingFunction.apply(p.val, value);
1992                              if (val != null) {
1993                                  if (p != null)
1994                                      p.val = val;
1995                                  else {
1558                                    len = 2;
1996                                      delta = 1;
1997 <                                    t.putTreeNode(h, k, val);
1997 >                                    t.putTreeVal(h, key, val);
1998                                  }
1999                              }
2000                              else if (p != null) {
2001                                  delta = -1;
2002 <                                t.deleteTreeNode(p);
2002 >                                if (t.removeTreeNode(p))
2003 >                                    setTabAt(tab, i, untreeify(t.first));
2004                              }
2005                          }
1568                    } finally {
1569                        t.release(0);
2006                      }
1571                    if (len != 0)
1572                        break;
2007                  }
2008 <                else
2009 <                    tab = (Node<V>[])fk;
2010 <            }
1577 <            else {
1578 <                synchronized (f) {
1579 <                    if (tabAt(tab, i) == f) {
1580 <                        len = 1;
1581 <                        for (Node<V> e = f, pred = null;; ++len) {
1582 <                            Object ek; V ev;
1583 <                            if (e.hash == h &&
1584 <                                (ev = e.val) != null &&
1585 <                                ((ek = e.key) == k || k.equals(ek))) {
1586 <                                val = mf.apply(ev, v);
1587 <                                if (val != null)
1588 <                                    e.val = val;
1589 <                                else {
1590 <                                    delta = -1;
1591 <                                    Node<V> en = e.next;
1592 <                                    if (pred != null)
1593 <                                        pred.next = en;
1594 <                                    else
1595 <                                        setTabAt(tab, i, en);
1596 <                                }
1597 <                                break;
1598 <                            }
1599 <                            pred = e;
1600 <                            if ((e = e.next) == null) {
1601 <                                val = v;
1602 <                                pred.next = new Node<V>(h, k, val, null);
1603 <                                delta = 1;
1604 <                                if (len >= TREE_THRESHOLD)
1605 <                                    replaceWithTreeBin(tab, i, k);
1606 <                                break;
1607 <                            }
1608 <                        }
1609 <                    }
1610 <                }
1611 <                if (len != 0)
2008 >                if (binCount != 0) {
2009 >                    if (binCount >= TREEIFY_THRESHOLD)
2010 >                        treeifyBin(tab, i);
2011                      break;
2012 +                }
2013              }
2014          }
2015          if (delta != 0)
2016 <            addCount((long)delta, len);
2016 >            addCount((long)delta, binCount);
2017          return val;
2018      }
2019  
2020 <    /** Implementation for putAll */
2021 <    @SuppressWarnings("unchecked") private final void internalPutAll
2022 <        (Map<? extends K, ? extends V> m) {
2023 <        tryPresize(m.size());
2024 <        long delta = 0L;     // number of uncommitted additions
2025 <        boolean npe = false; // to throw exception on exit for nulls
2026 <        try {                // to clean up counts on other exceptions
2027 <            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
2028 <                Object k; V v;
2029 <                if (entry == null || (k = entry.getKey()) == null ||
2030 <                    (v = entry.getValue()) == null) {
2031 <                    npe = true;
2032 <                    break;
2033 <                }
2034 <                int h = spread(k.hashCode());
2035 <                for (Node<V>[] tab = table;;) {
2036 <                    int i; Node<V> f; int fh; Object fk;
2037 <                    if (tab == null)
2038 <                        tab = initTable();
2039 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
2040 <                        if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
2041 <                            ++delta;
2042 <                            break;
2043 <                        }
2044 <                    }
2045 <                    else if ((fh = f.hash) < 0) {
2046 <                        if ((fk = f.key) instanceof TreeBin) {
2047 <                            TreeBin<V> t = (TreeBin<V>)fk;
2048 <                            boolean validated = false;
2049 <                            t.acquire(0);
2050 <                            try {
2051 <                                if (tabAt(tab, i) == f) {
2052 <                                    validated = true;
2053 <                                    TreeNode<V> p = t.getTreeNode(h, k, t.root);
2054 <                                    if (p != null)
2055 <                                        p.val = v;
2056 <                                    else {
2057 <                                        t.putTreeNode(h, k, v);
2058 <                                        ++delta;
2059 <                                    }
2060 <                                }
2061 <                            } finally {
2062 <                                t.release(0);
2063 <                            }
2064 <                            if (validated)
2065 <                                break;
2020 >    // Hashtable legacy methods
2021 >
2022 >    /**
2023 >     * Legacy method testing if some key maps into the specified value
2024 >     * in this table.
2025 >     *
2026 >     * @deprecated This method is identical in functionality to
2027 >     * {@link #containsValue(Object)}, and exists solely to ensure
2028 >     * full compatibility with class {@link java.util.Hashtable},
2029 >     * which supported this method prior to introduction of the
2030 >     * Java Collections framework.
2031 >     *
2032 >     * @param  value a value to search for
2033 >     * @return {@code true} if and only if some key maps to the
2034 >     *         {@code value} argument in this table as
2035 >     *         determined by the {@code equals} method;
2036 >     *         {@code false} otherwise
2037 >     * @throws NullPointerException if the specified value is null
2038 >     */
2039 >    @Deprecated
2040 >    public boolean contains(Object value) {
2041 >        return containsValue(value);
2042 >    }
2043 >
2044 >    /**
2045 >     * Returns an enumeration of the keys in this table.
2046 >     *
2047 >     * @return an enumeration of the keys in this table
2048 >     * @see #keySet()
2049 >     */
2050 >    public Enumeration<K> keys() {
2051 >        Node<K,V>[] t;
2052 >        int f = (t = table) == null ? 0 : t.length;
2053 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2054 >    }
2055 >
2056 >    /**
2057 >     * Returns an enumeration of the values in this table.
2058 >     *
2059 >     * @return an enumeration of the values in this table
2060 >     * @see #values()
2061 >     */
2062 >    public Enumeration<V> elements() {
2063 >        Node<K,V>[] t;
2064 >        int f = (t = table) == null ? 0 : t.length;
2065 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2066 >    }
2067 >
2068 >    // ConcurrentHashMap-only methods
2069 >
2070 >    /**
2071 >     * Returns the number of mappings. This method should be used
2072 >     * instead of {@link #size} because a ConcurrentHashMap may
2073 >     * contain more mappings than can be represented as an int. The
2074 >     * value returned is an estimate; the actual count may differ if
2075 >     * there are concurrent insertions or removals.
2076 >     *
2077 >     * @return the number of mappings
2078 >     * @since 1.8
2079 >     */
2080 >    public long mappingCount() {
2081 >        long n = sumCount();
2082 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2083 >    }
2084 >
2085 >    /**
2086 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2087 >     * from the given type to {@code Boolean.TRUE}.
2088 >     *
2089 >     * @param <K> the element type of the returned set
2090 >     * @return the new set
2091 >     * @since 1.8
2092 >     */
2093 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2094 >        return new KeySetView<K,Boolean>
2095 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2096 >    }
2097 >
2098 >    /**
2099 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2100 >     * from the given type to {@code Boolean.TRUE}.
2101 >     *
2102 >     * @param initialCapacity The implementation performs internal
2103 >     * sizing to accommodate this many elements.
2104 >     * @param <K> the element type of the returned set
2105 >     * @return the new set
2106 >     * @throws IllegalArgumentException if the initial capacity of
2107 >     * elements is negative
2108 >     * @since 1.8
2109 >     */
2110 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2111 >        return new KeySetView<K,Boolean>
2112 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2113 >    }
2114 >
2115 >    /**
2116 >     * Returns a {@link Set} view of the keys in this map, using the
2117 >     * given common mapped value for any additions (i.e., {@link
2118 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2119 >     * This is of course only appropriate if it is acceptable to use
2120 >     * the same value for all additions from this view.
2121 >     *
2122 >     * @param mappedValue the mapped value to use for any additions
2123 >     * @return the set view
2124 >     * @throws NullPointerException if the mappedValue is null
2125 >     */
2126 >    public KeySetView<K,V> keySet(V mappedValue) {
2127 >        if (mappedValue == null)
2128 >            throw new NullPointerException();
2129 >        return new KeySetView<K,V>(this, mappedValue);
2130 >    }
2131 >
2132 >    /* ---------------- Special Nodes -------------- */
2133 >
2134 >    /**
2135 >     * A node inserted at head of bins during transfer operations.
2136 >     */
2137 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2138 >        final Node<K,V>[] nextTable;
2139 >        ForwardingNode(Node<K,V>[] tab) {
2140 >            super(MOVED, null, null, null);
2141 >            this.nextTable = tab;
2142 >        }
2143 >
2144 >        Node<K,V> find(int h, Object k) {
2145 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2146 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2147 >                Node<K,V> e; int n;
2148 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2149 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2150 >                    return null;
2151 >                for (;;) {
2152 >                    int eh; K ek;
2153 >                    if ((eh = e.hash) == h &&
2154 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2155 >                        return e;
2156 >                    if (eh < 0) {
2157 >                        if (e instanceof ForwardingNode) {
2158 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2159 >                            continue outer;
2160                          }
2161                          else
2162 <                            tab = (Node<V>[])fk;
1669 <                    }
1670 <                    else {
1671 <                        int len = 0;
1672 <                        synchronized (f) {
1673 <                            if (tabAt(tab, i) == f) {
1674 <                                len = 1;
1675 <                                for (Node<V> e = f;; ++len) {
1676 <                                    Object ek; V ev;
1677 <                                    if (e.hash == h &&
1678 <                                        (ev = e.val) != null &&
1679 <                                        ((ek = e.key) == k || k.equals(ek))) {
1680 <                                        e.val = v;
1681 <                                        break;
1682 <                                    }
1683 <                                    Node<V> last = e;
1684 <                                    if ((e = e.next) == null) {
1685 <                                        ++delta;
1686 <                                        last.next = new Node<V>(h, k, v, null);
1687 <                                        if (len >= TREE_THRESHOLD)
1688 <                                            replaceWithTreeBin(tab, i, k);
1689 <                                        break;
1690 <                                    }
1691 <                                }
1692 <                            }
1693 <                        }
1694 <                        if (len != 0) {
1695 <                            if (len > 1) {
1696 <                                addCount(delta, len);
1697 <                                delta = 0L;
1698 <                            }
1699 <                            break;
1700 <                        }
2162 >                            return e.find(h, k);
2163                      }
2164 +                    if ((e = e.next) == null)
2165 +                        return null;
2166                  }
2167              }
1704        } finally {
1705            if (delta != 0L)
1706                addCount(delta, 2);
2168          }
1708        if (npe)
1709            throw new NullPointerException();
2169      }
2170  
2171      /**
2172 <     * Implementation for clear. Steps through each bin, removing all
1714 <     * nodes.
2172 >     * A place-holder node used in computeIfAbsent and compute
2173       */
2174 <    @SuppressWarnings("unchecked") private final void internalClear() {
2175 <        long delta = 0L; // negative number of deletions
2176 <        int i = 0;
2177 <        Node<V>[] tab = table;
2178 <        while (tab != null && i < tab.length) {
2179 <            Node<V> f = tabAt(tab, i);
2180 <            if (f == null)
1723 <                ++i;
1724 <            else if (f.hash < 0) {
1725 <                Object fk;
1726 <                if ((fk = f.key) instanceof TreeBin) {
1727 <                    TreeBin<V> t = (TreeBin<V>)fk;
1728 <                    t.acquire(0);
1729 <                    try {
1730 <                        if (tabAt(tab, i) == f) {
1731 <                            for (Node<V> p = t.first; p != null; p = p.next) {
1732 <                                if (p.val != null) { // (currently always true)
1733 <                                    p.val = null;
1734 <                                    --delta;
1735 <                                }
1736 <                            }
1737 <                            t.first = null;
1738 <                            t.root = null;
1739 <                            ++i;
1740 <                        }
1741 <                    } finally {
1742 <                        t.release(0);
1743 <                    }
1744 <                }
1745 <                else
1746 <                    tab = (Node<V>[])fk;
1747 <            }
1748 <            else {
1749 <                synchronized (f) {
1750 <                    if (tabAt(tab, i) == f) {
1751 <                        for (Node<V> e = f; e != null; e = e.next) {
1752 <                            if (e.val != null) {  // (currently always true)
1753 <                                e.val = null;
1754 <                                --delta;
1755 <                            }
1756 <                        }
1757 <                        setTabAt(tab, i, null);
1758 <                        ++i;
1759 <                    }
1760 <                }
1761 <            }
2174 >    static final class ReservationNode<K,V> extends Node<K,V> {
2175 >        ReservationNode() {
2176 >            super(RESERVED, null, null, null);
2177 >        }
2178 >
2179 >        Node<K,V> find(int h, Object k) {
2180 >            return null;
2181          }
1763        if (delta != 0L)
1764            addCount(delta, -1);
2182      }
2183  
2184      /* ---------------- Table Initialization and Resizing -------------- */
2185  
2186      /**
2187 <     * Returns a power of two table size for the given desired capacity.
2188 <     * See Hackers Delight, sec 3.2
2187 >     * Returns the stamp bits for resizing a table of size n.
2188 >     * Must be negative when shifted left by RESIZE_STAMP_SHIFT.
2189       */
2190 <    private static final int tableSizeFor(int c) {
2191 <        int n = c - 1;
1775 <        n |= n >>> 1;
1776 <        n |= n >>> 2;
1777 <        n |= n >>> 4;
1778 <        n |= n >>> 8;
1779 <        n |= n >>> 16;
1780 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
2190 >    static final int resizeStamp(int n) {
2191 >        return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
2192      }
2193  
2194      /**
2195       * Initializes table, using the size recorded in sizeCtl.
2196       */
2197 <    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
2198 <        Node<V>[] tab; int sc;
2199 <        while ((tab = table) == null) {
2197 >    private final Node<K,V>[] initTable() {
2198 >        Node<K,V>[] tab; int sc;
2199 >        while ((tab = table) == null || tab.length == 0) {
2200              if ((sc = sizeCtl) < 0)
2201                  Thread.yield(); // lost initialization race; just spin
2202              else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2203                  try {
2204 <                    if ((tab = table) == null) {
2204 >                    if ((tab = table) == null || tab.length == 0) {
2205                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2206 <                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2207 <                        table = tab = (Node<V>[])tb;
2206 >                        @SuppressWarnings("unchecked")
2207 >                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2208 >                        table = tab = nt;
2209                          sc = n - (n >>> 2);
2210                      }
2211                  } finally {
# Line 1816 | Line 2228 | public class ConcurrentHashMap<K, V>
2228       * @param check if <0, don't check resize, if <= 1 only check if uncontended
2229       */
2230      private final void addCount(long x, int check) {
2231 <        Cell[] as; long b, s;
2231 >        CounterCell[] as; long b, s;
2232          if ((as = counterCells) != null ||
2233              !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2234 <            Cell a; long v; int m;
2234 >            CounterCell a; long v; int m;
2235              boolean uncontended = true;
2236              if (as == null || (m = as.length - 1) < 0 ||
2237                  (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
# Line 1833 | Line 2245 | public class ConcurrentHashMap<K, V>
2245              s = sumCount();
2246          }
2247          if (check >= 0) {
2248 <            Node<V>[] tab, nt; int sc;
2248 >            Node<K,V>[] tab, nt; int n, sc;
2249              while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2250 <                   tab.length < MAXIMUM_CAPACITY) {
2250 >                   (n = tab.length) < MAXIMUM_CAPACITY) {
2251 >                int rs = resizeStamp(n);
2252                  if (sc < 0) {
2253 <                    if (sc == -1 || transferIndex <= transferOrigin ||
2254 <                        (nt = nextTable) == null)
2253 >                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2254 >                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
2255 >                        transferIndex <= 0)
2256                          break;
2257 <                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2257 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
2258                          transfer(tab, nt);
2259                  }
2260 <                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2260 >                else if (U.compareAndSwapInt(this, SIZECTL, sc,
2261 >                                             (rs << RESIZE_STAMP_SHIFT) + 2))
2262                      transfer(tab, null);
2263                  s = sumCount();
2264              }
# Line 1851 | Line 2266 | public class ConcurrentHashMap<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 (tab != null && (f instanceof ForwardingNode) &&
2274 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2275 +            int rs = resizeStamp(tab.length);
2276 +            while (nextTab == nextTable && table == tab &&
2277 +                   (sc = sizeCtl) < 0) {
2278 +                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2279 +                    sc == rs + MAX_RESIZERS || transferIndex <= 0)
2280 +                    break;
2281 +                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
2282 +                    transfer(tab, nextTab);
2283 +                    break;
2284 +                }
2285 +            }
2286 +            return nextTab;
2287 +        }
2288 +        return table;
2289 +    }
2290 +
2291 +    /**
2292       * Tries to presize table to accommodate the given number of elements.
2293       *
2294       * @param size number of elements (doesn't need to be perfectly accurate)
2295       */
2296 <    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
2296 >    private final void tryPresize(int size) {
2297          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2298              tableSizeFor(size + (size >>> 1) + 1);
2299          int sc;
2300          while ((sc = sizeCtl) >= 0) {
2301 <            Node<V>[] tab = table; int n;
2301 >            Node<K,V>[] tab = table; int n;
2302              if (tab == null || (n = tab.length) == 0) {
2303                  n = (sc > c) ? sc : c;
2304                  if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2305                      try {
2306                          if (table == tab) {
2307 <                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2308 <                            table = (Node<V>[])tb;
2307 >                            @SuppressWarnings("unchecked")
2308 >                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2309 >                            table = nt;
2310                              sc = n - (n >>> 2);
2311                          }
2312                      } finally {
# Line 1877 | Line 2316 | public class ConcurrentHashMap<K, V>
2316              }
2317              else if (c <= sc || n >= MAXIMUM_CAPACITY)
2318                  break;
2319 <            else if (tab == table &&
2320 <                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2321 <                transfer(tab, null);
2319 >            else if (tab == table) {
2320 >                int rs = resizeStamp(n);
2321 >                if (sc < 0) {
2322 >                    Node<K,V>[] nt;
2323 >                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2324 >                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
2325 >                        transferIndex <= 0)
2326 >                        break;
2327 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
2328 >                        transfer(tab, nt);
2329 >                }
2330 >                else if (U.compareAndSwapInt(this, SIZECTL, sc,
2331 >                                             (rs << RESIZE_STAMP_SHIFT) + 2))
2332 >                    transfer(tab, null);
2333 >            }
2334          }
2335      }
2336  
# Line 1887 | Line 2338 | public class ConcurrentHashMap<K, V>
2338       * Moves and/or copies the nodes in each bin to new table. See
2339       * above for explanation.
2340       */
2341 <    @SuppressWarnings("unchecked") private final void transfer
1891 <        (Node<V>[] tab, Node<V>[] nextTab) {
2341 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2342          int n = tab.length, stride;
2343          if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2344              stride = MIN_TRANSFER_STRIDE; // subdivide range
2345          if (nextTab == null) {            // initiating
2346              try {
2347 <                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
2348 <                nextTab = (Node<V>[])tb;
2347 >                @SuppressWarnings("unchecked")
2348 >                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
2349 >                nextTab = nt;
2350              } catch (Throwable ex) {      // try to cope with OOME
2351                  sizeCtl = Integer.MAX_VALUE;
2352                  return;
2353              }
2354              nextTable = nextTab;
1904            transferOrigin = n;
2355              transferIndex = n;
1906            Node<V> rev = new Node<V>(MOVED, tab, null, null);
1907            for (int k = n; k > 0;) {    // progressively reveal ready slots
1908                int nextk = (k > stride) ? k - stride : 0;
1909                for (int m = nextk; m < k; ++m)
1910                    nextTab[m] = rev;
1911                for (int m = n + nextk; m < n + k; ++m)
1912                    nextTab[m] = rev;
1913                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
1914            }
2356          }
2357          int nextn = nextTab.length;
2358 <        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2358 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2359          boolean advance = true;
2360 +        boolean finishing = false; // to ensure sweep before committing nextTab
2361          for (int i = 0, bound = 0;;) {
2362 <            int nextIndex, nextBound; Node<V> f; Object fk;
2362 >            Node<K,V> f; int fh;
2363              while (advance) {
2364 <                if (--i >= bound)
2364 >                int nextIndex, nextBound;
2365 >                if (--i >= bound || finishing)
2366                      advance = false;
2367 <                else if ((nextIndex = transferIndex) <= transferOrigin) {
2367 >                else if ((nextIndex = transferIndex) <= 0) {
2368                      i = -1;
2369                      advance = false;
2370                  }
# Line 1935 | Line 2378 | public class ConcurrentHashMap<K, V>
2378                  }
2379              }
2380              if (i < 0 || i >= n || i + n >= nextn) {
2381 <                for (int sc;;) {
2382 <                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2383 <                        if (sc == -1) {
2384 <                            nextTable = null;
2385 <                            table = nextTab;
2386 <                            sizeCtl = (n << 1) - (n >>> 1);
1944 <                        }
1945 <                        return;
1946 <                    }
2381 >                int sc;
2382 >                if (finishing) {
2383 >                    nextTable = null;
2384 >                    table = nextTab;
2385 >                    sizeCtl = (n << 1) - (n >>> 1);
2386 >                    return;
2387                  }
2388 <            }
2389 <            else if ((f = tabAt(tab, i)) == null) {
2390 <                if (casTabAt(tab, i, null, fwd)) {
2391 <                    setTabAt(nextTab, i, null);
2392 <                    setTabAt(nextTab, i + n, null);
1953 <                    advance = true;
2388 >                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
2389 >                    if ((sc - 2) != resizeStamp(n))
2390 >                        return;
2391 >                    finishing = advance = true;
2392 >                    i = n; // recheck before commit
2393                  }
2394              }
2395 <            else if (f.hash >= 0) {
2395 >            else if ((f = tabAt(tab, i)) == null)
2396 >                advance = casTabAt(tab, i, null, fwd);
2397 >            else if ((fh = f.hash) == MOVED)
2398 >                advance = true; // already processed
2399 >            else {
2400                  synchronized (f) {
2401                      if (tabAt(tab, i) == f) {
2402 <                        int runBit = f.hash & n;
2403 <                        Node<V> lastRun = f, lo = null, hi = null;
2404 <                        for (Node<V> p = f.next; p != null; p = p.next) {
2405 <                            int b = p.hash & n;
2406 <                            if (b != runBit) {
2407 <                                runBit = b;
2408 <                                lastRun = p;
2402 >                        Node<K,V> ln, hn;
2403 >                        if (fh >= 0) {
2404 >                            int runBit = fh & n;
2405 >                            Node<K,V> lastRun = f;
2406 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2407 >                                int b = p.hash & n;
2408 >                                if (b != runBit) {
2409 >                                    runBit = b;
2410 >                                    lastRun = p;
2411 >                                }
2412                              }
2413 <                        }
2414 <                        if (runBit == 0)
2415 <                            lo = lastRun;
1970 <                        else
1971 <                            hi = lastRun;
1972 <                        for (Node<V> p = f; p != lastRun; p = p.next) {
1973 <                            int ph = p.hash;
1974 <                            Object pk = p.key; V pv = p.val;
1975 <                            if ((ph & n) == 0)
1976 <                                lo = new Node<V>(ph, pk, pv, lo);
1977 <                            else
1978 <                                hi = new Node<V>(ph, pk, pv, hi);
1979 <                        }
1980 <                        setTabAt(nextTab, i, lo);
1981 <                        setTabAt(nextTab, i + n, hi);
1982 <                        setTabAt(tab, i, fwd);
1983 <                        advance = true;
1984 <                    }
1985 <                }
1986 <            }
1987 <            else if ((fk = f.key) instanceof TreeBin) {
1988 <                TreeBin<V> t = (TreeBin<V>)fk;
1989 <                t.acquire(0);
1990 <                try {
1991 <                    if (tabAt(tab, i) == f) {
1992 <                        TreeBin<V> lt = new TreeBin<V>();
1993 <                        TreeBin<V> ht = new TreeBin<V>();
1994 <                        int lc = 0, hc = 0;
1995 <                        for (Node<V> e = t.first; e != null; e = e.next) {
1996 <                            int h = e.hash;
1997 <                            Object k = e.key; V v = e.val;
1998 <                            if ((h & n) == 0) {
1999 <                                ++lc;
2000 <                                lt.putTreeNode(h, k, v);
2413 >                            if (runBit == 0) {
2414 >                                ln = lastRun;
2415 >                                hn = null;
2416                              }
2417                              else {
2418 <                                ++hc;
2419 <                                ht.putTreeNode(h, k, v);
2418 >                                hn = lastRun;
2419 >                                ln = null;
2420                              }
2421 +                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2422 +                                int ph = p.hash; K pk = p.key; V pv = p.val;
2423 +                                if ((ph & n) == 0)
2424 +                                    ln = new Node<K,V>(ph, pk, pv, ln);
2425 +                                else
2426 +                                    hn = new Node<K,V>(ph, pk, pv, hn);
2427 +                            }
2428 +                            setTabAt(nextTab, i, ln);
2429 +                            setTabAt(nextTab, i + n, hn);
2430 +                            setTabAt(tab, i, fwd);
2431 +                            advance = true;
2432                          }
2433 <                        Node<V> ln, hn; // throw away trees if too small
2434 <                        if (lc < TREE_THRESHOLD) {
2435 <                            ln = null;
2436 <                            for (Node<V> p = lt.first; p != null; p = p.next)
2437 <                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2438 <                        }
2439 <                        else
2440 <                            ln = new Node<V>(MOVED, lt, null, null);
2441 <                        setTabAt(nextTab, i, ln);
2442 <                        if (hc < TREE_THRESHOLD) {
2443 <                            hn = null;
2444 <                            for (Node<V> p = ht.first; p != null; p = p.next)
2445 <                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2433 >                        else if (f instanceof TreeBin) {
2434 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2435 >                            TreeNode<K,V> lo = null, loTail = null;
2436 >                            TreeNode<K,V> hi = null, hiTail = null;
2437 >                            int lc = 0, hc = 0;
2438 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2439 >                                int h = e.hash;
2440 >                                TreeNode<K,V> p = new TreeNode<K,V>
2441 >                                    (h, e.key, e.val, null, null);
2442 >                                if ((h & n) == 0) {
2443 >                                    if ((p.prev = loTail) == null)
2444 >                                        lo = p;
2445 >                                    else
2446 >                                        loTail.next = p;
2447 >                                    loTail = p;
2448 >                                    ++lc;
2449 >                                }
2450 >                                else {
2451 >                                    if ((p.prev = hiTail) == null)
2452 >                                        hi = p;
2453 >                                    else
2454 >                                        hiTail.next = p;
2455 >                                    hiTail = p;
2456 >                                    ++hc;
2457 >                                }
2458 >                            }
2459 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2460 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2461 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2462 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2463 >                            setTabAt(nextTab, i, ln);
2464 >                            setTabAt(nextTab, i + n, hn);
2465 >                            setTabAt(tab, i, fwd);
2466 >                            advance = true;
2467                          }
2021                        else
2022                            hn = new Node<V>(MOVED, ht, null, null);
2023                        setTabAt(nextTab, i + n, hn);
2024                        setTabAt(tab, i, fwd);
2025                        advance = true;
2468                      }
2027                } finally {
2028                    t.release(0);
2469                  }
2470              }
2031            else
2032                advance = true; // already processed
2471          }
2472      }
2473  
2474      /* ---------------- Counter support -------------- */
2475  
2476 +    /**
2477 +     * A padded cell for distributing counts.  Adapted from LongAdder
2478 +     * and Striped64.  See their internal docs for explanation.
2479 +     */
2480 +    @sun.misc.Contended static final class CounterCell {
2481 +        volatile long value;
2482 +        CounterCell(long x) { value = x; }
2483 +    }
2484 +
2485      final long sumCount() {
2486 <        Cell[] as = counterCells; Cell a;
2486 >        CounterCell[] as = counterCells; CounterCell a;
2487          long sum = baseCount;
2488          if (as != null) {
2489              for (int i = 0; i < as.length; ++i) {
# Line 2057 | Line 2504 | public class ConcurrentHashMap<K, V>
2504          }
2505          boolean collide = false;                // True if last slot nonempty
2506          for (;;) {
2507 <            Cell[] as; Cell a; int n; long v;
2507 >            CounterCell[] as; CounterCell a; int n; long v;
2508              if ((as = counterCells) != null && (n = as.length) > 0) {
2509                  if ((a = as[(n - 1) & h]) == null) {
2510                      if (cellsBusy == 0) {            // Try to attach new Cell
2511 <                        Cell r = new Cell(x); // Optimistic create
2511 >                        CounterCell r = new CounterCell(x); // Optimistic create
2512                          if (cellsBusy == 0 &&
2513                              U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2514                              boolean created = false;
2515                              try {               // Recheck under lock
2516 <                                Cell[] rs; int m, j;
2516 >                                CounterCell[] rs; int m, j;
2517                                  if ((rs = counterCells) != null &&
2518                                      (m = rs.length) > 0 &&
2519                                      rs[j = (m - 1) & h] == null) {
# Line 2095 | Line 2542 | public class ConcurrentHashMap<K, V>
2542                           U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2543                      try {
2544                          if (counterCells == as) {// Expand table unless stale
2545 <                            Cell[] rs = new Cell[n << 1];
2545 >                            CounterCell[] rs = new CounterCell[n << 1];
2546                              for (int i = 0; i < n; ++i)
2547                                  rs[i] = as[i];
2548                              counterCells = rs;
# Line 2113 | Line 2560 | public class ConcurrentHashMap<K, V>
2560                  boolean init = false;
2561                  try {                           // Initialize table
2562                      if (counterCells == as) {
2563 <                        Cell[] rs = new Cell[2];
2564 <                        rs[h & 1] = new Cell(x);
2563 >                        CounterCell[] rs = new CounterCell[2];
2564 >                        rs[h & 1] = new CounterCell(x);
2565                          counterCells = rs;
2566                          init = true;
2567                      }
# Line 2129 | Line 2576 | public class ConcurrentHashMap<K, V>
2576          }
2577      }
2578  
2579 <    /* ----------------Table Traversal -------------- */
2579 >    /* ---------------- Conversion from/to TreeBins -------------- */
2580  
2581      /**
2582 <     * Encapsulates traversal for methods such as containsValue; also
2583 <     * serves as a base class for other iterators and bulk tasks.
2584 <     *
2585 <     * At each step, the iterator snapshots the key ("nextKey") and
2586 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2587 <     * snapshot, has a non-null user value). Because val fields can
2588 <     * change (including to null, indicating deletion), field nextVal
2589 <     * might not be accurate at point of use, but still maintains the
2590 <     * weak consistency property of holding a value that was once
2591 <     * valid. To support iterator.remove, the nextKey field is not
2592 <     * updated (nulled out) when the iterator cannot advance.
2593 <     *
2594 <     * Internal traversals directly access these fields, as in:
2595 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2596 <     *
2597 <     * Exported iterators must track whether the iterator has advanced
2598 <     * (in hasNext vs next) (by setting/checking/nulling field
2599 <     * nextVal), and then extract key, value, or key-value pairs as
2600 <     * return values of next().
2601 <     *
2602 <     * The iterator visits once each still-valid node that was
2156 <     * reachable upon iterator construction. It might miss some that
2157 <     * were added to a bin after the bin was visited, which is OK wrt
2158 <     * consistency guarantees. Maintaining this property in the face
2159 <     * of possible ongoing resizes requires a fair amount of
2160 <     * bookkeeping state that is difficult to optimize away amidst
2161 <     * volatile accesses.  Even so, traversal maintains reasonable
2162 <     * throughput.
2163 <     *
2164 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2165 <     * However, if the table has been resized, then all future steps
2166 <     * must traverse both the bin at the current index as well as at
2167 <     * (index + baseSize); and so on for further resizings. To
2168 <     * paranoically cope with potential sharing by users of iterators
2169 <     * across threads, iteration terminates if a bounds checks fails
2170 <     * for a table read.
2171 <     *
2172 <     * This class supports both Spliterator-based traversal and
2173 <     * CountedCompleter-based bulk tasks. The same "batch" field is
2174 <     * used, but in slightly different ways, in the two cases.  For
2175 <     * Spliterators, it is a saturating (at Integer.MAX_VALUE)
2176 <     * estimate of element coverage. For CHM tasks, it is a pre-scaled
2177 <     * size that halves down to zero for leaf tasks, that is only
2178 <     * computed upon execution of the task. (Tasks can be submitted to
2179 <     * any pool, of any size, so we don't know scale factors until
2180 <     * running.)
2181 <     *
2182 <     * This class extends CountedCompleter to streamline parallel
2183 <     * iteration in bulk operations. This adds only a few fields of
2184 <     * space overhead, which is small enough in cases where it is not
2185 <     * needed to not worry about it.  Because CountedCompleter is
2186 <     * Serializable, but iterators need not be, we need to add warning
2187 <     * suppressions.
2188 <     */
2189 <    @SuppressWarnings("serial") static class Traverser<K,V,R>
2190 <        extends CountedCompleter<R> {
2191 <        final ConcurrentHashMap<K, V> map;
2192 <        Node<V> next;        // the next entry to use
2193 <        K nextKey;           // cached key field of next
2194 <        V nextVal;           // cached val field of next
2195 <        Node<V>[] tab;       // current table; updated if resized
2196 <        int index;           // index of bin to use next
2197 <        int baseIndex;       // current index of initial table
2198 <        int baseLimit;       // index bound for initial table
2199 <        int baseSize;        // initial table size
2200 <        int batch;           // split control
2201 <        /** Creates iterator for all entries in the table. */
2202 <        Traverser(ConcurrentHashMap<K, V> map) {
2203 <            this.map = map;
2204 <            Node<V>[] t;
2205 <            if ((t = tab = map.table) != null)
2206 <                baseLimit = baseSize = t.length;
2207 <        }
2208 <
2209 <        /** Task constructor */
2210 <        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it, int batch) {
2211 <            super(it);
2212 <            this.map = map;
2213 <            this.batch = batch; // -1 if unknown
2214 <            if (it == null) {
2215 <                Node<V>[] t;
2216 <                if ((t = tab = map.table) != null)
2217 <                    baseLimit = baseSize = t.length;
2218 <            }
2219 <            else { // split parent
2220 <                this.tab = it.tab;
2221 <                this.baseSize = it.baseSize;
2222 <                int hi = this.baseLimit = it.baseLimit;
2223 <                it.baseLimit = this.index = this.baseIndex =
2224 <                    (hi + it.baseIndex + 1) >>> 1;
2225 <            }
2226 <        }
2227 <
2228 <        /** Spliterator constructor */
2229 <        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it) {
2230 <            super(it);
2231 <            this.map = map;
2232 <            if (it == null) {
2233 <                Node<V>[] t;
2234 <                if ((t = tab = map.table) != null)
2235 <                    baseLimit = baseSize = t.length;
2236 <                long n = map.sumCount();
2237 <                batch = ((n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2238 <                         (int)n);
2239 <            }
2240 <            else {
2241 <                this.tab = it.tab;
2242 <                this.baseSize = it.baseSize;
2243 <                int hi = this.baseLimit = it.baseLimit;
2244 <                it.baseLimit = this.index = this.baseIndex =
2245 <                    (hi + it.baseIndex + 1) >>> 1;
2246 <                this.batch = it.batch >>>= 1;
2247 <            }
2248 <        }
2249 <
2250 <        /**
2251 <         * Advances next; returns nextVal or null if terminated.
2252 <         * See above for explanation.
2253 <         */
2254 <        @SuppressWarnings("unchecked") final V advance() {
2255 <            Node<V> e = next;
2256 <            V ev = null;
2257 <            outer: do {
2258 <                if (e != null)                  // advance past used/skipped node
2259 <                    e = e.next;
2260 <                while (e == null) {             // get to next non-null bin
2261 <                    ConcurrentHashMap<K, V> m;
2262 <                    Node<V>[] t; int b, i, n; Object ek; //  must use locals
2263 <                    if ((t = tab) != null)
2264 <                        n = t.length;
2265 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2266 <                        n = baseLimit = baseSize = t.length;
2267 <                    else
2268 <                        break outer;
2269 <                    if ((b = baseIndex) >= baseLimit ||
2270 <                        (i = index) < 0 || i >= n)
2271 <                        break outer;
2272 <                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2273 <                        if ((ek = e.key) instanceof TreeBin)
2274 <                            e = ((TreeBin<V>)ek).first;
2275 <                        else {
2276 <                            tab = (Node<V>[])ek;
2277 <                            continue;           // restarts due to null val
2582 >     * Replaces all linked nodes in bin at given index unless table is
2583 >     * too small, in which case resizes instead.
2584 >     */
2585 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2586 >        Node<K,V> b; int n, sc;
2587 >        if (tab != null) {
2588 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
2589 >                tryPresize(n << 1);
2590 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2591 >                synchronized (b) {
2592 >                    if (tabAt(tab, index) == b) {
2593 >                        TreeNode<K,V> hd = null, tl = null;
2594 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2595 >                            TreeNode<K,V> p =
2596 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2597 >                                                  null, null);
2598 >                            if ((p.prev = tl) == null)
2599 >                                hd = p;
2600 >                            else
2601 >                                tl.next = p;
2602 >                            tl = p;
2603                          }
2604 <                    }                           // visit upper slots if present
2605 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2604 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2605 >                    }
2606                  }
2607 <                nextKey = (K)e.key;
2283 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2284 <            next = e;
2285 <            return nextVal = ev;
2286 <        }
2287 <
2288 <        public final void remove() {
2289 <            K k = nextKey;
2290 <            if (k == null && (advance() == null || (k = nextKey) == null))
2291 <                throw new IllegalStateException();
2292 <            map.internalReplace(k, null, null);
2293 <        }
2294 <
2295 <        public final boolean hasNext() {
2296 <            return nextVal != null || advance() != null;
2297 <        }
2298 <
2299 <        public final boolean hasMoreElements() { return hasNext(); }
2300 <
2301 <        public void compute() { } // default no-op CountedCompleter body
2302 <
2303 <        /**
2304 <         * Returns a batch value > 0 if this task should (and must) be
2305 <         * split, if so, adding to pending count, and in any case
2306 <         * updating batch value. The initial batch value is approx
2307 <         * exp2 of the number of times (minus one) to split task by
2308 <         * two before executing leaf action. This value is faster to
2309 <         * compute and more convenient to use as a guide to splitting
2310 <         * than is the depth, since it is used while dividing by two
2311 <         * anyway.
2312 <         */
2313 <        final int preSplit() {
2314 <            int b;  ForkJoinPool pool;
2315 <            if ((b = batch) < 0) { // force initialization
2316 <                int sp = (((pool = getPool()) == null) ?
2317 <                          ForkJoinPool.getCommonPoolParallelism() :
2318 <                          pool.getParallelism()) << 3; // slack of 8
2319 <                long n = map.sumCount();
2320 <                b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2321 <            }
2322 <            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2323 <            if ((batch = b) > 0)
2324 <                addToPendingCount(1);
2325 <            return b;
2326 <        }
2327 <
2328 <        // spliterator support
2329 <
2330 <        public boolean hasExactSize() {
2331 <            return false;
2332 <        }
2333 <
2334 <        public boolean hasExactSplits() {
2335 <            return false;
2336 <        }
2337 <
2338 <        public long estimateSize() {
2339 <            return batch;
2607 >            }
2608          }
2609      }
2610  
2343    /* ---------------- Public operations -------------- */
2344
2345    /**
2346     * Creates a new, empty map with the default initial table size (16).
2347     */
2348    public ConcurrentHashMap() {
2349    }
2350
2351    /**
2352     * Creates a new, empty map with an initial table size
2353     * accommodating the specified number of elements without the need
2354     * to dynamically resize.
2355     *
2356     * @param initialCapacity The implementation performs internal
2357     * sizing to accommodate this many elements.
2358     * @throws IllegalArgumentException if the initial capacity of
2359     * elements is negative
2360     */
2361    public ConcurrentHashMap(int initialCapacity) {
2362        if (initialCapacity < 0)
2363            throw new IllegalArgumentException();
2364        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2365                   MAXIMUM_CAPACITY :
2366                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2367        this.sizeCtl = cap;
2368    }
2369
2611      /**
2612 <     * Creates a new map with the same mappings as the given map.
2372 <     *
2373 <     * @param m the map
2612 >     * Returns a list on non-TreeNodes replacing those in given list.
2613       */
2614 <    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2615 <        this.sizeCtl = DEFAULT_CAPACITY;
2616 <        internalPutAll(m);
2614 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2615 >        Node<K,V> hd = null, tl = null;
2616 >        for (Node<K,V> q = b; q != null; q = q.next) {
2617 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2618 >            if (tl == null)
2619 >                hd = p;
2620 >            else
2621 >                tl.next = p;
2622 >            tl = p;
2623 >        }
2624 >        return hd;
2625      }
2626  
2627 <    /**
2381 <     * Creates a new, empty map with an initial table size based on
2382 <     * the given number of elements ({@code initialCapacity}) and
2383 <     * initial table density ({@code loadFactor}).
2384 <     *
2385 <     * @param initialCapacity the initial capacity. The implementation
2386 <     * performs internal sizing to accommodate this many elements,
2387 <     * given the specified load factor.
2388 <     * @param loadFactor the load factor (table density) for
2389 <     * establishing the initial table size
2390 <     * @throws IllegalArgumentException if the initial capacity of
2391 <     * elements is negative or the load factor is nonpositive
2392 <     *
2393 <     * @since 1.6
2394 <     */
2395 <    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
2396 <        this(initialCapacity, loadFactor, 1);
2397 <    }
2627 >    /* ---------------- TreeNodes -------------- */
2628  
2629      /**
2630 <     * Creates a new, empty map with an initial table size based on
2401 <     * the given number of elements ({@code initialCapacity}), table
2402 <     * density ({@code loadFactor}), and number of concurrently
2403 <     * updating threads ({@code concurrencyLevel}).
2404 <     *
2405 <     * @param initialCapacity the initial capacity. The implementation
2406 <     * performs internal sizing to accommodate this many elements,
2407 <     * given the specified load factor.
2408 <     * @param loadFactor the load factor (table density) for
2409 <     * establishing the initial table size
2410 <     * @param concurrencyLevel the estimated number of concurrently
2411 <     * updating threads. The implementation may use this value as
2412 <     * a sizing hint.
2413 <     * @throws IllegalArgumentException if the initial capacity is
2414 <     * negative or the load factor or concurrencyLevel are
2415 <     * nonpositive
2630 >     * Nodes for use in TreeBins
2631       */
2632 <    public ConcurrentHashMap(int initialCapacity,
2633 <                               float loadFactor, int concurrencyLevel) {
2634 <        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2635 <            throw new IllegalArgumentException();
2636 <        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2637 <            initialCapacity = concurrencyLevel;   // as estimated threads
2423 <        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2424 <        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2425 <            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2426 <        this.sizeCtl = cap;
2427 <    }
2632 >    static final class TreeNode<K,V> extends Node<K,V> {
2633 >        TreeNode<K,V> parent;  // red-black tree links
2634 >        TreeNode<K,V> left;
2635 >        TreeNode<K,V> right;
2636 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2637 >        boolean red;
2638  
2639 <    /**
2640 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2641 <     * from the given type to {@code Boolean.TRUE}.
2642 <     *
2643 <     * @return the new set
2434 <     */
2435 <    public static <K> KeySetView<K,Boolean> newKeySet() {
2436 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(),
2437 <                                      Boolean.TRUE);
2438 <    }
2639 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2640 >                 TreeNode<K,V> parent) {
2641 >            super(hash, key, val, next);
2642 >            this.parent = parent;
2643 >        }
2644  
2645 <    /**
2646 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2647 <     * from the given type to {@code Boolean.TRUE}.
2443 <     *
2444 <     * @param initialCapacity The implementation performs internal
2445 <     * sizing to accommodate this many elements.
2446 <     * @throws IllegalArgumentException if the initial capacity of
2447 <     * elements is negative
2448 <     * @return the new set
2449 <     */
2450 <    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2451 <        return new KeySetView<K,Boolean>
2452 <            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2453 <    }
2645 >        Node<K,V> find(int h, Object k) {
2646 >            return findTreeNode(h, k, null);
2647 >        }
2648  
2649 <    /**
2650 <     * {@inheritDoc}
2651 <     */
2652 <    public boolean isEmpty() {
2653 <        return sumCount() <= 0L; // ignore transient negative values
2649 >        /**
2650 >         * Returns the TreeNode (or null if not found) for the given key
2651 >         * starting at given root.
2652 >         */
2653 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2654 >            if (k != null) {
2655 >                TreeNode<K,V> p = this;
2656 >                do  {
2657 >                    int ph, dir; K pk; TreeNode<K,V> q;
2658 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2659 >                    if ((ph = p.hash) > h)
2660 >                        p = pl;
2661 >                    else if (ph < h)
2662 >                        p = pr;
2663 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2664 >                        return p;
2665 >                    else if (pl == null)
2666 >                        p = pr;
2667 >                    else if (pr == null)
2668 >                        p = pl;
2669 >                    else if ((kc != null ||
2670 >                              (kc = comparableClassFor(k)) != null) &&
2671 >                             (dir = compareComparables(kc, k, pk)) != 0)
2672 >                        p = (dir < 0) ? pl : pr;
2673 >                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
2674 >                        return q;
2675 >                    else
2676 >                        p = pl;
2677 >                } while (p != null);
2678 >            }
2679 >            return null;
2680 >        }
2681      }
2682  
2683 <    /**
2463 <     * {@inheritDoc}
2464 <     */
2465 <    public int size() {
2466 <        long n = sumCount();
2467 <        return ((n < 0L) ? 0 :
2468 <                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2469 <                (int)n);
2470 <    }
2683 >    /* ---------------- TreeBins -------------- */
2684  
2685      /**
2686 <     * Returns the number of mappings. This method should be used
2687 <     * instead of {@link #size} because a ConcurrentHashMap may
2688 <     * contain more mappings than can be represented as an int. The
2689 <     * value returned is an estimate; the actual count may differ if
2690 <     * there are concurrent insertions or removals.
2691 <     *
2692 <     * @return the number of mappings
2693 <     */
2694 <    public long mappingCount() {
2695 <        long n = sumCount();
2696 <        return (n < 0L) ? 0L : n; // ignore transient negative values
2697 <    }
2686 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2687 >     * keys or values, but instead point to list of TreeNodes and
2688 >     * their root. They also maintain a parasitic read-write lock
2689 >     * forcing writers (who hold bin lock) to wait for readers (who do
2690 >     * not) to complete before tree restructuring operations.
2691 >     */
2692 >    static final class TreeBin<K,V> extends Node<K,V> {
2693 >        TreeNode<K,V> root;
2694 >        volatile TreeNode<K,V> first;
2695 >        volatile Thread waiter;
2696 >        volatile int lockState;
2697 >        // values for lockState
2698 >        static final int WRITER = 1; // set while holding write lock
2699 >        static final int WAITER = 2; // set when waiting for write lock
2700 >        static final int READER = 4; // increment value for setting read lock
2701 >
2702 >        /**
2703 >         * Tie-breaking utility for ordering insertions when equal
2704 >         * hashCodes and non-comparable. We don't require a total
2705 >         * order, just a consistent insertion rule to maintain
2706 >         * equivalence across rebalancings. Tie-breaking further than
2707 >         * necessary simplifies testing a bit.
2708 >         */
2709 >        static int tieBreakOrder(Object a, Object b) {
2710 >            int d;
2711 >            if (a == null || b == null ||
2712 >                (d = a.getClass().getName().
2713 >                 compareTo(b.getClass().getName())) == 0)
2714 >                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2715 >                     -1 : 1);
2716 >            return d;
2717 >        }
2718  
2719 <    /**
2720 <     * Returns the value to which the specified key is mapped,
2721 <     * or {@code null} if this map contains no mapping for the key.
2722 <     *
2723 <     * <p>More formally, if this map contains a mapping from a key
2724 <     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2725 <     * then this method returns {@code v}; otherwise it returns
2726 <     * {@code null}.  (There can be at most one such mapping.)
2727 <     *
2728 <     * @throws NullPointerException if the specified key is null
2729 <     */
2730 <    public V get(Object key) {
2731 <        return internalGet(key);
2732 <    }
2719 >        /**
2720 >         * Creates bin with initial set of nodes headed by b.
2721 >         */
2722 >        TreeBin(TreeNode<K,V> b) {
2723 >            super(TREEBIN, null, null, null);
2724 >            this.first = b;
2725 >            TreeNode<K,V> r = null;
2726 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2727 >                next = (TreeNode<K,V>)x.next;
2728 >                x.left = x.right = null;
2729 >                if (r == null) {
2730 >                    x.parent = null;
2731 >                    x.red = false;
2732 >                    r = x;
2733 >                }
2734 >                else {
2735 >                    K k = x.key;
2736 >                    int h = x.hash;
2737 >                    Class<?> kc = null;
2738 >                    for (TreeNode<K,V> p = r;;) {
2739 >                        int dir, ph;
2740 >                        K pk = p.key;
2741 >                        if ((ph = p.hash) > h)
2742 >                            dir = -1;
2743 >                        else if (ph < h)
2744 >                            dir = 1;
2745 >                        else if ((kc == null &&
2746 >                                  (kc = comparableClassFor(k)) == null) ||
2747 >                                 (dir = compareComparables(kc, k, pk)) == 0)
2748 >                            dir = tieBreakOrder(k, pk);
2749 >                            TreeNode<K,V> xp = p;
2750 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2751 >                            x.parent = xp;
2752 >                            if (dir <= 0)
2753 >                                xp.left = x;
2754 >                            else
2755 >                                xp.right = x;
2756 >                            r = balanceInsertion(r, x);
2757 >                            break;
2758 >                        }
2759 >                    }
2760 >                }
2761 >            }
2762 >            this.root = r;
2763 >            assert checkInvariants(root);
2764 >        }
2765  
2766 <    /**
2767 <     * Returns the value to which the specified key is mapped,
2768 <     * or the given defaultValue if this map contains no mapping for the key.
2769 <     *
2770 <     * @param key the key
2771 <     * @param defaultValue the value to return if this map contains
2772 <     * no mapping for the given key
2508 <     * @return the mapping for the key, if present; else the defaultValue
2509 <     * @throws NullPointerException if the specified key is null
2510 <     */
2511 <    public V getValueOrDefault(Object key, V defaultValue) {
2512 <        V v;
2513 <        return (v = internalGet(key)) == null ? defaultValue : v;
2514 <    }
2766 >        /**
2767 >         * Acquires write lock for tree restructuring.
2768 >         */
2769 >        private final void lockRoot() {
2770 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2771 >                contendedLock(); // offload to separate method
2772 >        }
2773  
2774 <    /**
2775 <     * Tests if the specified object is a key in this table.
2776 <     *
2777 <     * @param  key   possible key
2778 <     * @return {@code true} if and only if the specified object
2779 <     *         is a key in this table, as determined by the
2522 <     *         {@code equals} method; {@code false} otherwise
2523 <     * @throws NullPointerException if the specified key is null
2524 <     */
2525 <    public boolean containsKey(Object key) {
2526 <        return internalGet(key) != null;
2527 <    }
2774 >        /**
2775 >         * Releases write lock for tree restructuring.
2776 >         */
2777 >        private final void unlockRoot() {
2778 >            lockState = 0;
2779 >        }
2780  
2781 <    /**
2782 <     * Returns {@code true} if this map maps one or more keys to the
2783 <     * specified value. Note: This method may require a full traversal
2784 <     * of the map, and is much slower than method {@code containsKey}.
2785 <     *
2786 <     * @param value value whose presence in this map is to be tested
2787 <     * @return {@code true} if this map maps one or more keys to the
2788 <     *         specified value
2789 <     * @throws NullPointerException if the specified value is null
2790 <     */
2791 <    public boolean containsValue(Object value) {
2792 <        if (value == null)
2793 <            throw new NullPointerException();
2794 <        V v;
2795 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2796 <        while ((v = it.advance()) != null) {
2797 <            if (v == value || value.equals(v))
2798 <                return true;
2781 >        /**
2782 >         * Possibly blocks awaiting root lock.
2783 >         */
2784 >        private final void contendedLock() {
2785 >            boolean waiting = false;
2786 >            for (int s;;) {
2787 >                if (((s = lockState) & ~WAITER) == 0) {
2788 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2789 >                        if (waiting)
2790 >                            waiter = null;
2791 >                        return;
2792 >                    }
2793 >                }
2794 >                else if ((s & WAITER) == 0) {
2795 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2796 >                        waiting = true;
2797 >                        waiter = Thread.currentThread();
2798 >                    }
2799 >                }
2800 >                else if (waiting)
2801 >                    LockSupport.park(this);
2802 >            }
2803          }
2548        return false;
2549    }
2804  
2805 <    /**
2806 <     * Legacy method testing if some key maps into the specified value
2807 <     * in this table.  This method is identical in functionality to
2808 <     * {@link #containsValue(Object)}, and exists solely to ensure
2809 <     * full compatibility with class {@link java.util.Hashtable},
2810 <     * which supported this method prior to introduction of the
2811 <     * Java Collections framework.
2812 <     *
2813 <     * @param  value a value to search for
2814 <     * @return {@code true} if and only if some key maps to the
2815 <     *         {@code value} argument in this table as
2816 <     *         determined by the {@code equals} method;
2817 <     *         {@code false} otherwise
2818 <     * @throws NullPointerException if the specified value is null
2819 <     */
2820 <    @Deprecated public boolean contains(Object value) {
2821 <        return containsValue(value);
2822 <    }
2805 >        /**
2806 >         * Returns matching node or null if none. Tries to search
2807 >         * using tree comparisons from root, but continues linear
2808 >         * search when lock not available.
2809 >         */
2810 >        final Node<K,V> find(int h, Object k) {
2811 >            if (k != null) {
2812 >                for (Node<K,V> e = first; e != null; e = e.next) {
2813 >                    int s; K ek;
2814 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2815 >                        if (e.hash == h &&
2816 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2817 >                            return e;
2818 >                    }
2819 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2820 >                                                 s + READER)) {
2821 >                        TreeNode<K,V> r, p;
2822 >                        try {
2823 >                            p = ((r = root) == null ? null :
2824 >                                 r.findTreeNode(h, k, null));
2825 >                        } finally {
2826 >                            Thread w;
2827 >                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2828 >                                (READER|WAITER) && (w = waiter) != null)
2829 >                                LockSupport.unpark(w);
2830 >                        }
2831 >                        return p;
2832 >                    }
2833 >                }
2834 >            }
2835 >            return null;
2836 >        }
2837  
2838 <    /**
2839 <     * Maps the specified key to the specified value in this table.
2840 <     * Neither the key nor the value can be null.
2841 <     *
2842 <     * <p>The value can be retrieved by calling the {@code get} method
2843 <     * with a key that is equal to the original key.
2844 <     *
2845 <     * @param key key with which the specified value is to be associated
2846 <     * @param value value to be associated with the specified key
2847 <     * @return the previous value associated with {@code key}, or
2848 <     *         {@code null} if there was no mapping for {@code key}
2849 <     * @throws NullPointerException if the specified key or value is null
2850 <     */
2851 <    public V put(K key, V value) {
2852 <        return internalPut(key, value, false);
2853 <    }
2838 >        /**
2839 >         * Finds or adds a node.
2840 >         * @return null if added
2841 >         */
2842 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2843 >            Class<?> kc = null;
2844 >            boolean searched = false;
2845 >            for (TreeNode<K,V> p = root;;) {
2846 >                int dir, ph; K pk;
2847 >                if (p == null) {
2848 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2849 >                    break;
2850 >                }
2851 >                else if ((ph = p.hash) > h)
2852 >                    dir = -1;
2853 >                else if (ph < h)
2854 >                    dir = 1;
2855 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2856 >                    return p;
2857 >                else if ((kc == null &&
2858 >                          (kc = comparableClassFor(k)) == null) ||
2859 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2860 >                    if (!searched) {
2861 >                        TreeNode<K,V> q, ch;
2862 >                        searched = true;
2863 >                        if (((ch = p.left) != null &&
2864 >                             (q = ch.findTreeNode(h, k, kc)) != null) ||
2865 >                            ((ch = p.right) != null &&
2866 >                             (q = ch.findTreeNode(h, k, kc)) != null))
2867 >                            return q;
2868 >                    }
2869 >                    dir = tieBreakOrder(k, pk);
2870 >                }
2871 >
2872 >                TreeNode<K,V> xp = p;
2873 >                if ((p = (dir <= 0) ? p.left : p.right) == null) {
2874 >                    TreeNode<K,V> x, f = first;
2875 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2876 >                    if (f != null)
2877 >                        f.prev = x;
2878 >                    if (dir <= 0)
2879 >                        xp.left = x;
2880 >                    else
2881 >                        xp.right = x;
2882 >                    if (!xp.red)
2883 >                        x.red = true;
2884 >                    else {
2885 >                        lockRoot();
2886 >                        try {
2887 >                            root = balanceInsertion(root, x);
2888 >                        } finally {
2889 >                            unlockRoot();
2890 >                        }
2891 >                    }
2892 >                    break;
2893 >                }
2894 >            }
2895 >            assert checkInvariants(root);
2896 >            return null;
2897 >        }
2898  
2899 <    /**
2900 <     * {@inheritDoc}
2901 <     *
2902 <     * @return the previous value associated with the specified key,
2903 <     *         or {@code null} if there was no mapping for the key
2904 <     * @throws NullPointerException if the specified key or value is null
2905 <     */
2906 <    public V putIfAbsent(K key, V value) {
2907 <        return internalPut(key, value, true);
2908 <    }
2899 >        /**
2900 >         * Removes the given node, that must be present before this
2901 >         * call.  This is messier than typical red-black deletion code
2902 >         * because we cannot swap the contents of an interior node
2903 >         * with a leaf successor that is pinned by "next" pointers
2904 >         * that are accessible independently of lock. So instead we
2905 >         * swap the tree linkages.
2906 >         *
2907 >         * @return true if now too small, so should be untreeified
2908 >         */
2909 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2910 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2911 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2912 >            TreeNode<K,V> r, rl;
2913 >            if (pred == null)
2914 >                first = next;
2915 >            else
2916 >                pred.next = next;
2917 >            if (next != null)
2918 >                next.prev = pred;
2919 >            if (first == null) {
2920 >                root = null;
2921 >                return true;
2922 >            }
2923 >            if ((r = root) == null || r.right == null || // too small
2924 >                (rl = r.left) == null || rl.left == null)
2925 >                return true;
2926 >            lockRoot();
2927 >            try {
2928 >                TreeNode<K,V> replacement;
2929 >                TreeNode<K,V> pl = p.left;
2930 >                TreeNode<K,V> pr = p.right;
2931 >                if (pl != null && pr != null) {
2932 >                    TreeNode<K,V> s = pr, sl;
2933 >                    while ((sl = s.left) != null) // find successor
2934 >                        s = sl;
2935 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2936 >                    TreeNode<K,V> sr = s.right;
2937 >                    TreeNode<K,V> pp = p.parent;
2938 >                    if (s == pr) { // p was s's direct parent
2939 >                        p.parent = s;
2940 >                        s.right = p;
2941 >                    }
2942 >                    else {
2943 >                        TreeNode<K,V> sp = s.parent;
2944 >                        if ((p.parent = sp) != null) {
2945 >                            if (s == sp.left)
2946 >                                sp.left = p;
2947 >                            else
2948 >                                sp.right = p;
2949 >                        }
2950 >                        if ((s.right = pr) != null)
2951 >                            pr.parent = s;
2952 >                    }
2953 >                    p.left = null;
2954 >                    if ((p.right = sr) != null)
2955 >                        sr.parent = p;
2956 >                    if ((s.left = pl) != null)
2957 >                        pl.parent = s;
2958 >                    if ((s.parent = pp) == null)
2959 >                        r = s;
2960 >                    else if (p == pp.left)
2961 >                        pp.left = s;
2962 >                    else
2963 >                        pp.right = s;
2964 >                    if (sr != null)
2965 >                        replacement = sr;
2966 >                    else
2967 >                        replacement = p;
2968 >                }
2969 >                else if (pl != null)
2970 >                    replacement = pl;
2971 >                else if (pr != null)
2972 >                    replacement = pr;
2973 >                else
2974 >                    replacement = p;
2975 >                if (replacement != p) {
2976 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2977 >                    if (pp == null)
2978 >                        r = replacement;
2979 >                    else if (p == pp.left)
2980 >                        pp.left = replacement;
2981 >                    else
2982 >                        pp.right = replacement;
2983 >                    p.left = p.right = p.parent = null;
2984 >                }
2985  
2986 <    /**
2599 <     * Copies all of the mappings from the specified map to this one.
2600 <     * These mappings replace any mappings that this map had for any of the
2601 <     * keys currently in the specified map.
2602 <     *
2603 <     * @param m mappings to be stored in this map
2604 <     */
2605 <    public void putAll(Map<? extends K, ? extends V> m) {
2606 <        internalPutAll(m);
2607 <    }
2986 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2987  
2988 <    /**
2989 <     * If the specified key is not already associated with a value (or
2990 <     * is mapped to {@code null}), attempts to compute its value using
2991 <     * the given mapping function and enters it into this map unless
2992 <     * {@code null}. The entire method invocation is performed
2993 <     * atomically, so the function is applied at most once per key.
2994 <     * Some attempted update operations on this map by other threads
2995 <     * may be blocked while computation is in progress, so the
2996 <     * computation should be short and simple, and must not attempt to
2997 <     * update any other mappings of this Map.
2998 <     *
2999 <     * @param key key with which the specified value is to be associated
3000 <     * @param mappingFunction the function to compute a value
3001 <     * @return the current (existing or computed) value associated with
3002 <     *         the specified key, or null if the computed value is null
3003 <     * @throws NullPointerException if the specified key or mappingFunction
2625 <     *         is null
2626 <     * @throws IllegalStateException if the computation detectably
2627 <     *         attempts a recursive update to this map that would
2628 <     *         otherwise never complete
2629 <     * @throws RuntimeException or Error if the mappingFunction does so,
2630 <     *         in which case the mapping is left unestablished
2631 <     */
2632 <    public V computeIfAbsent
2633 <        (K key, Function<? super K, ? extends V> mappingFunction) {
2634 <        return internalComputeIfAbsent(key, mappingFunction);
2635 <    }
2988 >                if (p == replacement) {  // detach pointers
2989 >                    TreeNode<K,V> pp;
2990 >                    if ((pp = p.parent) != null) {
2991 >                        if (p == pp.left)
2992 >                            pp.left = null;
2993 >                        else if (p == pp.right)
2994 >                            pp.right = null;
2995 >                        p.parent = null;
2996 >                    }
2997 >                }
2998 >            } finally {
2999 >                unlockRoot();
3000 >            }
3001 >            assert checkInvariants(root);
3002 >            return false;
3003 >        }
3004  
3005 <    /**
3006 <     * If the value for the specified key is present and non-null,
2639 <     * attempts to compute a new mapping given the key and its current
2640 <     * mapped value.  The entire method invocation is performed
2641 <     * atomically.  Some attempted update operations on this map by
2642 <     * other threads may be blocked while computation is in progress,
2643 <     * so the computation should be short and simple, and must not
2644 <     * attempt to update any other mappings of this Map.
2645 <     *
2646 <     * @param key key with which the specified value is to be associated
2647 <     * @param remappingFunction the function to compute a value
2648 <     * @return the new value associated with the specified key, or null if none
2649 <     * @throws NullPointerException if the specified key or remappingFunction
2650 <     *         is null
2651 <     * @throws IllegalStateException if the computation detectably
2652 <     *         attempts a recursive update to this map that would
2653 <     *         otherwise never complete
2654 <     * @throws RuntimeException or Error if the remappingFunction does so,
2655 <     *         in which case the mapping is unchanged
2656 <     */
2657 <    public V computeIfPresent
2658 <        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2659 <        return internalCompute(key, true, remappingFunction);
2660 <    }
3005 >        /* ------------------------------------------------------------ */
3006 >        // Red-black tree methods, all adapted from CLR
3007  
3008 <    /**
3009 <     * Attempts to compute a mapping for the specified key and its
3010 <     * current mapped value (or {@code null} if there is no current
3011 <     * mapping). The entire method invocation is performed atomically.
3012 <     * Some attempted update operations on this map by other threads
3013 <     * may be blocked while computation is in progress, so the
3014 <     * computation should be short and simple, and must not attempt to
3015 <     * update any other mappings of this Map.
3016 <     *
3017 <     * @param key key with which the specified value is to be associated
3018 <     * @param remappingFunction the function to compute a value
3019 <     * @return the new value associated with the specified key, or null if none
3020 <     * @throws NullPointerException if the specified key or remappingFunction
3021 <     *         is null
3022 <     * @throws IllegalStateException if the computation detectably
3023 <     *         attempts a recursive update to this map that would
3024 <     *         otherwise never complete
2679 <     * @throws RuntimeException or Error if the remappingFunction does so,
2680 <     *         in which case the mapping is unchanged
2681 <     */
2682 <    public V compute
2683 <        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2684 <        return internalCompute(key, false, remappingFunction);
2685 <    }
3008 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
3009 >                                              TreeNode<K,V> p) {
3010 >            TreeNode<K,V> r, pp, rl;
3011 >            if (p != null && (r = p.right) != null) {
3012 >                if ((rl = p.right = r.left) != null)
3013 >                    rl.parent = p;
3014 >                if ((pp = r.parent = p.parent) == null)
3015 >                    (root = r).red = false;
3016 >                else if (pp.left == p)
3017 >                    pp.left = r;
3018 >                else
3019 >                    pp.right = r;
3020 >                r.left = p;
3021 >                p.parent = r;
3022 >            }
3023 >            return root;
3024 >        }
3025  
3026 <    /**
3027 <     * If the specified key is not already associated with a
3028 <     * (non-null) value, associates it with the given value.
3029 <     * Otherwise, replaces the value with the results of the given
3030 <     * remapping function, or removes if {@code null}. The entire
3031 <     * method invocation is performed atomically.  Some attempted
3032 <     * update operations on this map by other threads may be blocked
3033 <     * while computation is in progress, so the computation should be
3034 <     * short and simple, and must not attempt to update any other
3035 <     * mappings of this Map.
3036 <     *
3037 <     * @param key key with which the specified value is to be associated
3038 <     * @param value the value to use if absent
3039 <     * @param remappingFunction the function to recompute a value if present
3040 <     * @return the new value associated with the specified key, or null if none
3041 <     * @throws NullPointerException if the specified key or the
3042 <     *         remappingFunction is null
2704 <     * @throws RuntimeException or Error if the remappingFunction does so,
2705 <     *         in which case the mapping is unchanged
2706 <     */
2707 <    public V merge
2708 <        (K key, V value,
2709 <         BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2710 <        return internalMerge(key, value, remappingFunction);
2711 <    }
3026 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
3027 >                                               TreeNode<K,V> p) {
3028 >            TreeNode<K,V> l, pp, lr;
3029 >            if (p != null && (l = p.left) != null) {
3030 >                if ((lr = p.left = l.right) != null)
3031 >                    lr.parent = p;
3032 >                if ((pp = l.parent = p.parent) == null)
3033 >                    (root = l).red = false;
3034 >                else if (pp.right == p)
3035 >                    pp.right = l;
3036 >                else
3037 >                    pp.left = l;
3038 >                l.right = p;
3039 >                p.parent = l;
3040 >            }
3041 >            return root;
3042 >        }
3043  
3044 <    /**
3045 <     * Removes the key (and its corresponding value) from this map.
3046 <     * This method does nothing if the key is not in the map.
3047 <     *
3048 <     * @param  key the key that needs to be removed
3049 <     * @return the previous value associated with {@code key}, or
3050 <     *         {@code null} if there was no mapping for {@code key}
3051 <     * @throws NullPointerException if the specified key is null
3052 <     */
3053 <    public V remove(Object key) {
3054 <        return internalReplace(key, null, null);
3055 <    }
3044 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
3045 >                                                    TreeNode<K,V> x) {
3046 >            x.red = true;
3047 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
3048 >                if ((xp = x.parent) == null) {
3049 >                    x.red = false;
3050 >                    return x;
3051 >                }
3052 >                else if (!xp.red || (xpp = xp.parent) == null)
3053 >                    return root;
3054 >                if (xp == (xppl = xpp.left)) {
3055 >                    if ((xppr = xpp.right) != null && xppr.red) {
3056 >                        xppr.red = false;
3057 >                        xp.red = false;
3058 >                        xpp.red = true;
3059 >                        x = xpp;
3060 >                    }
3061 >                    else {
3062 >                        if (x == xp.right) {
3063 >                            root = rotateLeft(root, x = xp);
3064 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3065 >                        }
3066 >                        if (xp != null) {
3067 >                            xp.red = false;
3068 >                            if (xpp != null) {
3069 >                                xpp.red = true;
3070 >                                root = rotateRight(root, xpp);
3071 >                            }
3072 >                        }
3073 >                    }
3074 >                }
3075 >                else {
3076 >                    if (xppl != null && xppl.red) {
3077 >                        xppl.red = false;
3078 >                        xp.red = false;
3079 >                        xpp.red = true;
3080 >                        x = xpp;
3081 >                    }
3082 >                    else {
3083 >                        if (x == xp.left) {
3084 >                            root = rotateRight(root, x = xp);
3085 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3086 >                        }
3087 >                        if (xp != null) {
3088 >                            xp.red = false;
3089 >                            if (xpp != null) {
3090 >                                xpp.red = true;
3091 >                                root = rotateLeft(root, xpp);
3092 >                            }
3093 >                        }
3094 >                    }
3095 >                }
3096 >            }
3097 >        }
3098  
3099 <    /**
3100 <     * {@inheritDoc}
3101 <     *
3102 <     * @throws NullPointerException if the specified key is null
3103 <     */
3104 <    public boolean remove(Object key, Object value) {
3105 <        if (key == null)
3106 <            throw new NullPointerException();
3107 <        return value != null && internalReplace(key, null, value) != null;
3108 <    }
3099 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3100 >                                                   TreeNode<K,V> x) {
3101 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
3102 >                if (x == null || x == root)
3103 >                    return root;
3104 >                else if ((xp = x.parent) == null) {
3105 >                    x.red = false;
3106 >                    return x;
3107 >                }
3108 >                else if (x.red) {
3109 >                    x.red = false;
3110 >                    return root;
3111 >                }
3112 >                else if ((xpl = xp.left) == x) {
3113 >                    if ((xpr = xp.right) != null && xpr.red) {
3114 >                        xpr.red = false;
3115 >                        xp.red = true;
3116 >                        root = rotateLeft(root, xp);
3117 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3118 >                    }
3119 >                    if (xpr == null)
3120 >                        x = xp;
3121 >                    else {
3122 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3123 >                        if ((sr == null || !sr.red) &&
3124 >                            (sl == null || !sl.red)) {
3125 >                            xpr.red = true;
3126 >                            x = xp;
3127 >                        }
3128 >                        else {
3129 >                            if (sr == null || !sr.red) {
3130 >                                if (sl != null)
3131 >                                    sl.red = false;
3132 >                                xpr.red = true;
3133 >                                root = rotateRight(root, xpr);
3134 >                                xpr = (xp = x.parent) == null ?
3135 >                                    null : xp.right;
3136 >                            }
3137 >                            if (xpr != null) {
3138 >                                xpr.red = (xp == null) ? false : xp.red;
3139 >                                if ((sr = xpr.right) != null)
3140 >                                    sr.red = false;
3141 >                            }
3142 >                            if (xp != null) {
3143 >                                xp.red = false;
3144 >                                root = rotateLeft(root, xp);
3145 >                            }
3146 >                            x = root;
3147 >                        }
3148 >                    }
3149 >                }
3150 >                else { // symmetric
3151 >                    if (xpl != null && xpl.red) {
3152 >                        xpl.red = false;
3153 >                        xp.red = true;
3154 >                        root = rotateRight(root, xp);
3155 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3156 >                    }
3157 >                    if (xpl == null)
3158 >                        x = xp;
3159 >                    else {
3160 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3161 >                        if ((sl == null || !sl.red) &&
3162 >                            (sr == null || !sr.red)) {
3163 >                            xpl.red = true;
3164 >                            x = xp;
3165 >                        }
3166 >                        else {
3167 >                            if (sl == null || !sl.red) {
3168 >                                if (sr != null)
3169 >                                    sr.red = false;
3170 >                                xpl.red = true;
3171 >                                root = rotateLeft(root, xpl);
3172 >                                xpl = (xp = x.parent) == null ?
3173 >                                    null : xp.left;
3174 >                            }
3175 >                            if (xpl != null) {
3176 >                                xpl.red = (xp == null) ? false : xp.red;
3177 >                                if ((sl = xpl.left) != null)
3178 >                                    sl.red = false;
3179 >                            }
3180 >                            if (xp != null) {
3181 >                                xp.red = false;
3182 >                                root = rotateRight(root, xp);
3183 >                            }
3184 >                            x = root;
3185 >                        }
3186 >                    }
3187 >                }
3188 >            }
3189 >        }
3190  
3191 <    /**
3192 <     * {@inheritDoc}
3193 <     *
3194 <     * @throws NullPointerException if any of the arguments are null
3195 <     */
3196 <    public boolean replace(K key, V oldValue, V newValue) {
3197 <        if (key == null || oldValue == null || newValue == null)
3198 <            throw new NullPointerException();
3199 <        return internalReplace(key, newValue, oldValue) != null;
3200 <    }
3191 >        /**
3192 >         * Recursive invariant check
3193 >         */
3194 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3195 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3196 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3197 >            if (tb != null && tb.next != t)
3198 >                return false;
3199 >            if (tn != null && tn.prev != t)
3200 >                return false;
3201 >            if (tp != null && t != tp.left && t != tp.right)
3202 >                return false;
3203 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3204 >                return false;
3205 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3206 >                return false;
3207 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3208 >                return false;
3209 >            if (tl != null && !checkInvariants(tl))
3210 >                return false;
3211 >            if (tr != null && !checkInvariants(tr))
3212 >                return false;
3213 >            return true;
3214 >        }
3215  
3216 <    /**
3217 <     * {@inheritDoc}
3218 <     *
3219 <     * @return the previous value associated with the specified key,
3220 <     *         or {@code null} if there was no mapping for the key
3221 <     * @throws NullPointerException if the specified key or value is null
3222 <     */
3223 <    public V replace(K key, V value) {
3224 <        if (key == null || value == null)
3225 <            throw new NullPointerException();
3226 <        return internalReplace(key, value, null);
3216 >        private static final sun.misc.Unsafe U;
3217 >        private static final long LOCKSTATE;
3218 >        static {
3219 >            try {
3220 >                U = sun.misc.Unsafe.getUnsafe();
3221 >                Class<?> k = TreeBin.class;
3222 >                LOCKSTATE = U.objectFieldOffset
3223 >                    (k.getDeclaredField("lockState"));
3224 >            } catch (Exception e) {
3225 >                throw new Error(e);
3226 >            }
3227 >        }
3228      }
3229  
3230 <    /**
2762 <     * Removes all of the mappings from this map.
2763 <     */
2764 <    public void clear() {
2765 <        internalClear();
2766 <    }
3230 >    /* ----------------Table Traversal -------------- */
3231  
3232      /**
3233 <     * Returns a {@link Set} view of the keys contained in this map.
3234 <     * The set is backed by the map, so changes to the map are
3235 <     * reflected in the set, and vice-versa.
3236 <     *
3237 <     * @return the set view
3238 <     */
3239 <    public KeySetView<K,V> keySet() {
3240 <        KeySetView<K,V> ks = keySet;
3241 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
3233 >     * Records the table, its length, and current traversal index for a
3234 >     * traverser that must process a region of a forwarded table before
3235 >     * proceeding with current table.
3236 >     */
3237 >    static final class TableStack<K,V> {
3238 >        int length;
3239 >        int index;
3240 >        Node<K,V>[] tab;
3241 >        TableStack<K,V> next;
3242      }
3243  
3244      /**
3245 <     * Returns a {@link Set} view of the keys in this map, using the
3246 <     * given common mapped value for any additions (i.e., {@link
2783 <     * Collection#add} and {@link Collection#addAll(Collection)}).
2784 <     * This is of course only appropriate if it is acceptable to use
2785 <     * the same value for all additions from this view.
3245 >     * Encapsulates traversal for methods such as containsValue; also
3246 >     * serves as a base class for other iterators and spliterators.
3247       *
3248 <     * @param mappedValue the mapped value to use for any additions
3249 <     * @return the set view
3250 <     * @throws NullPointerException if the mappedValue is null
3251 <     */
3252 <    public KeySetView<K,V> keySet(V mappedValue) {
3253 <        if (mappedValue == null)
3254 <            throw new NullPointerException();
3255 <        return new KeySetView<K,V>(this, mappedValue);
2795 <    }
2796 <
2797 <    /**
2798 <     * Returns a {@link Collection} view of the values contained in this map.
2799 <     * The collection is backed by the map, so changes to the map are
2800 <     * reflected in the collection, and vice-versa.
2801 <     */
2802 <    public ValuesView<K,V> values() {
2803 <        ValuesView<K,V> vs = values;
2804 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2805 <    }
2806 <
2807 <    /**
2808 <     * Returns a {@link Set} view of the mappings contained in this map.
2809 <     * The set is backed by the map, so changes to the map are
2810 <     * reflected in the set, and vice-versa.  The set supports element
2811 <     * removal, which removes the corresponding mapping from the map,
2812 <     * via the {@code Iterator.remove}, {@code Set.remove},
2813 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
2814 <     * operations.  It does not support the {@code add} or
2815 <     * {@code addAll} operations.
3248 >     * Method advance visits once each still-valid node that was
3249 >     * reachable upon iterator construction. It might miss some that
3250 >     * were added to a bin after the bin was visited, which is OK wrt
3251 >     * consistency guarantees. Maintaining this property in the face
3252 >     * of possible ongoing resizes requires a fair amount of
3253 >     * bookkeeping state that is difficult to optimize away amidst
3254 >     * volatile accesses.  Even so, traversal maintains reasonable
3255 >     * throughput.
3256       *
3257 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
3258 <     * that will never throw {@link ConcurrentModificationException},
3259 <     * and guarantees to traverse elements as they existed upon
3260 <     * construction of the iterator, and may (but is not guaranteed to)
3261 <     * reflect any modifications subsequent to construction.
3257 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3258 >     * However, if the table has been resized, then all future steps
3259 >     * must traverse both the bin at the current index as well as at
3260 >     * (index + baseSize); and so on for further resizings. To
3261 >     * paranoically cope with potential sharing by users of iterators
3262 >     * across threads, iteration terminates if a bounds checks fails
3263 >     * for a table read.
3264       */
3265 <    public Set<Map.Entry<K,V>> entrySet() {
3266 <        EntrySetView<K,V> es = entrySet;
3267 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
3268 <    }
3265 >    static class Traverser<K,V> {
3266 >        Node<K,V>[] tab;        // current table; updated if resized
3267 >        Node<K,V> next;         // the next entry to use
3268 >        TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3269 >        int index;              // index of bin to use next
3270 >        int baseIndex;          // current index of initial table
3271 >        int baseLimit;          // index bound for initial table
3272 >        final int baseSize;     // initial table size
3273 >
3274 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3275 >            this.tab = tab;
3276 >            this.baseSize = size;
3277 >            this.baseIndex = this.index = index;
3278 >            this.baseLimit = limit;
3279 >            this.next = null;
3280 >        }
3281  
3282 <    /**
3283 <     * Returns an enumeration of the keys in this table.
3284 <     *
3285 <     * @return an enumeration of the keys in this table
3286 <     * @see #keySet()
3287 <     */
3288 <    public Enumeration<K> keys() {
3289 <        return new KeyIterator<K,V>(this);
3290 <    }
3282 >        /**
3283 >         * Advances if possible, returning next valid node, or null if none.
3284 >         */
3285 >        final Node<K,V> advance() {
3286 >            Node<K,V> e;
3287 >            if ((e = next) != null)
3288 >                e = e.next;
3289 >            for (;;) {
3290 >                Node<K,V>[] t; int i, n;  // must use locals in checks
3291 >                if (e != null)
3292 >                    return next = e;
3293 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3294 >                    (n = t.length) <= (i = index) || i < 0)
3295 >                    return next = null;
3296 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
3297 >                    if (e instanceof ForwardingNode) {
3298 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3299 >                        e = null;
3300 >                        pushState(t, i, n);
3301 >                        continue;
3302 >                    }
3303 >                    else if (e instanceof TreeBin)
3304 >                        e = ((TreeBin<K,V>)e).first;
3305 >                    else
3306 >                        e = null;
3307 >                }
3308 >                if (stack != null)
3309 >                    recoverState(n);
3310 >                else if ((index = i + baseSize) >= n)
3311 >                    index = ++baseIndex; // visit upper slots if present
3312 >            }
3313 >        }
3314  
3315 <    /**
3316 <     * Returns an enumeration of the values in this table.
3317 <     *
3318 <     * @return an enumeration of the values in this table
3319 <     * @see #values()
3320 <     */
3321 <    public Enumeration<V> elements() {
3322 <        return new ValueIterator<K,V>(this);
3323 <    }
3315 >        /**
3316 >         * Saves traversal state upon encountering a forwarding node.
3317 >         */
3318 >        private void pushState(Node<K,V>[] t, int i, int n) {
3319 >            TableStack<K,V> s = spare;  // reuse if possible
3320 >            if (s != null)
3321 >                spare = s.next;
3322 >            else
3323 >                s = new TableStack<K,V>();
3324 >            s.tab = t;
3325 >            s.length = n;
3326 >            s.index = i;
3327 >            s.next = stack;
3328 >            stack = s;
3329 >        }
3330  
3331 <    /**
3332 <     * Returns the hash code value for this {@link Map}, i.e.,
3333 <     * the sum of, for each key-value pair in the map,
3334 <     * {@code key.hashCode() ^ value.hashCode()}.
3335 <     *
3336 <     * @return the hash code value for this map
3337 <     */
3338 <    public int hashCode() {
3339 <        int h = 0;
3340 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3341 <        V v;
3342 <        while ((v = it.advance()) != null) {
3343 <            h += it.nextKey.hashCode() ^ v.hashCode();
3331 >        /**
3332 >         * Possibly pops traversal state.
3333 >         *
3334 >         * @param n length of current table
3335 >         */
3336 >        private void recoverState(int n) {
3337 >            TableStack<K,V> s; int len;
3338 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
3339 >                n = len;
3340 >                index = s.index;
3341 >                tab = s.tab;
3342 >                s.tab = null;
3343 >                TableStack<K,V> next = s.next;
3344 >                s.next = spare; // save for reuse
3345 >                stack = next;
3346 >                spare = s;
3347 >            }
3348 >            if (s == null && (index += baseSize) >= n)
3349 >                index = ++baseIndex;
3350          }
2862        return h;
3351      }
3352  
3353      /**
3354 <     * Returns a string representation of this map.  The string
3355 <     * representation consists of a list of key-value mappings (in no
3356 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3357 <     * mappings are separated by the characters {@code ", "} (comma
3358 <     * and space).  Each key-value mapping is rendered as the key
3359 <     * followed by an equals sign ("{@code =}") followed by the
3360 <     * associated value.
3361 <     *
3362 <     * @return a string representation of this map
3363 <     */
3364 <    public String toString() {
2877 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2878 <        StringBuilder sb = new StringBuilder();
2879 <        sb.append('{');
2880 <        V v;
2881 <        if ((v = it.advance()) != null) {
2882 <            for (;;) {
2883 <                K k = it.nextKey;
2884 <                sb.append(k == this ? "(this Map)" : k);
2885 <                sb.append('=');
2886 <                sb.append(v == this ? "(this Map)" : v);
2887 <                if ((v = it.advance()) == null)
2888 <                    break;
2889 <                sb.append(',').append(' ');
2890 <            }
3354 >     * Base of key, value, and entry Iterators. Adds fields to
3355 >     * Traverser to support iterator.remove.
3356 >     */
3357 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3358 >        final ConcurrentHashMap<K,V> map;
3359 >        Node<K,V> lastReturned;
3360 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3361 >                    ConcurrentHashMap<K,V> map) {
3362 >            super(tab, size, index, limit);
3363 >            this.map = map;
3364 >            advance();
3365          }
2892        return sb.append('}').toString();
2893    }
3366  
3367 <    /**
3368 <     * Compares the specified object with this map for equality.
3369 <     * Returns {@code true} if the given object is a map with the same
3370 <     * mappings as this map.  This operation may return misleading
3371 <     * results if either map is concurrently modified during execution
3372 <     * of this method.
3373 <     *
3374 <     * @param o object to be compared for equality with this map
3375 <     * @return {@code true} if the specified object is equal to this map
2904 <     */
2905 <    public boolean equals(Object o) {
2906 <        if (o != this) {
2907 <            if (!(o instanceof Map))
2908 <                return false;
2909 <            Map<?,?> m = (Map<?,?>) o;
2910 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2911 <            V val;
2912 <            while ((val = it.advance()) != null) {
2913 <                Object v = m.get(it.nextKey);
2914 <                if (v == null || (v != val && !v.equals(val)))
2915 <                    return false;
2916 <            }
2917 <            for (Map.Entry<?,?> e : m.entrySet()) {
2918 <                Object mk, mv, v;
2919 <                if ((mk = e.getKey()) == null ||
2920 <                    (mv = e.getValue()) == null ||
2921 <                    (v = internalGet(mk)) == null ||
2922 <                    (mv != v && !mv.equals(v)))
2923 <                    return false;
2924 <            }
3367 >        public final boolean hasNext() { return next != null; }
3368 >        public final boolean hasMoreElements() { return next != null; }
3369 >
3370 >        public final void remove() {
3371 >            Node<K,V> p;
3372 >            if ((p = lastReturned) == null)
3373 >                throw new IllegalStateException();
3374 >            lastReturned = null;
3375 >            map.replaceNode(p.key, null, null);
3376          }
2926        return true;
3377      }
3378  
3379 <    /* ----------------Iterators -------------- */
3380 <
3381 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3382 <        extends Traverser<K,V,Object>
3383 <        implements Spliterator<K>, Iterator<K>, Enumeration<K> {
2934 <        KeyIterator(ConcurrentHashMap<K, V> map) { super(map); }
2935 <        KeyIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
2936 <            super(map, it);
2937 <        }
2938 <        public KeyIterator<K,V> trySplit() {
2939 <            if (tab != null && baseIndex == baseLimit)
2940 <                return null;
2941 <            return new KeyIterator<K,V>(map, this);
3379 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3380 >        implements Iterator<K>, Enumeration<K> {
3381 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3382 >                    ConcurrentHashMap<K,V> map) {
3383 >            super(tab, index, size, limit, map);
3384          }
3385 +
3386          public final K next() {
3387 <            if (nextVal == null && advance() == null)
3387 >            Node<K,V> p;
3388 >            if ((p = next) == null)
3389                  throw new NoSuchElementException();
3390 <            K k = nextKey;
3391 <            nextVal = null;
3390 >            K k = p.key;
3391 >            lastReturned = p;
3392 >            advance();
3393              return k;
3394          }
3395  
3396          public final K nextElement() { return next(); }
2952
2953        public Iterator<K> iterator() { return this; }
2954
2955        public void forEach(Consumer<? super K> action) {
2956            if (action == null) throw new NullPointerException();
2957            while (advance() != null)
2958                action.accept(nextKey);
2959        }
2960
2961        public boolean tryAdvance(Consumer<? super K> block) {
2962            if (block == null) throw new NullPointerException();
2963            if (advance() == null)
2964                return false;
2965            block.accept(nextKey);
2966            return true;
2967        }
3397      }
3398  
3399 <    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3400 <        extends Traverser<K,V,Object>
3401 <        implements Spliterator<V>, Iterator<V>, Enumeration<V> {
3402 <        ValueIterator(ConcurrentHashMap<K, V> map) { super(map); }
3403 <        ValueIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
2975 <            super(map, it);
2976 <        }
2977 <        public ValueIterator<K,V> trySplit() {
2978 <            if (tab != null && baseIndex == baseLimit)
2979 <                return null;
2980 <            return new ValueIterator<K,V>(map, this);
3399 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3400 >        implements Iterator<V>, Enumeration<V> {
3401 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3402 >                      ConcurrentHashMap<K,V> map) {
3403 >            super(tab, index, size, limit, map);
3404          }
3405  
3406          public final V next() {
3407 <            V v;
3408 <            if ((v = nextVal) == null && (v = advance()) == null)
3407 >            Node<K,V> p;
3408 >            if ((p = next) == null)
3409                  throw new NoSuchElementException();
3410 <            nextVal = null;
3410 >            V v = p.val;
3411 >            lastReturned = p;
3412 >            advance();
3413              return v;
3414          }
3415  
3416          public final V nextElement() { return next(); }
2992
2993        public Iterator<V> iterator() { return this; }
2994
2995        public void forEach(Consumer<? super V> action) {
2996            if (action == null) throw new NullPointerException();
2997            V v;
2998            while ((v = advance()) != null)
2999                action.accept(v);
3000        }
3001
3002        public boolean tryAdvance(Consumer<? super V> block) {
3003            V v;
3004            if (block == null) throw new NullPointerException();
3005            if ((v = advance()) == null)
3006                return false;
3007            block.accept(v);
3008            return true;
3009        }
3010
3417      }
3418  
3419 <    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3420 <        extends Traverser<K,V,Object>
3421 <        implements Spliterator<Map.Entry<K,V>>, Iterator<Map.Entry<K,V>> {
3422 <        EntryIterator(ConcurrentHashMap<K, V> map) { super(map); }
3423 <        EntryIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
3018 <            super(map, it);
3019 <        }
3020 <        public EntryIterator<K,V> trySplit() {
3021 <            if (tab != null && baseIndex == baseLimit)
3022 <                return null;
3023 <            return new EntryIterator<K,V>(map, this);
3419 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3420 >        implements Iterator<Map.Entry<K,V>> {
3421 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3422 >                      ConcurrentHashMap<K,V> map) {
3423 >            super(tab, index, size, limit, map);
3424          }
3425  
3426          public final Map.Entry<K,V> next() {
3427 <            V v;
3428 <            if ((v = nextVal) == null && (v = advance()) == null)
3427 >            Node<K,V> p;
3428 >            if ((p = next) == null)
3429                  throw new NoSuchElementException();
3430 <            K k = nextKey;
3431 <            nextVal = null;
3430 >            K k = p.key;
3431 >            V v = p.val;
3432 >            lastReturned = p;
3433 >            advance();
3434              return new MapEntry<K,V>(k, v, map);
3435          }
3034
3035        public Iterator<Map.Entry<K,V>> iterator() { return this; }
3036
3037        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
3038            if (action == null) throw new NullPointerException();
3039            V v;
3040            while ((v = advance()) != null)
3041                action.accept(entryFor(nextKey, v));
3042        }
3043
3044        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> block) {
3045            V v;
3046            if (block == null) throw new NullPointerException();
3047            if ((v = advance()) == null)
3048                return false;
3049            block.accept(entryFor(nextKey, v));
3050            return true;
3051        }
3052
3436      }
3437  
3438      /**
3439 <     * Exported Entry for iterators
3439 >     * Exported Entry for EntryIterator
3440       */
3441 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3441 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3442          final K key; // non-null
3443          V val;       // non-null
3444 <        final ConcurrentHashMap<K, V> map;
3445 <        MapEntry(K key, V val, ConcurrentHashMap<K, V> map) {
3444 >        final ConcurrentHashMap<K,V> map;
3445 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3446              this.key = key;
3447              this.val = val;
3448              this.map = map;
3449          }
3450 <        public final K getKey()       { return key; }
3451 <        public final V getValue()     { return val; }
3452 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3453 <        public final String toString(){ return key + "=" + val; }
3450 >        public K getKey()        { return key; }
3451 >        public V getValue()      { return val; }
3452 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3453 >        public String toString() { return key + "=" + val; }
3454  
3455 <        public final boolean equals(Object o) {
3455 >        public boolean equals(Object o) {
3456              Object k, v; Map.Entry<?,?> e;
3457              return ((o instanceof Map.Entry) &&
3458                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3083 | Line 3466 | public class ConcurrentHashMap<K, V>
3466           * value to return is somewhat arbitrary here. Since we do not
3467           * necessarily track asynchronous changes, the most recent
3468           * "previous" value could be different from what we return (or
3469 <         * could even have been removed in which case the put will
3469 >         * could even have been removed, in which case the put will
3470           * re-establish). We do not and cannot guarantee more.
3471           */
3472 <        public final V setValue(V value) {
3472 >        public V setValue(V value) {
3473              if (value == null) throw new NullPointerException();
3474              V v = val;
3475              val = value;
# Line 3095 | Line 3478 | public class ConcurrentHashMap<K, V>
3478          }
3479      }
3480  
3481 <    /**
3482 <     * Returns exportable snapshot entry for the given key and value
3483 <     * when write-through can't or shouldn't be used.
3484 <     */
3485 <    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3486 <        return new AbstractMap.SimpleEntry<K,V>(k, v);
3487 <    }
3481 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3482 >        implements Spliterator<K> {
3483 >        long est;               // size estimate
3484 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3485 >                       long est) {
3486 >            super(tab, size, index, limit);
3487 >            this.est = est;
3488 >        }
3489 >
3490 >        public Spliterator<K> trySplit() {
3491 >            int i, f, h;
3492 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3493 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3494 >                                        f, est >>>= 1);
3495 >        }
3496  
3497 <    /* ---------------- Serialization Support -------------- */
3497 >        public void forEachRemaining(Consumer<? super K> action) {
3498 >            if (action == null) throw new NullPointerException();
3499 >            for (Node<K,V> p; (p = advance()) != null;)
3500 >                action.accept(p.key);
3501 >        }
3502  
3503 <    /**
3504 <     * Stripped-down version of helper class used in previous version,
3505 <     * declared for the sake of serialization compatibility
3506 <     */
3507 <    static class Segment<K,V> implements Serializable {
3508 <        private static final long serialVersionUID = 2249069246763182397L;
3509 <        final float loadFactor;
3510 <        Segment(float lf) { this.loadFactor = lf; }
3503 >        public boolean tryAdvance(Consumer<? super K> action) {
3504 >            if (action == null) throw new NullPointerException();
3505 >            Node<K,V> p;
3506 >            if ((p = advance()) == null)
3507 >                return false;
3508 >            action.accept(p.key);
3509 >            return true;
3510 >        }
3511 >
3512 >        public long estimateSize() { return est; }
3513 >
3514 >        public int characteristics() {
3515 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3516 >                Spliterator.NONNULL;
3517 >        }
3518      }
3519  
3520 <    /**
3521 <     * Saves the state of the {@code ConcurrentHashMap} instance to a
3522 <     * stream (i.e., serializes it).
3523 <     * @param s the stream
3524 <     * @serialData
3525 <     * the key (Object) and value (Object)
3526 <     * for each key-value mapping, followed by a null pair.
3125 <     * The key-value mappings are emitted in no particular order.
3126 <     */
3127 <    @SuppressWarnings("unchecked") private void writeObject
3128 <        (java.io.ObjectOutputStream s)
3129 <        throws java.io.IOException {
3130 <        if (segments == null) { // for serialization compatibility
3131 <            segments = (Segment<K,V>[])
3132 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3133 <            for (int i = 0; i < segments.length; ++i)
3134 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3520 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3521 >        implements Spliterator<V> {
3522 >        long est;               // size estimate
3523 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3524 >                         long est) {
3525 >            super(tab, size, index, limit);
3526 >            this.est = est;
3527          }
3528 <        s.defaultWriteObject();
3529 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3530 <        V v;
3531 <        while ((v = it.advance()) != null) {
3532 <            s.writeObject(it.nextKey);
3533 <            s.writeObject(v);
3528 >
3529 >        public Spliterator<V> trySplit() {
3530 >            int i, f, h;
3531 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3532 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3533 >                                          f, est >>>= 1);
3534 >        }
3535 >
3536 >        public void forEachRemaining(Consumer<? super V> action) {
3537 >            if (action == null) throw new NullPointerException();
3538 >            for (Node<K,V> p; (p = advance()) != null;)
3539 >                action.accept(p.val);
3540 >        }
3541 >
3542 >        public boolean tryAdvance(Consumer<? super V> action) {
3543 >            if (action == null) throw new NullPointerException();
3544 >            Node<K,V> p;
3545 >            if ((p = advance()) == null)
3546 >                return false;
3547 >            action.accept(p.val);
3548 >            return true;
3549 >        }
3550 >
3551 >        public long estimateSize() { return est; }
3552 >
3553 >        public int characteristics() {
3554 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3555          }
3143        s.writeObject(null);
3144        s.writeObject(null);
3145        segments = null; // throw away
3556      }
3557  
3558 <    /**
3559 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3560 <     * @param s the stream
3561 <     */
3562 <    @SuppressWarnings("unchecked") private void readObject
3563 <        (java.io.ObjectInputStream s)
3564 <        throws java.io.IOException, ClassNotFoundException {
3565 <        s.defaultReadObject();
3566 <        this.segments = null; // unneeded
3558 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3559 >        implements Spliterator<Map.Entry<K,V>> {
3560 >        final ConcurrentHashMap<K,V> map; // To export MapEntry
3561 >        long est;               // size estimate
3562 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3563 >                         long est, ConcurrentHashMap<K,V> map) {
3564 >            super(tab, size, index, limit);
3565 >            this.map = map;
3566 >            this.est = est;
3567 >        }
3568  
3569 <        // Create all nodes, then place in table once size is known
3570 <        long size = 0L;
3571 <        Node<V> p = null;
3572 <        for (;;) {
3573 <            K k = (K) s.readObject();
3163 <            V v = (V) s.readObject();
3164 <            if (k != null && v != null) {
3165 <                int h = spread(k.hashCode());
3166 <                p = new Node<V>(h, k, v, p);
3167 <                ++size;
3168 <            }
3169 <            else
3170 <                break;
3569 >        public Spliterator<Map.Entry<K,V>> trySplit() {
3570 >            int i, f, h;
3571 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3572 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3573 >                                          f, est >>>= 1, map);
3574          }
3575 <        if (p != null) {
3576 <            boolean init = false;
3577 <            int n;
3578 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3579 <                n = MAXIMUM_CAPACITY;
3580 <            else {
3581 <                int sz = (int)size;
3582 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3583 <            }
3584 <            int sc = sizeCtl;
3585 <            boolean collide = false;
3586 <            if (n > sc &&
3587 <                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3588 <                try {
3589 <                    if (table == null) {
3590 <                        init = true;
3591 <                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3592 <                        Node<V>[] tab = (Node<V>[])rt;
3593 <                        int mask = n - 1;
3594 <                        while (p != null) {
3595 <                            int j = p.hash & mask;
3193 <                            Node<V> next = p.next;
3194 <                            Node<V> q = p.next = tabAt(tab, j);
3195 <                            setTabAt(tab, j, p);
3196 <                            if (!collide && q != null && q.hash == p.hash)
3197 <                                collide = true;
3198 <                            p = next;
3199 <                        }
3200 <                        table = tab;
3201 <                        addCount(size, -1);
3202 <                        sc = n - (n >>> 2);
3203 <                    }
3204 <                } finally {
3205 <                    sizeCtl = sc;
3206 <                }
3207 <                if (collide) { // rescan and convert to TreeBins
3208 <                    Node<V>[] tab = table;
3209 <                    for (int i = 0; i < tab.length; ++i) {
3210 <                        int c = 0;
3211 <                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3212 <                            if (++c > TREE_THRESHOLD &&
3213 <                                (e.key instanceof Comparable)) {
3214 <                                replaceWithTreeBin(tab, i, e.key);
3215 <                                break;
3216 <                            }
3217 <                        }
3218 <                    }
3219 <                }
3220 <            }
3221 <            if (!init) { // Can only happen if unsafely published.
3222 <                while (p != null) {
3223 <                    internalPut((K)p.key, p.val, false);
3224 <                    p = p.next;
3225 <                }
3226 <            }
3575 >
3576 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3577 >            if (action == null) throw new NullPointerException();
3578 >            for (Node<K,V> p; (p = advance()) != null; )
3579 >                action.accept(new MapEntry<K,V>(p.key, p.val, map));
3580 >        }
3581 >
3582 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3583 >            if (action == null) throw new NullPointerException();
3584 >            Node<K,V> p;
3585 >            if ((p = advance()) == null)
3586 >                return false;
3587 >            action.accept(new MapEntry<K,V>(p.key, p.val, map));
3588 >            return true;
3589 >        }
3590 >
3591 >        public long estimateSize() { return est; }
3592 >
3593 >        public int characteristics() {
3594 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3595 >                Spliterator.NONNULL;
3596          }
3597      }
3598  
3599 <    // -------------------------------------------------------
3599 >    // Parallel bulk operations
3600  
3601 <    // Sequential bulk operations
3601 >    /**
3602 >     * Computes initial batch value for bulk tasks. The returned value
3603 >     * is approximately exp2 of the number of times (minus one) to
3604 >     * split task by two before executing leaf action. This value is
3605 >     * faster to compute and more convenient to use as a guide to
3606 >     * splitting than is the depth, since it is used while dividing by
3607 >     * two anyway.
3608 >     */
3609 >    final int batchFor(long b) {
3610 >        long n;
3611 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3612 >            return 0;
3613 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3614 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3615 >    }
3616  
3617      /**
3618       * Performs the given action for each (key, value).
3619       *
3620 +     * @param parallelismThreshold the (estimated) number of elements
3621 +     * needed for this operation to be executed in parallel
3622       * @param action the action
3623 +     * @since 1.8
3624       */
3625 <    public void forEachSequentially
3626 <        (BiConsumer<? super K, ? super V> action) {
3625 >    public void forEach(long parallelismThreshold,
3626 >                        BiConsumer<? super K,? super V> action) {
3627          if (action == null) throw new NullPointerException();
3628 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3629 <        V v;
3630 <        while ((v = it.advance()) != null)
3245 <            action.accept(it.nextKey, v);
3628 >        new ForEachMappingTask<K,V>
3629 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3630 >             action).invoke();
3631      }
3632  
3633      /**
3634       * Performs the given action for each non-null transformation
3635       * of each (key, value).
3636       *
3637 +     * @param parallelismThreshold the (estimated) number of elements
3638 +     * needed for this operation to be executed in parallel
3639       * @param transformer a function returning the transformation
3640       * for an element, or null if there is no transformation (in
3641       * which case the action is not applied)
3642       * @param action the action
3643 +     * @param <U> the return type of the transformer
3644 +     * @since 1.8
3645       */
3646 <    public <U> void forEachSequentially
3647 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3648 <         Consumer<? super U> action) {
3646 >    public <U> void forEach(long parallelismThreshold,
3647 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3648 >                            Consumer<? super U> action) {
3649          if (transformer == null || action == null)
3650              throw new NullPointerException();
3651 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3652 <        V v; U u;
3653 <        while ((v = it.advance()) != null) {
3265 <            if ((u = transformer.apply(it.nextKey, v)) != null)
3266 <                action.accept(u);
3267 <        }
3651 >        new ForEachTransformedMappingTask<K,V,U>
3652 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3653 >             transformer, action).invoke();
3654      }
3655  
3656      /**
3657       * Returns a non-null result from applying the given search
3658 <     * function on each (key, value), or null if none.
3658 >     * function on each (key, value), or null if none.  Upon
3659 >     * success, further element processing is suppressed and the
3660 >     * results of any other parallel invocations of the search
3661 >     * function are ignored.
3662       *
3663 +     * @param parallelismThreshold the (estimated) number of elements
3664 +     * needed for this operation to be executed in parallel
3665       * @param searchFunction a function returning a non-null
3666       * result on success, else null
3667 +     * @param <U> the return type of the search function
3668       * @return a non-null result from applying the given search
3669       * function on each (key, value), or null if none
3670 +     * @since 1.8
3671       */
3672 <    public <U> U searchSequentially
3673 <        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3672 >    public <U> U search(long parallelismThreshold,
3673 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3674          if (searchFunction == null) throw new NullPointerException();
3675 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3676 <        V v; U u;
3677 <        while ((v = it.advance()) != null) {
3285 <            if ((u = searchFunction.apply(it.nextKey, v)) != null)
3286 <                return u;
3287 <        }
3288 <        return null;
3675 >        return new SearchMappingsTask<K,V,U>
3676 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3677 >             searchFunction, new AtomicReference<U>()).invoke();
3678      }
3679  
3680      /**
# Line 3293 | Line 3682 | public class ConcurrentHashMap<K, V>
3682       * of all (key, value) pairs using the given reducer to
3683       * combine values, or null if none.
3684       *
3685 +     * @param parallelismThreshold the (estimated) number of elements
3686 +     * needed for this operation to be executed in parallel
3687       * @param transformer a function returning the transformation
3688       * for an element, or null if there is no transformation (in
3689       * which case it is not combined)
3690       * @param reducer a commutative associative combining function
3691 +     * @param <U> the return type of the transformer
3692       * @return the result of accumulating the given transformation
3693       * of all (key, value) pairs
3694 +     * @since 1.8
3695       */
3696 <    public <U> U reduceSequentially
3697 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3698 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
3696 >    public <U> U reduce(long parallelismThreshold,
3697 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3698 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3699          if (transformer == null || reducer == null)
3700              throw new NullPointerException();
3701 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3702 <        U r = null, u; V v;
3703 <        while ((v = it.advance()) != null) {
3311 <            if ((u = transformer.apply(it.nextKey, v)) != null)
3312 <                r = (r == null) ? u : reducer.apply(r, u);
3313 <        }
3314 <        return r;
3701 >        return new MapReduceMappingsTask<K,V,U>
3702 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3703 >             null, transformer, reducer).invoke();
3704      }
3705  
3706      /**
# Line 3319 | Line 3708 | public class ConcurrentHashMap<K, V>
3708       * of all (key, value) pairs using the given reducer to
3709       * combine values, and the given basis as an identity value.
3710       *
3711 +     * @param parallelismThreshold the (estimated) number of elements
3712 +     * needed for this operation to be executed in parallel
3713       * @param transformer a function returning the transformation
3714       * for an element
3715       * @param basis the identity (initial default value) for the reduction
3716       * @param reducer a commutative associative combining function
3717       * @return the result of accumulating the given transformation
3718       * of all (key, value) pairs
3719 +     * @since 1.8
3720       */
3721 <    public double reduceToDoubleSequentially
3722 <        (ToDoubleBiFunction<? super K, ? super V> transformer,
3723 <         double basis,
3724 <         DoubleBinaryOperator reducer) {
3721 >    public double reduceToDouble(long parallelismThreshold,
3722 >                                 ToDoubleBiFunction<? super K, ? super V> transformer,
3723 >                                 double basis,
3724 >                                 DoubleBinaryOperator reducer) {
3725          if (transformer == null || reducer == null)
3726              throw new NullPointerException();
3727 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3728 <        double r = basis; V v;
3729 <        while ((v = it.advance()) != null)
3338 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey, v));
3339 <        return r;
3727 >        return new MapReduceMappingsToDoubleTask<K,V>
3728 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3729 >             null, transformer, basis, reducer).invoke();
3730      }
3731  
3732      /**
# Line 3344 | Line 3734 | public class ConcurrentHashMap<K, V>
3734       * of all (key, value) pairs using the given reducer to
3735       * combine values, and the given basis as an identity value.
3736       *
3737 +     * @param parallelismThreshold the (estimated) number of elements
3738 +     * needed for this operation to be executed in parallel
3739       * @param transformer a function returning the transformation
3740       * for an element
3741       * @param basis the identity (initial default value) for the reduction
3742       * @param reducer a commutative associative combining function
3743       * @return the result of accumulating the given transformation
3744       * of all (key, value) pairs
3745 +     * @since 1.8
3746       */
3747 <    public long reduceToLongSequentially
3748 <        (ToLongBiFunction<? super K, ? super V> transformer,
3749 <         long basis,
3750 <         LongBinaryOperator reducer) {
3747 >    public long reduceToLong(long parallelismThreshold,
3748 >                             ToLongBiFunction<? super K, ? super V> transformer,
3749 >                             long basis,
3750 >                             LongBinaryOperator reducer) {
3751          if (transformer == null || reducer == null)
3752              throw new NullPointerException();
3753 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3754 <        long r = basis; V v;
3755 <        while ((v = it.advance()) != null)
3363 <            r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey, v));
3364 <        return r;
3753 >        return new MapReduceMappingsToLongTask<K,V>
3754 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3755 >             null, transformer, basis, reducer).invoke();
3756      }
3757  
3758      /**
# Line 3369 | Line 3760 | public class ConcurrentHashMap<K, V>
3760       * of all (key, value) pairs using the given reducer to
3761       * combine values, and the given basis as an identity value.
3762       *
3763 +     * @param parallelismThreshold the (estimated) number of elements
3764 +     * needed for this operation to be executed in parallel
3765       * @param transformer a function returning the transformation
3766       * for an element
3767       * @param basis the identity (initial default value) for the reduction
3768       * @param reducer a commutative associative combining function
3769       * @return the result of accumulating the given transformation
3770       * of all (key, value) pairs
3771 +     * @since 1.8
3772       */
3773 <    public int reduceToIntSequentially
3774 <        (ToIntBiFunction<? super K, ? super V> transformer,
3775 <         int basis,
3776 <         IntBinaryOperator reducer) {
3773 >    public int reduceToInt(long parallelismThreshold,
3774 >                           ToIntBiFunction<? super K, ? super V> transformer,
3775 >                           int basis,
3776 >                           IntBinaryOperator reducer) {
3777          if (transformer == null || reducer == null)
3778              throw new NullPointerException();
3779 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3780 <        int r = basis; V v;
3781 <        while ((v = it.advance()) != null)
3388 <            r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey, v));
3389 <        return r;
3779 >        return new MapReduceMappingsToIntTask<K,V>
3780 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3781 >             null, transformer, basis, reducer).invoke();
3782      }
3783  
3784      /**
3785       * Performs the given action for each key.
3786       *
3787 +     * @param parallelismThreshold the (estimated) number of elements
3788 +     * needed for this operation to be executed in parallel
3789       * @param action the action
3790 +     * @since 1.8
3791       */
3792 <    public void forEachKeySequentially
3793 <        (Consumer<? super K> action) {
3792 >    public void forEachKey(long parallelismThreshold,
3793 >                           Consumer<? super K> action) {
3794          if (action == null) throw new NullPointerException();
3795 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3796 <        while (it.advance() != null)
3797 <            action.accept(it.nextKey);
3795 >        new ForEachKeyTask<K,V>
3796 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3797 >             action).invoke();
3798      }
3799  
3800      /**
3801       * Performs the given action for each non-null transformation
3802       * of each key.
3803       *
3804 +     * @param parallelismThreshold the (estimated) number of elements
3805 +     * needed for this operation to be executed in parallel
3806       * @param transformer a function returning the transformation
3807       * for an element, or null if there is no transformation (in
3808       * which case the action is not applied)
3809       * @param action the action
3810 +     * @param <U> the return type of the transformer
3811 +     * @since 1.8
3812       */
3813 <    public <U> void forEachKeySequentially
3814 <        (Function<? super K, ? extends U> transformer,
3815 <         Consumer<? super U> action) {
3813 >    public <U> void forEachKey(long parallelismThreshold,
3814 >                               Function<? super K, ? extends U> transformer,
3815 >                               Consumer<? super U> action) {
3816          if (transformer == null || action == null)
3817              throw new NullPointerException();
3818 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3819 <        U u;
3820 <        while (it.advance() != null) {
3422 <            if ((u = transformer.apply(it.nextKey)) != null)
3423 <                action.accept(u);
3424 <        }
3425 <        ForkJoinTasks.forEachKey
3426 <            (this, transformer, action).invoke();
3818 >        new ForEachTransformedKeyTask<K,V,U>
3819 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3820 >             transformer, action).invoke();
3821      }
3822  
3823      /**
3824       * Returns a non-null result from applying the given search
3825 <     * function on each key, or null if none.
3825 >     * function on each key, or null if none. Upon success,
3826 >     * further element processing is suppressed and the results of
3827 >     * any other parallel invocations of the search function are
3828 >     * ignored.
3829       *
3830 +     * @param parallelismThreshold the (estimated) number of elements
3831 +     * needed for this operation to be executed in parallel
3832       * @param searchFunction a function returning a non-null
3833       * result on success, else null
3834 +     * @param <U> the return type of the search function
3835       * @return a non-null result from applying the given search
3836       * function on each key, or null if none
3837 +     * @since 1.8
3838       */
3839 <    public <U> U searchKeysSequentially
3840 <        (Function<? super K, ? extends U> searchFunction) {
3841 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3842 <        U u;
3843 <        while (it.advance() != null) {
3844 <            if ((u = searchFunction.apply(it.nextKey)) != null)
3444 <                return u;
3445 <        }
3446 <        return null;
3839 >    public <U> U searchKeys(long parallelismThreshold,
3840 >                            Function<? super K, ? extends U> searchFunction) {
3841 >        if (searchFunction == null) throw new NullPointerException();
3842 >        return new SearchKeysTask<K,V,U>
3843 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3844 >             searchFunction, new AtomicReference<U>()).invoke();
3845      }
3846  
3847      /**
3848       * Returns the result of accumulating all keys using the given
3849       * reducer to combine values, or null if none.
3850       *
3851 +     * @param parallelismThreshold the (estimated) number of elements
3852 +     * needed for this operation to be executed in parallel
3853       * @param reducer a commutative associative combining function
3854       * @return the result of accumulating all keys using the given
3855       * reducer to combine values, or null if none
3856 +     * @since 1.8
3857       */
3858 <    public K reduceKeysSequentially
3859 <        (BiFunction<? super K, ? super K, ? extends K> reducer) {
3858 >    public K reduceKeys(long parallelismThreshold,
3859 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3860          if (reducer == null) throw new NullPointerException();
3861 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3862 <        K r = null;
3863 <        while (it.advance() != null) {
3463 <            K u = it.nextKey;
3464 <            r = (r == null) ? u : reducer.apply(r, u);
3465 <        }
3466 <        return r;
3861 >        return new ReduceKeysTask<K,V>
3862 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3863 >             null, reducer).invoke();
3864      }
3865  
3866      /**
# Line 3471 | Line 3868 | public class ConcurrentHashMap<K, V>
3868       * of all keys using the given reducer to combine values, or
3869       * null if none.
3870       *
3871 +     * @param parallelismThreshold the (estimated) number of elements
3872 +     * needed for this operation to be executed in parallel
3873       * @param transformer a function returning the transformation
3874       * for an element, or null if there is no transformation (in
3875       * which case it is not combined)
3876       * @param reducer a commutative associative combining function
3877 +     * @param <U> the return type of the transformer
3878       * @return the result of accumulating the given transformation
3879       * of all keys
3880 +     * @since 1.8
3881       */
3882 <    public <U> U reduceKeysSequentially
3883 <        (Function<? super K, ? extends U> transformer,
3882 >    public <U> U reduceKeys(long parallelismThreshold,
3883 >                            Function<? super K, ? extends U> transformer,
3884           BiFunction<? super U, ? super U, ? extends U> reducer) {
3885          if (transformer == null || reducer == null)
3886              throw new NullPointerException();
3887 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3888 <        U r = null, u;
3889 <        while (it.advance() != null) {
3489 <            if ((u = transformer.apply(it.nextKey)) != null)
3490 <                r = (r == null) ? u : reducer.apply(r, u);
3491 <        }
3492 <        return r;
3887 >        return new MapReduceKeysTask<K,V,U>
3888 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3889 >             null, transformer, reducer).invoke();
3890      }
3891  
3892      /**
# Line 3497 | Line 3894 | public class ConcurrentHashMap<K, V>
3894       * of all keys using the given reducer to combine values, and
3895       * the given basis as an identity value.
3896       *
3897 +     * @param parallelismThreshold the (estimated) number of elements
3898 +     * needed for this operation to be executed in parallel
3899       * @param transformer a function returning the transformation
3900       * for an element
3901       * @param basis the identity (initial default value) for the reduction
3902       * @param reducer a commutative associative combining function
3903       * @return the result of accumulating the given transformation
3904       * of all keys
3905 +     * @since 1.8
3906       */
3907 <    public double reduceKeysToDoubleSequentially
3908 <        (ToDoubleFunction<? super K> transformer,
3909 <         double basis,
3910 <         DoubleBinaryOperator reducer) {
3907 >    public double reduceKeysToDouble(long parallelismThreshold,
3908 >                                     ToDoubleFunction<? super K> transformer,
3909 >                                     double basis,
3910 >                                     DoubleBinaryOperator reducer) {
3911          if (transformer == null || reducer == null)
3912              throw new NullPointerException();
3913 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3914 <        double r = basis;
3915 <        while (it.advance() != null)
3516 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey));
3517 <        return r;
3913 >        return new MapReduceKeysToDoubleTask<K,V>
3914 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3915 >             null, transformer, basis, reducer).invoke();
3916      }
3917  
3918      /**
# Line 3522 | Line 3920 | public class ConcurrentHashMap<K, V>
3920       * of all keys using the given reducer to combine values, and
3921       * the given basis as an identity value.
3922       *
3923 +     * @param parallelismThreshold the (estimated) number of elements
3924 +     * needed for this operation to be executed in parallel
3925       * @param transformer a function returning the transformation
3926       * for an element
3927       * @param basis the identity (initial default value) for the reduction
3928       * @param reducer a commutative associative combining function
3929       * @return the result of accumulating the given transformation
3930       * of all keys
3931 +     * @since 1.8
3932       */
3933 <    public long reduceKeysToLongSequentially
3934 <        (ToLongFunction<? super K> transformer,
3935 <         long basis,
3936 <         LongBinaryOperator reducer) {
3933 >    public long reduceKeysToLong(long parallelismThreshold,
3934 >                                 ToLongFunction<? super K> transformer,
3935 >                                 long basis,
3936 >                                 LongBinaryOperator reducer) {
3937          if (transformer == null || reducer == null)
3938              throw new NullPointerException();
3939 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3940 <        long r = basis;
3941 <        while (it.advance() != null)
3541 <            r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey));
3542 <        return r;
3939 >        return new MapReduceKeysToLongTask<K,V>
3940 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3941 >             null, transformer, basis, reducer).invoke();
3942      }
3943  
3944      /**
# Line 3547 | Line 3946 | public class ConcurrentHashMap<K, V>
3946       * of all keys using the given reducer to combine values, and
3947       * the given basis as an identity value.
3948       *
3949 +     * @param parallelismThreshold the (estimated) number of elements
3950 +     * needed for this operation to be executed in parallel
3951       * @param transformer a function returning the transformation
3952       * for an element
3953       * @param basis the identity (initial default value) for the reduction
3954       * @param reducer a commutative associative combining function
3955       * @return the result of accumulating the given transformation
3956       * of all keys
3957 +     * @since 1.8
3958       */
3959 <    public int reduceKeysToIntSequentially
3960 <        (ToIntFunction<? super K> transformer,
3961 <         int basis,
3962 <         IntBinaryOperator reducer) {
3959 >    public int reduceKeysToInt(long parallelismThreshold,
3960 >                               ToIntFunction<? super K> transformer,
3961 >                               int basis,
3962 >                               IntBinaryOperator reducer) {
3963          if (transformer == null || reducer == null)
3964              throw new NullPointerException();
3965 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3966 <        int r = basis;
3967 <        while (it.advance() != null)
3566 <            r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey));
3567 <        return r;
3965 >        return new MapReduceKeysToIntTask<K,V>
3966 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3967 >             null, transformer, basis, reducer).invoke();
3968      }
3969  
3970      /**
3971       * Performs the given action for each value.
3972       *
3973 +     * @param parallelismThreshold the (estimated) number of elements
3974 +     * needed for this operation to be executed in parallel
3975       * @param action the action
3976 +     * @since 1.8
3977       */
3978 <    public void forEachValueSequentially(Consumer<? super V> action) {
3979 <        if (action == null) throw new NullPointerException();
3980 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3981 <        V v;
3982 <        while ((v = it.advance()) != null)
3983 <            action.accept(v);
3978 >    public void forEachValue(long parallelismThreshold,
3979 >                             Consumer<? super V> action) {
3980 >        if (action == null)
3981 >            throw new NullPointerException();
3982 >        new ForEachValueTask<K,V>
3983 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3984 >             action).invoke();
3985      }
3986  
3987      /**
3988       * Performs the given action for each non-null transformation
3989       * of each value.
3990       *
3991 +     * @param parallelismThreshold the (estimated) number of elements
3992 +     * needed for this operation to be executed in parallel
3993       * @param transformer a function returning the transformation
3994       * for an element, or null if there is no transformation (in
3995       * which case the action is not applied)
3996 +     * @param action the action
3997 +     * @param <U> the return type of the transformer
3998 +     * @since 1.8
3999       */
4000 <    public <U> void forEachValueSequentially
4001 <        (Function<? super V, ? extends U> transformer,
4002 <         Consumer<? super U> action) {
4000 >    public <U> void forEachValue(long parallelismThreshold,
4001 >                                 Function<? super V, ? extends U> transformer,
4002 >                                 Consumer<? super U> action) {
4003          if (transformer == null || action == null)
4004              throw new NullPointerException();
4005 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4006 <        V v; U u;
4007 <        while ((v = it.advance()) != null) {
3599 <            if ((u = transformer.apply(v)) != null)
3600 <                action.accept(u);
3601 <        }
4005 >        new ForEachTransformedValueTask<K,V,U>
4006 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4007 >             transformer, action).invoke();
4008      }
4009  
4010      /**
4011       * Returns a non-null result from applying the given search
4012 <     * function on each value, or null if none.
4012 >     * function on each value, or null if none.  Upon success,
4013 >     * further element processing is suppressed and the results of
4014 >     * any other parallel invocations of the search function are
4015 >     * ignored.
4016       *
4017 +     * @param parallelismThreshold the (estimated) number of elements
4018 +     * needed for this operation to be executed in parallel
4019       * @param searchFunction a function returning a non-null
4020       * result on success, else null
4021 +     * @param <U> the return type of the search function
4022       * @return a non-null result from applying the given search
4023       * function on each value, or null if none
4024 +     * @since 1.8
4025       */
4026 <    public <U> U searchValuesSequentially
4027 <        (Function<? super V, ? extends U> searchFunction) {
4026 >    public <U> U searchValues(long parallelismThreshold,
4027 >                              Function<? super V, ? extends U> searchFunction) {
4028          if (searchFunction == null) throw new NullPointerException();
4029 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4030 <        V v; U u;
4031 <        while ((v = it.advance()) != null) {
3619 <            if ((u = searchFunction.apply(v)) != null)
3620 <                return u;
3621 <        }
3622 <        return null;
4029 >        return new SearchValuesTask<K,V,U>
4030 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4031 >             searchFunction, new AtomicReference<U>()).invoke();
4032      }
4033  
4034      /**
4035       * Returns the result of accumulating all values using the
4036       * given reducer to combine values, or null if none.
4037       *
4038 +     * @param parallelismThreshold the (estimated) number of elements
4039 +     * needed for this operation to be executed in parallel
4040       * @param reducer a commutative associative combining function
4041       * @return the result of accumulating all values
4042 +     * @since 1.8
4043       */
4044 <    public V reduceValuesSequentially
4045 <        (BiFunction<? super V, ? super V, ? extends V> reducer) {
4044 >    public V reduceValues(long parallelismThreshold,
4045 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
4046          if (reducer == null) throw new NullPointerException();
4047 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4048 <        V r = null; V v;
4049 <        while ((v = it.advance()) != null)
3638 <            r = (r == null) ? v : reducer.apply(r, v);
3639 <        return r;
4047 >        return new ReduceValuesTask<K,V>
4048 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4049 >             null, reducer).invoke();
4050      }
4051  
4052      /**
# Line 3644 | Line 4054 | public class ConcurrentHashMap<K, V>
4054       * of all values using the given reducer to combine values, or
4055       * null if none.
4056       *
4057 +     * @param parallelismThreshold the (estimated) number of elements
4058 +     * needed for this operation to be executed in parallel
4059       * @param transformer a function returning the transformation
4060       * for an element, or null if there is no transformation (in
4061       * which case it is not combined)
4062       * @param reducer a commutative associative combining function
4063 +     * @param <U> the return type of the transformer
4064       * @return the result of accumulating the given transformation
4065       * of all values
4066 +     * @since 1.8
4067       */
4068 <    public <U> U reduceValuesSequentially
4069 <        (Function<? super V, ? extends U> transformer,
4070 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4068 >    public <U> U reduceValues(long parallelismThreshold,
4069 >                              Function<? super V, ? extends U> transformer,
4070 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
4071          if (transformer == null || reducer == null)
4072              throw new NullPointerException();
4073 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4074 <        U r = null, u; V v;
4075 <        while ((v = it.advance()) != null) {
3662 <            if ((u = transformer.apply(v)) != null)
3663 <                r = (r == null) ? u : reducer.apply(r, u);
3664 <        }
3665 <        return r;
4073 >        return new MapReduceValuesTask<K,V,U>
4074 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4075 >             null, transformer, reducer).invoke();
4076      }
4077  
4078      /**
# Line 3670 | Line 4080 | public class ConcurrentHashMap<K, V>
4080       * of all values using the given reducer to combine values,
4081       * and the given basis as an identity value.
4082       *
4083 +     * @param parallelismThreshold the (estimated) number of elements
4084 +     * needed for this operation to be executed in parallel
4085       * @param transformer a function returning the transformation
4086       * for an element
4087       * @param basis the identity (initial default value) for the reduction
4088       * @param reducer a commutative associative combining function
4089       * @return the result of accumulating the given transformation
4090       * of all values
4091 +     * @since 1.8
4092       */
4093 <    public double reduceValuesToDoubleSequentially
4094 <        (ToDoubleFunction<? super V> transformer,
4095 <         double basis,
4096 <         DoubleBinaryOperator reducer) {
4093 >    public double reduceValuesToDouble(long parallelismThreshold,
4094 >                                       ToDoubleFunction<? super V> transformer,
4095 >                                       double basis,
4096 >                                       DoubleBinaryOperator reducer) {
4097          if (transformer == null || reducer == null)
4098              throw new NullPointerException();
4099 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4100 <        double r = basis; V v;
4101 <        while ((v = it.advance()) != null)
3689 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
3690 <        return r;
4099 >        return new MapReduceValuesToDoubleTask<K,V>
4100 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4101 >             null, transformer, basis, reducer).invoke();
4102      }
4103  
4104      /**
# Line 3695 | Line 4106 | public class ConcurrentHashMap<K, V>
4106       * of all values using the given reducer to combine values,
4107       * and the given basis as an identity value.
4108       *
4109 +     * @param parallelismThreshold the (estimated) number of elements
4110 +     * needed for this operation to be executed in parallel
4111       * @param transformer a function returning the transformation
4112       * for an element
4113       * @param basis the identity (initial default value) for the reduction
4114       * @param reducer a commutative associative combining function
4115       * @return the result of accumulating the given transformation
4116       * of all values
4117 +     * @since 1.8
4118       */
4119 <    public long reduceValuesToLongSequentially
4120 <        (ToLongFunction<? super V> transformer,
4121 <         long basis,
4122 <         LongBinaryOperator reducer) {
4119 >    public long reduceValuesToLong(long parallelismThreshold,
4120 >                                   ToLongFunction<? super V> transformer,
4121 >                                   long basis,
4122 >                                   LongBinaryOperator reducer) {
4123          if (transformer == null || reducer == null)
4124              throw new NullPointerException();
4125 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4126 <        long r = basis; V v;
4127 <        while ((v = it.advance()) != null)
3714 <            r = reducer.applyAsLong(r, transformer.applyAsLong(v));
3715 <        return r;
4125 >        return new MapReduceValuesToLongTask<K,V>
4126 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4127 >             null, transformer, basis, reducer).invoke();
4128      }
4129  
4130      /**
# Line 3720 | Line 4132 | public class ConcurrentHashMap<K, V>
4132       * of all values using the given reducer to combine values,
4133       * and the given basis as an identity value.
4134       *
4135 +     * @param parallelismThreshold the (estimated) number of elements
4136 +     * needed for this operation to be executed in parallel
4137       * @param transformer a function returning the transformation
4138       * for an element
4139       * @param basis the identity (initial default value) for the reduction
4140       * @param reducer a commutative associative combining function
4141       * @return the result of accumulating the given transformation
4142       * of all values
4143 +     * @since 1.8
4144       */
4145 <    public int reduceValuesToIntSequentially
4146 <        (ToIntFunction<? super V> transformer,
4147 <         int basis,
4148 <         IntBinaryOperator reducer) {
4145 >    public int reduceValuesToInt(long parallelismThreshold,
4146 >                                 ToIntFunction<? super V> transformer,
4147 >                                 int basis,
4148 >                                 IntBinaryOperator reducer) {
4149          if (transformer == null || reducer == null)
4150              throw new NullPointerException();
4151 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4152 <        int r = basis; V v;
4153 <        while ((v = it.advance()) != null)
3739 <            r = reducer.applyAsInt(r, transformer.applyAsInt(v));
3740 <        return r;
4151 >        return new MapReduceValuesToIntTask<K,V>
4152 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4153 >             null, transformer, basis, reducer).invoke();
4154      }
4155  
4156      /**
4157       * Performs the given action for each entry.
4158       *
4159 +     * @param parallelismThreshold the (estimated) number of elements
4160 +     * needed for this operation to be executed in parallel
4161       * @param action the action
4162 +     * @since 1.8
4163       */
4164 <    public void forEachEntrySequentially
4165 <        (Consumer<? super Map.Entry<K,V>> action) {
4164 >    public void forEachEntry(long parallelismThreshold,
4165 >                             Consumer<? super Map.Entry<K,V>> action) {
4166          if (action == null) throw new NullPointerException();
4167 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4168 <        V v;
3753 <        while ((v = it.advance()) != null)
3754 <            action.accept(entryFor(it.nextKey, v));
4167 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4168 >                                  action).invoke();
4169      }
4170  
4171      /**
4172       * Performs the given action for each non-null transformation
4173       * of each entry.
4174       *
4175 +     * @param parallelismThreshold the (estimated) number of elements
4176 +     * needed for this operation to be executed in parallel
4177       * @param transformer a function returning the transformation
4178       * for an element, or null if there is no transformation (in
4179       * which case the action is not applied)
4180       * @param action the action
4181 +     * @param <U> the return type of the transformer
4182 +     * @since 1.8
4183       */
4184 <    public <U> void forEachEntrySequentially
4185 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4186 <         Consumer<? super U> action) {
4184 >    public <U> void forEachEntry(long parallelismThreshold,
4185 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
4186 >                                 Consumer<? super U> action) {
4187          if (transformer == null || action == null)
4188              throw new NullPointerException();
4189 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4190 <        V v; U u;
4191 <        while ((v = it.advance()) != null) {
3774 <            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3775 <                action.accept(u);
3776 <        }
4189 >        new ForEachTransformedEntryTask<K,V,U>
4190 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4191 >             transformer, action).invoke();
4192      }
4193  
4194      /**
4195       * Returns a non-null result from applying the given search
4196 <     * function on each entry, or null if none.
4196 >     * function on each entry, or null if none.  Upon success,
4197 >     * further element processing is suppressed and the results of
4198 >     * any other parallel invocations of the search function are
4199 >     * ignored.
4200       *
4201 +     * @param parallelismThreshold the (estimated) number of elements
4202 +     * needed for this operation to be executed in parallel
4203       * @param searchFunction a function returning a non-null
4204       * result on success, else null
4205 +     * @param <U> the return type of the search function
4206       * @return a non-null result from applying the given search
4207       * function on each entry, or null if none
4208 +     * @since 1.8
4209       */
4210 <    public <U> U searchEntriesSequentially
4211 <        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4210 >    public <U> U searchEntries(long parallelismThreshold,
4211 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4212          if (searchFunction == null) throw new NullPointerException();
4213 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4214 <        V v; U u;
4215 <        while ((v = it.advance()) != null) {
3794 <            if ((u = searchFunction.apply(entryFor(it.nextKey, v))) != null)
3795 <                return u;
3796 <        }
3797 <        return null;
4213 >        return new SearchEntriesTask<K,V,U>
4214 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4215 >             searchFunction, new AtomicReference<U>()).invoke();
4216      }
4217  
4218      /**
4219       * Returns the result of accumulating all entries using the
4220       * given reducer to combine values, or null if none.
4221       *
4222 +     * @param parallelismThreshold the (estimated) number of elements
4223 +     * needed for this operation to be executed in parallel
4224       * @param reducer a commutative associative combining function
4225       * @return the result of accumulating all entries
4226 +     * @since 1.8
4227       */
4228 <    public Map.Entry<K,V> reduceEntriesSequentially
4229 <        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4228 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4229 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4230          if (reducer == null) throw new NullPointerException();
4231 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4232 <        Map.Entry<K,V> r = null; V v;
4233 <        while ((v = it.advance()) != null) {
3813 <            Map.Entry<K,V> u = entryFor(it.nextKey, v);
3814 <            r = (r == null) ? u : reducer.apply(r, u);
3815 <        }
3816 <        return r;
4231 >        return new ReduceEntriesTask<K,V>
4232 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4233 >             null, reducer).invoke();
4234      }
4235  
4236      /**
# Line 3821 | Line 4238 | public class ConcurrentHashMap<K, V>
4238       * of all entries using the given reducer to combine values,
4239       * or null if none.
4240       *
4241 +     * @param parallelismThreshold the (estimated) number of elements
4242 +     * needed for this operation to be executed in parallel
4243       * @param transformer a function returning the transformation
4244       * for an element, or null if there is no transformation (in
4245       * which case it is not combined)
4246       * @param reducer a commutative associative combining function
4247 +     * @param <U> the return type of the transformer
4248       * @return the result of accumulating the given transformation
4249       * of all entries
4250 +     * @since 1.8
4251       */
4252 <    public <U> U reduceEntriesSequentially
4253 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4254 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4252 >    public <U> U reduceEntries(long parallelismThreshold,
4253 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
4254 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
4255          if (transformer == null || reducer == null)
4256              throw new NullPointerException();
4257 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4258 <        U r = null, u; V v;
4259 <        while ((v = it.advance()) != null) {
3839 <            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3840 <                r = (r == null) ? u : reducer.apply(r, u);
3841 <        }
3842 <        return r;
4257 >        return new MapReduceEntriesTask<K,V,U>
4258 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4259 >             null, transformer, reducer).invoke();
4260      }
4261  
4262      /**
# Line 3847 | Line 4264 | public class ConcurrentHashMap<K, V>
4264       * of all entries using the given reducer to combine values,
4265       * and the given basis as an identity value.
4266       *
4267 +     * @param parallelismThreshold the (estimated) number of elements
4268 +     * needed for this operation to be executed in parallel
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 entries
4275 +     * @since 1.8
4276       */
4277 <    public double reduceEntriesToDoubleSequentially
4278 <        (ToDoubleFunction<Map.Entry<K,V>> transformer,
4279 <         double basis,
4280 <         DoubleBinaryOperator reducer) {
4277 >    public double reduceEntriesToDouble(long parallelismThreshold,
4278 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
4279 >                                        double basis,
4280 >                                        DoubleBinaryOperator reducer) {
4281          if (transformer == null || reducer == null)
4282              throw new NullPointerException();
4283 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4284 <        double r = basis; V v;
4285 <        while ((v = it.advance()) != null)
3866 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(it.nextKey, v)));
3867 <        return r;
4283 >        return new MapReduceEntriesToDoubleTask<K,V>
4284 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4285 >             null, transformer, basis, reducer).invoke();
4286      }
4287  
4288      /**
# Line 3872 | Line 4290 | public class ConcurrentHashMap<K, V>
4290       * of all entries using the given reducer to combine values,
4291       * and the given basis as an identity value.
4292       *
4293 +     * @param parallelismThreshold the (estimated) number of elements
4294 +     * needed for this operation to be executed in parallel
4295       * @param transformer a function returning the transformation
4296       * for an element
4297       * @param basis the identity (initial default value) for the reduction
4298       * @param reducer a commutative associative combining function
4299       * @return the result of accumulating the given transformation
4300       * of all entries
4301 +     * @since 1.8
4302       */
4303 <    public long reduceEntriesToLongSequentially
4304 <        (ToLongFunction<Map.Entry<K,V>> transformer,
4305 <         long basis,
4306 <         LongBinaryOperator reducer) {
4303 >    public long reduceEntriesToLong(long parallelismThreshold,
4304 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
4305 >                                    long basis,
4306 >                                    LongBinaryOperator reducer) {
4307          if (transformer == null || reducer == null)
4308              throw new NullPointerException();
4309 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4310 <        long r = basis; V v;
4311 <        while ((v = it.advance()) != null)
3891 <            r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(it.nextKey, v)));
3892 <        return r;
4309 >        return new MapReduceEntriesToLongTask<K,V>
4310 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4311 >             null, transformer, basis, reducer).invoke();
4312      }
4313  
4314      /**
# Line 3897 | Line 4316 | public class ConcurrentHashMap<K, V>
4316       * of all entries using the given reducer to combine values,
4317       * and the given basis as an identity value.
4318       *
4319 +     * @param parallelismThreshold the (estimated) number of elements
4320 +     * needed for this operation to be executed in parallel
4321       * @param transformer a function returning the transformation
4322       * for an element
4323       * @param basis the identity (initial default value) for the reduction
4324       * @param reducer a commutative associative combining function
4325       * @return the result of accumulating the given transformation
4326       * of all entries
4327 +     * @since 1.8
4328       */
4329 <    public int reduceEntriesToIntSequentially
4330 <        (ToIntFunction<Map.Entry<K,V>> transformer,
4331 <         int basis,
4332 <         IntBinaryOperator reducer) {
4329 >    public int reduceEntriesToInt(long parallelismThreshold,
4330 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
4331 >                                  int basis,
4332 >                                  IntBinaryOperator reducer) {
4333          if (transformer == null || reducer == null)
4334              throw new NullPointerException();
4335 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4336 <        int r = basis; V v;
4337 <        while ((v = it.advance()) != null)
3916 <            r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(it.nextKey, v)));
3917 <        return r;
3918 <    }
3919 <
3920 <    // Parallel bulk operations
3921 <
3922 <    /**
3923 <     * Performs the given action for each (key, value).
3924 <     *
3925 <     * @param action the action
3926 <     */
3927 <    public void forEachInParallel(BiConsumer<? super K,? super V> action) {
3928 <        ForkJoinTasks.forEach
3929 <            (this, action).invoke();
3930 <    }
3931 <
3932 <    /**
3933 <     * Performs the given action for each non-null transformation
3934 <     * of each (key, value).
3935 <     *
3936 <     * @param transformer a function returning the transformation
3937 <     * for an element, or null if there is no transformation (in
3938 <     * which case the action is not applied)
3939 <     * @param action the action
3940 <     */
3941 <    public <U> void forEachInParallel
3942 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3943 <                            Consumer<? super U> action) {
3944 <        ForkJoinTasks.forEach
3945 <            (this, transformer, action).invoke();
3946 <    }
3947 <
3948 <    /**
3949 <     * Returns a non-null result from applying the given search
3950 <     * function on each (key, value), or null if none.  Upon
3951 <     * success, further element processing is suppressed and the
3952 <     * results of any other parallel invocations of the search
3953 <     * function are ignored.
3954 <     *
3955 <     * @param searchFunction a function returning a non-null
3956 <     * result on success, else null
3957 <     * @return a non-null result from applying the given search
3958 <     * function on each (key, value), or null if none
3959 <     */
3960 <    public <U> U searchInParallel
3961 <        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3962 <        return ForkJoinTasks.search
3963 <            (this, searchFunction).invoke();
3964 <    }
3965 <
3966 <    /**
3967 <     * Returns the result of accumulating the given transformation
3968 <     * of all (key, value) pairs using the given reducer to
3969 <     * combine values, or null if none.
3970 <     *
3971 <     * @param transformer a function returning the transformation
3972 <     * for an element, or null if there is no transformation (in
3973 <     * which case it is not combined)
3974 <     * @param reducer a commutative associative combining function
3975 <     * @return the result of accumulating the given transformation
3976 <     * of all (key, value) pairs
3977 <     */
3978 <    public <U> U reduceInParallel
3979 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3980 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
3981 <        return ForkJoinTasks.reduce
3982 <            (this, transformer, reducer).invoke();
3983 <    }
3984 <
3985 <    /**
3986 <     * Returns the result of accumulating the given transformation
3987 <     * of all (key, value) pairs using the given reducer to
3988 <     * combine values, and the given basis as an identity value.
3989 <     *
3990 <     * @param transformer a function returning the transformation
3991 <     * for an element
3992 <     * @param basis the identity (initial default value) for the reduction
3993 <     * @param reducer a commutative associative combining function
3994 <     * @return the result of accumulating the given transformation
3995 <     * of all (key, value) pairs
3996 <     */
3997 <    public double reduceToDoubleInParallel
3998 <        (ToDoubleBiFunction<? super K, ? super V> transformer,
3999 <         double basis,
4000 <         DoubleBinaryOperator reducer) {
4001 <        return ForkJoinTasks.reduceToDouble
4002 <            (this, transformer, basis, reducer).invoke();
4003 <    }
4004 <
4005 <    /**
4006 <     * Returns the result of accumulating the given transformation
4007 <     * of all (key, value) pairs using the given reducer to
4008 <     * combine values, and the given basis as an identity value.
4009 <     *
4010 <     * @param transformer a function returning the transformation
4011 <     * for an element
4012 <     * @param basis the identity (initial default value) for the reduction
4013 <     * @param reducer a commutative associative combining function
4014 <     * @return the result of accumulating the given transformation
4015 <     * of all (key, value) pairs
4016 <     */
4017 <    public long reduceToLongInParallel
4018 <        (ToLongBiFunction<? super K, ? super V> transformer,
4019 <         long basis,
4020 <         LongBinaryOperator reducer) {
4021 <        return ForkJoinTasks.reduceToLong
4022 <            (this, transformer, basis, reducer).invoke();
4023 <    }
4024 <
4025 <    /**
4026 <     * Returns the result of accumulating the given transformation
4027 <     * of all (key, value) pairs using the given reducer to
4028 <     * combine values, and the given basis as an identity value.
4029 <     *
4030 <     * @param transformer a function returning the transformation
4031 <     * for an element
4032 <     * @param basis the identity (initial default value) for the reduction
4033 <     * @param reducer a commutative associative combining function
4034 <     * @return the result of accumulating the given transformation
4035 <     * of all (key, value) pairs
4036 <     */
4037 <    public int reduceToIntInParallel
4038 <        (ToIntBiFunction<? super K, ? super V> transformer,
4039 <         int basis,
4040 <         IntBinaryOperator reducer) {
4041 <        return ForkJoinTasks.reduceToInt
4042 <            (this, transformer, basis, reducer).invoke();
4043 <    }
4044 <
4045 <    /**
4046 <     * Performs the given action for each key.
4047 <     *
4048 <     * @param action the action
4049 <     */
4050 <    public void forEachKeyInParallel(Consumer<? super K> action) {
4051 <        ForkJoinTasks.forEachKey
4052 <            (this, action).invoke();
4053 <    }
4054 <
4055 <    /**
4056 <     * Performs the given action for each non-null transformation
4057 <     * of each key.
4058 <     *
4059 <     * @param transformer a function returning the transformation
4060 <     * for an element, or null if there is no transformation (in
4061 <     * which case the action is not applied)
4062 <     * @param action the action
4063 <     */
4064 <    public <U> void forEachKeyInParallel
4065 <        (Function<? super K, ? extends U> transformer,
4066 <         Consumer<? super U> action) {
4067 <        ForkJoinTasks.forEachKey
4068 <            (this, transformer, action).invoke();
4069 <    }
4070 <
4071 <    /**
4072 <     * Returns a non-null result from applying the given search
4073 <     * function on each key, or null if none. Upon success,
4074 <     * further element processing is suppressed and the results of
4075 <     * any other parallel invocations of the search function are
4076 <     * ignored.
4077 <     *
4078 <     * @param searchFunction a function returning a non-null
4079 <     * result on success, else null
4080 <     * @return a non-null result from applying the given search
4081 <     * function on each key, or null if none
4082 <     */
4083 <    public <U> U searchKeysInParallel
4084 <        (Function<? super K, ? extends U> searchFunction) {
4085 <        return ForkJoinTasks.searchKeys
4086 <            (this, searchFunction).invoke();
4087 <    }
4088 <
4089 <    /**
4090 <     * Returns the result of accumulating all keys using the given
4091 <     * reducer to combine values, or null if none.
4092 <     *
4093 <     * @param reducer a commutative associative combining function
4094 <     * @return the result of accumulating all keys using the given
4095 <     * reducer to combine values, or null if none
4096 <     */
4097 <    public K reduceKeysInParallel
4098 <        (BiFunction<? super K, ? super K, ? extends K> reducer) {
4099 <        return ForkJoinTasks.reduceKeys
4100 <            (this, reducer).invoke();
4101 <    }
4102 <
4103 <    /**
4104 <     * Returns the result of accumulating the given transformation
4105 <     * of all keys using the given reducer to combine values, or
4106 <     * null if none.
4107 <     *
4108 <     * @param transformer a function returning the transformation
4109 <     * for an element, or null if there is no transformation (in
4110 <     * which case it is not combined)
4111 <     * @param reducer a commutative associative combining function
4112 <     * @return the result of accumulating the given transformation
4113 <     * of all keys
4114 <     */
4115 <    public <U> U reduceKeysInParallel
4116 <        (Function<? super K, ? extends U> transformer,
4117 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4118 <        return ForkJoinTasks.reduceKeys
4119 <            (this, transformer, reducer).invoke();
4120 <    }
4121 <
4122 <    /**
4123 <     * Returns the result of accumulating the given transformation
4124 <     * of all keys using the given reducer to combine values, and
4125 <     * the given basis as an identity value.
4126 <     *
4127 <     * @param transformer a function returning the transformation
4128 <     * for an element
4129 <     * @param basis the identity (initial default value) for the reduction
4130 <     * @param reducer a commutative associative combining function
4131 <     * @return the result of accumulating the given transformation
4132 <     * of all keys
4133 <     */
4134 <    public double reduceKeysToDoubleInParallel
4135 <        (ToDoubleFunction<? super K> transformer,
4136 <         double basis,
4137 <         DoubleBinaryOperator reducer) {
4138 <        return ForkJoinTasks.reduceKeysToDouble
4139 <            (this, transformer, basis, reducer).invoke();
4140 <    }
4141 <
4142 <    /**
4143 <     * Returns the result of accumulating the given transformation
4144 <     * of all keys using the given reducer to combine values, and
4145 <     * the given basis as an identity value.
4146 <     *
4147 <     * @param transformer a function returning the transformation
4148 <     * for an element
4149 <     * @param basis the identity (initial default value) for the reduction
4150 <     * @param reducer a commutative associative combining function
4151 <     * @return the result of accumulating the given transformation
4152 <     * of all keys
4153 <     */
4154 <    public long reduceKeysToLongInParallel
4155 <        (ToLongFunction<? super K> transformer,
4156 <         long basis,
4157 <         LongBinaryOperator reducer) {
4158 <        return ForkJoinTasks.reduceKeysToLong
4159 <            (this, transformer, basis, reducer).invoke();
4160 <    }
4161 <
4162 <    /**
4163 <     * Returns the result of accumulating the given transformation
4164 <     * of all keys using the given reducer to combine values, and
4165 <     * the given basis as an identity value.
4166 <     *
4167 <     * @param transformer a function returning the transformation
4168 <     * for an element
4169 <     * @param basis the identity (initial default value) for the reduction
4170 <     * @param reducer a commutative associative combining function
4171 <     * @return the result of accumulating the given transformation
4172 <     * of all keys
4173 <     */
4174 <    public int reduceKeysToIntInParallel
4175 <        (ToIntFunction<? super K> transformer,
4176 <         int basis,
4177 <         IntBinaryOperator reducer) {
4178 <        return ForkJoinTasks.reduceKeysToInt
4179 <            (this, transformer, basis, reducer).invoke();
4180 <    }
4181 <
4182 <    /**
4183 <     * Performs the given action for each value.
4184 <     *
4185 <     * @param action the action
4186 <     */
4187 <    public void forEachValueInParallel(Consumer<? super V> action) {
4188 <        ForkJoinTasks.forEachValue
4189 <            (this, action).invoke();
4190 <    }
4191 <
4192 <    /**
4193 <     * Performs the given action for each non-null transformation
4194 <     * of each value.
4195 <     *
4196 <     * @param transformer a function returning the transformation
4197 <     * for an element, or null if there is no transformation (in
4198 <     * which case the action is not applied)
4199 <     */
4200 <    public <U> void forEachValueInParallel
4201 <        (Function<? super V, ? extends U> transformer,
4202 <         Consumer<? super U> action) {
4203 <        ForkJoinTasks.forEachValue
4204 <            (this, transformer, action).invoke();
4205 <    }
4206 <
4207 <    /**
4208 <     * Returns a non-null result from applying the given search
4209 <     * function on each value, or null if none.  Upon success,
4210 <     * further element processing is suppressed and the results of
4211 <     * any other parallel invocations of the search function are
4212 <     * ignored.
4213 <     *
4214 <     * @param searchFunction a function returning a non-null
4215 <     * result on success, else null
4216 <     * @return a non-null result from applying the given search
4217 <     * function on each value, or null if none
4218 <     */
4219 <    public <U> U searchValuesInParallel
4220 <        (Function<? super V, ? extends U> searchFunction) {
4221 <        return ForkJoinTasks.searchValues
4222 <            (this, searchFunction).invoke();
4223 <    }
4224 <
4225 <    /**
4226 <     * Returns the result of accumulating all values using the
4227 <     * given reducer to combine values, or null if none.
4228 <     *
4229 <     * @param reducer a commutative associative combining function
4230 <     * @return the result of accumulating all values
4231 <     */
4232 <    public V reduceValuesInParallel
4233 <        (BiFunction<? super V, ? super V, ? extends V> reducer) {
4234 <        return ForkJoinTasks.reduceValues
4235 <            (this, reducer).invoke();
4236 <    }
4237 <
4238 <    /**
4239 <     * Returns the result of accumulating the given transformation
4240 <     * of all values using the given reducer to combine values, or
4241 <     * null if none.
4242 <     *
4243 <     * @param transformer a function returning the transformation
4244 <     * for an element, or null if there is no transformation (in
4245 <     * which case it is not combined)
4246 <     * @param reducer a commutative associative combining function
4247 <     * @return the result of accumulating the given transformation
4248 <     * of all values
4249 <     */
4250 <    public <U> U reduceValuesInParallel
4251 <        (Function<? super V, ? extends U> transformer,
4252 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4253 <        return ForkJoinTasks.reduceValues
4254 <            (this, transformer, reducer).invoke();
4255 <    }
4256 <
4257 <    /**
4258 <     * Returns the result of accumulating the given transformation
4259 <     * of all values using the given reducer to combine values,
4260 <     * and the given basis as an identity value.
4261 <     *
4262 <     * @param transformer a function returning the transformation
4263 <     * for an element
4264 <     * @param basis the identity (initial default value) for the reduction
4265 <     * @param reducer a commutative associative combining function
4266 <     * @return the result of accumulating the given transformation
4267 <     * of all values
4268 <     */
4269 <    public double reduceValuesToDoubleInParallel
4270 <        (ToDoubleFunction<? super V> transformer,
4271 <         double basis,
4272 <         DoubleBinaryOperator reducer) {
4273 <        return ForkJoinTasks.reduceValuesToDouble
4274 <            (this, transformer, basis, reducer).invoke();
4275 <    }
4276 <
4277 <    /**
4278 <     * Returns the result of accumulating the given transformation
4279 <     * of all values using the given reducer to combine values,
4280 <     * and the given basis as an identity value.
4281 <     *
4282 <     * @param transformer a function returning the transformation
4283 <     * for an element
4284 <     * @param basis the identity (initial default value) for the reduction
4285 <     * @param reducer a commutative associative combining function
4286 <     * @return the result of accumulating the given transformation
4287 <     * of all values
4288 <     */
4289 <    public long reduceValuesToLongInParallel
4290 <        (ToLongFunction<? super V> transformer,
4291 <         long basis,
4292 <         LongBinaryOperator reducer) {
4293 <        return ForkJoinTasks.reduceValuesToLong
4294 <            (this, transformer, basis, reducer).invoke();
4295 <    }
4296 <
4297 <    /**
4298 <     * Returns the result of accumulating the given transformation
4299 <     * of all values using the given reducer to combine values,
4300 <     * and the given basis as an identity value.
4301 <     *
4302 <     * @param transformer a function returning the transformation
4303 <     * for an element
4304 <     * @param basis the identity (initial default value) for the reduction
4305 <     * @param reducer a commutative associative combining function
4306 <     * @return the result of accumulating the given transformation
4307 <     * of all values
4308 <     */
4309 <    public int reduceValuesToIntInParallel
4310 <        (ToIntFunction<? super V> transformer,
4311 <         int basis,
4312 <         IntBinaryOperator reducer) {
4313 <        return ForkJoinTasks.reduceValuesToInt
4314 <            (this, transformer, basis, reducer).invoke();
4315 <    }
4316 <
4317 <    /**
4318 <     * Performs the given action for each entry.
4319 <     *
4320 <     * @param action the action
4321 <     */
4322 <    public void forEachEntryInParallel(Consumer<? super Map.Entry<K,V>> action) {
4323 <        ForkJoinTasks.forEachEntry
4324 <            (this, action).invoke();
4325 <    }
4326 <
4327 <    /**
4328 <     * Performs the given action for each non-null transformation
4329 <     * of each entry.
4330 <     *
4331 <     * @param transformer a function returning the transformation
4332 <     * for an element, or null if there is no transformation (in
4333 <     * which case the action is not applied)
4334 <     * @param action the action
4335 <     */
4336 <    public <U> void forEachEntryInParallel
4337 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4338 <         Consumer<? super U> action) {
4339 <        ForkJoinTasks.forEachEntry
4340 <            (this, transformer, action).invoke();
4341 <    }
4342 <
4343 <    /**
4344 <     * Returns a non-null result from applying the given search
4345 <     * function on each entry, or null if none.  Upon success,
4346 <     * further element processing is suppressed and the results of
4347 <     * any other parallel invocations of the search function are
4348 <     * ignored.
4349 <     *
4350 <     * @param searchFunction a function returning a non-null
4351 <     * result on success, else null
4352 <     * @return a non-null result from applying the given search
4353 <     * function on each entry, or null if none
4354 <     */
4355 <    public <U> U searchEntriesInParallel
4356 <        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4357 <        return ForkJoinTasks.searchEntries
4358 <            (this, searchFunction).invoke();
4359 <    }
4360 <
4361 <    /**
4362 <     * Returns the result of accumulating all entries using the
4363 <     * given reducer to combine values, or null if none.
4364 <     *
4365 <     * @param reducer a commutative associative combining function
4366 <     * @return the result of accumulating all entries
4367 <     */
4368 <    public Map.Entry<K,V> reduceEntriesInParallel
4369 <        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4370 <        return ForkJoinTasks.reduceEntries
4371 <            (this, reducer).invoke();
4372 <    }
4373 <
4374 <    /**
4375 <     * Returns the result of accumulating the given transformation
4376 <     * of all entries using the given reducer to combine values,
4377 <     * or null if none.
4378 <     *
4379 <     * @param transformer a function returning the transformation
4380 <     * for an element, or null if there is no transformation (in
4381 <     * which case it is not combined)
4382 <     * @param reducer a commutative associative combining function
4383 <     * @return the result of accumulating the given transformation
4384 <     * of all entries
4385 <     */
4386 <    public <U> U reduceEntriesInParallel
4387 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4388 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4389 <        return ForkJoinTasks.reduceEntries
4390 <            (this, transformer, reducer).invoke();
4391 <    }
4392 <
4393 <    /**
4394 <     * Returns the result of accumulating the given transformation
4395 <     * of all entries using the given reducer to combine values,
4396 <     * and the given basis as an identity value.
4397 <     *
4398 <     * @param transformer a function returning the transformation
4399 <     * for an element
4400 <     * @param basis the identity (initial default value) for the reduction
4401 <     * @param reducer a commutative associative combining function
4402 <     * @return the result of accumulating the given transformation
4403 <     * of all entries
4404 <     */
4405 <    public double reduceEntriesToDoubleInParallel
4406 <        (ToDoubleFunction<Map.Entry<K,V>> transformer,
4407 <         double basis,
4408 <         DoubleBinaryOperator reducer) {
4409 <        return ForkJoinTasks.reduceEntriesToDouble
4410 <            (this, transformer, basis, reducer).invoke();
4411 <    }
4412 <
4413 <    /**
4414 <     * Returns the result of accumulating the given transformation
4415 <     * of all entries using the given reducer to combine values,
4416 <     * and the given basis as an identity value.
4417 <     *
4418 <     * @param transformer a function returning the transformation
4419 <     * for an element
4420 <     * @param basis the identity (initial default value) for the reduction
4421 <     * @param reducer a commutative associative combining function
4422 <     * @return the result of accumulating the given transformation
4423 <     * of all entries
4424 <     */
4425 <    public long reduceEntriesToLongInParallel
4426 <        (ToLongFunction<Map.Entry<K,V>> transformer,
4427 <         long basis,
4428 <         LongBinaryOperator reducer) {
4429 <        return ForkJoinTasks.reduceEntriesToLong
4430 <            (this, transformer, basis, reducer).invoke();
4431 <    }
4432 <
4433 <    /**
4434 <     * Returns the result of accumulating the given transformation
4435 <     * of all entries using the given reducer to combine values,
4436 <     * and the given basis as an identity value.
4437 <     *
4438 <     * @param transformer a function returning the transformation
4439 <     * for an element
4440 <     * @param basis the identity (initial default value) for the reduction
4441 <     * @param reducer a commutative associative combining function
4442 <     * @return the result of accumulating the given transformation
4443 <     * of all entries
4444 <     */
4445 <    public int reduceEntriesToIntInParallel
4446 <        (ToIntFunction<Map.Entry<K,V>> transformer,
4447 <         int basis,
4448 <         IntBinaryOperator reducer) {
4449 <        return ForkJoinTasks.reduceEntriesToInt
4450 <            (this, transformer, basis, reducer).invoke();
4335 >        return new MapReduceEntriesToIntTask<K,V>
4336 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4337 >             null, transformer, basis, reducer).invoke();
4338      }
4339  
4340  
# Line 4456 | Line 4343 | public class ConcurrentHashMap<K, V>
4343      /**
4344       * Base class for views.
4345       */
4346 <    abstract static class CHMView<K, V> implements java.io.Serializable {
4346 >    abstract static class CollectionView<K,V,E>
4347 >        implements Collection<E>, java.io.Serializable {
4348          private static final long serialVersionUID = 7249069246763182397L;
4349 <        final ConcurrentHashMap<K, V> map;
4350 <        CHMView(ConcurrentHashMap<K, V> map)  { this.map = map; }
4349 >        final ConcurrentHashMap<K,V> map;
4350 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4351  
4352          /**
4353           * Returns the map backing this view.
# Line 4468 | Line 4356 | public class ConcurrentHashMap<K, V>
4356           */
4357          public ConcurrentHashMap<K,V> getMap() { return map; }
4358  
4359 <        public final int size()                 { return map.size(); }
4360 <        public final boolean isEmpty()          { return map.isEmpty(); }
4361 <        public final void clear()               { map.clear(); }
4359 >        /**
4360 >         * Removes all of the elements from this view, by removing all
4361 >         * the mappings from the map backing this view.
4362 >         */
4363 >        public final void clear()      { map.clear(); }
4364 >        public final int size()        { return map.size(); }
4365 >        public final boolean isEmpty() { return map.isEmpty(); }
4366  
4367          // implementations below rely on concrete classes supplying these
4368 <        public abstract Iterator<?> iterator();
4368 >        // abstract methods
4369 >        /**
4370 >         * Returns an iterator over the elements in this collection.
4371 >         *
4372 >         * <p>The returned iterator is
4373 >         * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
4374 >         *
4375 >         * @return an iterator over the elements in this collection
4376 >         */
4377 >        public abstract Iterator<E> iterator();
4378          public abstract boolean contains(Object o);
4379          public abstract boolean remove(Object o);
4380  
# Line 4481 | Line 4382 | public class ConcurrentHashMap<K, V>
4382  
4383          public final Object[] toArray() {
4384              long sz = map.mappingCount();
4385 <            if (sz > (long)(MAX_ARRAY_SIZE))
4385 >            if (sz > MAX_ARRAY_SIZE)
4386                  throw new OutOfMemoryError(oomeMsg);
4387              int n = (int)sz;
4388              Object[] r = new Object[n];
4389              int i = 0;
4390 <            Iterator<?> it = iterator();
4490 <            while (it.hasNext()) {
4390 >            for (E e : this) {
4391                  if (i == n) {
4392                      if (n >= MAX_ARRAY_SIZE)
4393                          throw new OutOfMemoryError(oomeMsg);
# Line 4497 | Line 4397 | public class ConcurrentHashMap<K, V>
4397                          n += (n >>> 1) + 1;
4398                      r = Arrays.copyOf(r, n);
4399                  }
4400 <                r[i++] = it.next();
4400 >                r[i++] = e;
4401              }
4402              return (i == n) ? r : Arrays.copyOf(r, i);
4403          }
4404  
4405 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4405 >        @SuppressWarnings("unchecked")
4406 >        public final <T> T[] toArray(T[] a) {
4407              long sz = map.mappingCount();
4408 <            if (sz > (long)(MAX_ARRAY_SIZE))
4408 >            if (sz > MAX_ARRAY_SIZE)
4409                  throw new OutOfMemoryError(oomeMsg);
4410              int m = (int)sz;
4411              T[] r = (a.length >= m) ? a :
# Line 4512 | Line 4413 | public class ConcurrentHashMap<K, V>
4413                  .newInstance(a.getClass().getComponentType(), m);
4414              int n = r.length;
4415              int i = 0;
4416 <            Iterator<?> it = iterator();
4516 <            while (it.hasNext()) {
4416 >            for (E e : this) {
4417                  if (i == n) {
4418                      if (n >= MAX_ARRAY_SIZE)
4419                          throw new OutOfMemoryError(oomeMsg);
# Line 4523 | Line 4423 | public class ConcurrentHashMap<K, V>
4423                          n += (n >>> 1) + 1;
4424                      r = Arrays.copyOf(r, n);
4425                  }
4426 <                r[i++] = (T)it.next();
4426 >                r[i++] = (T)e;
4427              }
4428              if (a == r && i < n) {
4429                  r[i] = null; // null-terminate
# Line 4532 | Line 4432 | public class ConcurrentHashMap<K, V>
4432              return (i == n) ? r : Arrays.copyOf(r, i);
4433          }
4434  
4435 <        public final int hashCode() {
4436 <            int h = 0;
4437 <            for (Iterator<?> it = iterator(); it.hasNext();)
4438 <                h += it.next().hashCode();
4439 <            return h;
4440 <        }
4441 <
4435 >        /**
4436 >         * Returns a string representation of this collection.
4437 >         * The string representation consists of the string representations
4438 >         * of the collection's elements in the order they are returned by
4439 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4440 >         * Adjacent elements are separated by the characters {@code ", "}
4441 >         * (comma and space).  Elements are converted to strings as by
4442 >         * {@link String#valueOf(Object)}.
4443 >         *
4444 >         * @return a string representation of this collection
4445 >         */
4446          public final String toString() {
4447              StringBuilder sb = new StringBuilder();
4448              sb.append('[');
4449 <            Iterator<?> it = iterator();
4449 >            Iterator<E> it = iterator();
4450              if (it.hasNext()) {
4451                  for (;;) {
4452                      Object e = it.next();
# Line 4557 | Line 4461 | public class ConcurrentHashMap<K, V>
4461  
4462          public final boolean containsAll(Collection<?> c) {
4463              if (c != this) {
4464 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4561 <                    Object e = it.next();
4464 >                for (Object e : c) {
4465                      if (e == null || !contains(e))
4466                          return false;
4467                  }
# Line 4567 | Line 4470 | public class ConcurrentHashMap<K, V>
4470          }
4471  
4472          public final boolean removeAll(Collection<?> c) {
4473 +            if (c == null) throw new NullPointerException();
4474              boolean modified = false;
4475 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4475 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4476                  if (c.contains(it.next())) {
4477                      it.remove();
4478                      modified = true;
# Line 4578 | Line 4482 | public class ConcurrentHashMap<K, V>
4482          }
4483  
4484          public final boolean retainAll(Collection<?> c) {
4485 +            if (c == null) throw new NullPointerException();
4486              boolean modified = false;
4487 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4487 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4488                  if (!c.contains(it.next())) {
4489                      it.remove();
4490                      modified = true;
# Line 4593 | Line 4498 | public class ConcurrentHashMap<K, V>
4498      /**
4499       * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4500       * which additions may optionally be enabled by mapping to a
4501 <     * common value.  This class cannot be directly instantiated. See
4502 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4503 <     * {@link #newKeySet(int)}.
4501 >     * common value.  This class cannot be directly instantiated.
4502 >     * See {@link #keySet() keySet()},
4503 >     * {@link #keySet(Object) keySet(V)},
4504 >     * {@link #newKeySet() newKeySet()},
4505 >     * {@link #newKeySet(int) newKeySet(int)}.
4506 >     *
4507 >     * @since 1.8
4508       */
4509 <    public static class KeySetView<K,V> extends CHMView<K,V>
4509 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4510          implements Set<K>, java.io.Serializable {
4511          private static final long serialVersionUID = 7249069246763182397L;
4512          private final V value;
4513 <        KeySetView(ConcurrentHashMap<K, V> map, V value) {  // non-public
4513 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4514              super(map);
4515              this.value = value;
4516          }
# Line 4615 | Line 4524 | public class ConcurrentHashMap<K, V>
4524           */
4525          public V getMappedValue() { return value; }
4526  
4527 <        // implement Set API
4528 <
4527 >        /**
4528 >         * {@inheritDoc}
4529 >         * @throws NullPointerException if the specified key is null
4530 >         */
4531          public boolean contains(Object o) { return map.containsKey(o); }
4621        public boolean remove(Object o)   { return map.remove(o) != null; }
4532  
4533          /**
4534 <         * Returns a "weakly consistent" iterator that will never
4535 <         * throw {@link ConcurrentModificationException}, and
4536 <         * guarantees to traverse elements as they existed upon
4537 <         * construction of the iterator, and may (but is not
4538 <         * guaranteed to) reflect any modifications subsequent to
4539 <         * construction.
4534 >         * Removes the key from this map view, by removing the key (and its
4535 >         * corresponding value) from the backing map.  This method does
4536 >         * nothing if the key is not in the map.
4537 >         *
4538 >         * @param  o the key to be removed from the backing map
4539 >         * @return {@code true} if the backing map contained the specified key
4540 >         * @throws NullPointerException if the specified key is null
4541 >         */
4542 >        public boolean remove(Object o) { return map.remove(o) != null; }
4543 >
4544 >        /**
4545 >         * @return an iterator over the keys of the backing map
4546 >         */
4547 >        public Iterator<K> iterator() {
4548 >            Node<K,V>[] t;
4549 >            ConcurrentHashMap<K,V> m = map;
4550 >            int f = (t = m.table) == null ? 0 : t.length;
4551 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4552 >        }
4553 >
4554 >        /**
4555 >         * Adds the specified key to this set view by mapping the key to
4556 >         * the default mapped value in the backing map, if defined.
4557           *
4558 <         * @return an iterator over the keys of this map
4558 >         * @param e key to be added
4559 >         * @return {@code true} if this set changed as a result of the call
4560 >         * @throws NullPointerException if the specified key is null
4561 >         * @throws UnsupportedOperationException if no default mapped value
4562 >         * for additions was provided
4563           */
4633        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4564          public boolean add(K e) {
4565              V v;
4566              if ((v = value) == null)
4567                  throw new UnsupportedOperationException();
4568 <            if (e == null)
4639 <                throw new NullPointerException();
4640 <            return map.internalPut(e, v, true) == null;
4568 >            return map.putVal(e, v, true) == null;
4569          }
4570 +
4571 +        /**
4572 +         * Adds all of the elements in the specified collection to this set,
4573 +         * as if by calling {@link #add} on each one.
4574 +         *
4575 +         * @param c the elements to be inserted into this set
4576 +         * @return {@code true} if this set changed as a result of the call
4577 +         * @throws NullPointerException if the collection or any of its
4578 +         * elements are {@code null}
4579 +         * @throws UnsupportedOperationException if no default mapped value
4580 +         * for additions was provided
4581 +         */
4582          public boolean addAll(Collection<? extends K> c) {
4583              boolean added = false;
4584              V v;
4585              if ((v = value) == null)
4586                  throw new UnsupportedOperationException();
4587              for (K e : c) {
4588 <                if (e == null)
4649 <                    throw new NullPointerException();
4650 <                if (map.internalPut(e, v, true) == null)
4588 >                if (map.putVal(e, v, true) == null)
4589                      added = true;
4590              }
4591              return added;
4592          }
4593 +
4594 +        public int hashCode() {
4595 +            int h = 0;
4596 +            for (K e : this)
4597 +                h += e.hashCode();
4598 +            return h;
4599 +        }
4600 +
4601          public boolean equals(Object o) {
4602              Set<?> c;
4603              return ((o instanceof Set) &&
# Line 4659 | Line 4605 | public class ConcurrentHashMap<K, V>
4605                       (containsAll(c) && c.containsAll(this))));
4606          }
4607  
4608 <        public Stream<K> stream() {
4609 <            return Streams.stream(() -> new KeyIterator<K,V>(map), 0);
4608 >        public Spliterator<K> spliterator() {
4609 >            Node<K,V>[] t;
4610 >            ConcurrentHashMap<K,V> m = map;
4611 >            long n = m.sumCount();
4612 >            int f = (t = m.table) == null ? 0 : t.length;
4613 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4614          }
4615 <        public Stream<K> parallelStream() {
4616 <            return Streams.parallelStream(() -> new KeyIterator<K,V>(map, null),
4617 <                                          0);
4615 >
4616 >        public void forEach(Consumer<? super K> action) {
4617 >            if (action == null) throw new NullPointerException();
4618 >            Node<K,V>[] t;
4619 >            if ((t = map.table) != null) {
4620 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4621 >                for (Node<K,V> p; (p = it.advance()) != null; )
4622 >                    action.accept(p.key);
4623 >            }
4624          }
4625      }
4626  
4627      /**
4628       * A view of a ConcurrentHashMap as a {@link Collection} of
4629       * values, in which additions are disabled. This class cannot be
4630 <     * directly instantiated. See {@link #values},
4675 <     *
4676 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4677 <     * that will never throw {@link ConcurrentModificationException},
4678 <     * and guarantees to traverse elements as they existed upon
4679 <     * construction of the iterator, and may (but is not guaranteed to)
4680 <     * reflect any modifications subsequent to construction.
4630 >     * directly instantiated. See {@link #values()}.
4631       */
4632 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4633 <        implements Collection<V> {
4632 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4633 >        implements Collection<V>, java.io.Serializable {
4634          private static final long serialVersionUID = 2249069246763182397L;
4635 <        ValuesView(ConcurrentHashMap<K, V> map)   { super(map); }
4636 <        public final boolean contains(Object o) { return map.containsValue(o); }
4635 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4636 >        public final boolean contains(Object o) {
4637 >            return map.containsValue(o);
4638 >        }
4639 >
4640          public final boolean remove(Object o) {
4641              if (o != null) {
4642 <                Iterator<V> it = new ValueIterator<K,V>(map);
4690 <                while (it.hasNext()) {
4642 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4643                      if (o.equals(it.next())) {
4644                          it.remove();
4645                          return true;
# Line 4697 | Line 4649 | public class ConcurrentHashMap<K, V>
4649              return false;
4650          }
4651  
4700        /**
4701         * Returns a "weakly consistent" iterator that will never
4702         * throw {@link ConcurrentModificationException}, and
4703         * guarantees to traverse elements as they existed upon
4704         * construction of the iterator, and may (but is not
4705         * guaranteed to) reflect any modifications subsequent to
4706         * construction.
4707         *
4708         * @return an iterator over the values of this map
4709         */
4652          public final Iterator<V> iterator() {
4653 <            return new ValueIterator<K,V>(map);
4653 >            ConcurrentHashMap<K,V> m = map;
4654 >            Node<K,V>[] t;
4655 >            int f = (t = m.table) == null ? 0 : t.length;
4656 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4657          }
4658 +
4659          public final boolean add(V e) {
4660              throw new UnsupportedOperationException();
4661          }
# Line 4717 | Line 4663 | public class ConcurrentHashMap<K, V>
4663              throw new UnsupportedOperationException();
4664          }
4665  
4666 <        public Stream<V> stream() {
4667 <            return Streams.stream(() -> new ValueIterator<K,V>(map), 0);
4666 >        public Spliterator<V> spliterator() {
4667 >            Node<K,V>[] t;
4668 >            ConcurrentHashMap<K,V> m = map;
4669 >            long n = m.sumCount();
4670 >            int f = (t = m.table) == null ? 0 : t.length;
4671 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4672          }
4673  
4674 <        public Stream<V> parallelStream() {
4675 <            return Streams.parallelStream(() -> new ValueIterator<K,V>(map, null),
4676 <                                          0);
4674 >        public void forEach(Consumer<? super V> action) {
4675 >            if (action == null) throw new NullPointerException();
4676 >            Node<K,V>[] t;
4677 >            if ((t = map.table) != null) {
4678 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4679 >                for (Node<K,V> p; (p = it.advance()) != null; )
4680 >                    action.accept(p.val);
4681 >            }
4682          }
4728
4683      }
4684  
4685      /**
4686       * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4687       * entries.  This class cannot be directly instantiated. See
4688 <     * {@link #entrySet}.
4688 >     * {@link #entrySet()}.
4689       */
4690 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4691 <        implements Set<Map.Entry<K,V>> {
4690 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4691 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4692          private static final long serialVersionUID = 2249069246763182397L;
4693 <        EntrySetView(ConcurrentHashMap<K, V> map) { super(map); }
4694 <        public final boolean contains(Object o) {
4693 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4694 >
4695 >        public boolean contains(Object o) {
4696              Object k, v, r; Map.Entry<?,?> e;
4697              return ((o instanceof Map.Entry) &&
4698                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4745 | Line 4700 | public class ConcurrentHashMap<K, V>
4700                      (v = e.getValue()) != null &&
4701                      (v == r || v.equals(r)));
4702          }
4703 <        public final boolean remove(Object o) {
4703 >
4704 >        public boolean remove(Object o) {
4705              Object k, v; Map.Entry<?,?> e;
4706              return ((o instanceof Map.Entry) &&
4707                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4754 | Line 4710 | public class ConcurrentHashMap<K, V>
4710          }
4711  
4712          /**
4713 <         * Returns a "weakly consistent" iterator that will never
4758 <         * throw {@link ConcurrentModificationException}, and
4759 <         * guarantees to traverse elements as they existed upon
4760 <         * construction of the iterator, and may (but is not
4761 <         * guaranteed to) reflect any modifications subsequent to
4762 <         * construction.
4763 <         *
4764 <         * @return an iterator over the entries of this map
4713 >         * @return an iterator over the entries of the backing map
4714           */
4715 <        public final Iterator<Map.Entry<K,V>> iterator() {
4716 <            return new EntryIterator<K,V>(map);
4715 >        public Iterator<Map.Entry<K,V>> iterator() {
4716 >            ConcurrentHashMap<K,V> m = map;
4717 >            Node<K,V>[] t;
4718 >            int f = (t = m.table) == null ? 0 : t.length;
4719 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4720          }
4721  
4722 <        public final boolean add(Entry<K,V> e) {
4723 <            K key = e.getKey();
4772 <            V value = e.getValue();
4773 <            if (key == null || value == null)
4774 <                throw new NullPointerException();
4775 <            return map.internalPut(key, value, false) == null;
4722 >        public boolean add(Entry<K,V> e) {
4723 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4724          }
4725 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4725 >
4726 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4727              boolean added = false;
4728              for (Entry<K,V> e : c) {
4729                  if (add(e))
# Line 4782 | Line 4731 | public class ConcurrentHashMap<K, V>
4731              }
4732              return added;
4733          }
4734 <        public boolean equals(Object o) {
4734 >
4735 >        public final int hashCode() {
4736 >            int h = 0;
4737 >            Node<K,V>[] t;
4738 >            if ((t = map.table) != null) {
4739 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4740 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4741 >                    h += p.hashCode();
4742 >                }
4743 >            }
4744 >            return h;
4745 >        }
4746 >
4747 >        public final boolean equals(Object o) {
4748              Set<?> c;
4749              return ((o instanceof Set) &&
4750                      ((c = (Set<?>)o) == this ||
4751                       (containsAll(c) && c.containsAll(this))));
4752          }
4753  
4754 <        public Stream<Map.Entry<K,V>> stream() {
4755 <            return Streams.stream(() -> new EntryIterator<K,V>(map), 0);
4754 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4755 >            Node<K,V>[] t;
4756 >            ConcurrentHashMap<K,V> m = map;
4757 >            long n = m.sumCount();
4758 >            int f = (t = m.table) == null ? 0 : t.length;
4759 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4760          }
4761  
4762 <        public Stream<Map.Entry<K,V>> parallelStream() {
4763 <            return Streams.parallelStream(() -> new EntryIterator<K,V>(map, null),
4764 <                                          0);
4762 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4763 >            if (action == null) throw new NullPointerException();
4764 >            Node<K,V>[] t;
4765 >            if ((t = map.table) != null) {
4766 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4767 >                for (Node<K,V> p; (p = it.advance()) != null; )
4768 >                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
4769 >            }
4770          }
4771 +
4772      }
4773  
4774 <    // ---------------------------------------------------------------------
4774 >    // -------------------------------------------------------
4775  
4776      /**
4777 <     * Predefined tasks for performing bulk parallel operations on
4778 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
4807 <     * for bulk operations. Each method has the same name, but returns
4808 <     * a task rather than invoking it. These methods may be useful in
4809 <     * custom applications such as submitting a task without waiting
4810 <     * for completion, using a custom pool, or combining with other
4811 <     * tasks.
4777 >     * Base class for bulk tasks. Repeats some fields and code from
4778 >     * class Traverser, because we need to subclass CountedCompleter.
4779       */
4780 <    public static class ForkJoinTasks {
4781 <        private ForkJoinTasks() {}
4782 <
4783 <        /**
4784 <         * Returns a task that when invoked, performs the given
4785 <         * action for each (key, value)
4786 <         *
4787 <         * @param map the map
4788 <         * @param action the action
4789 <         * @return the task
4790 <         */
4791 <        public static <K,V> ForkJoinTask<Void> forEach
4792 <            (ConcurrentHashMap<K,V> map,
4793 <             BiConsumer<? super K, ? super V> action) {
4794 <            if (action == null) throw new NullPointerException();
4795 <            return new ForEachMappingTask<K,V>(map, null, -1, action);
4796 <        }
4797 <
4798 <        /**
4799 <         * Returns a task that when invoked, performs the given
4800 <         * action for each non-null transformation of each (key, value)
4801 <         *
4802 <         * @param map the map
4836 <         * @param transformer a function returning the transformation
4837 <         * for an element, or null if there is no transformation (in
4838 <         * which case the action is not applied)
4839 <         * @param action the action
4840 <         * @return the task
4841 <         */
4842 <        public static <K,V,U> ForkJoinTask<Void> forEach
4843 <            (ConcurrentHashMap<K,V> map,
4844 <             BiFunction<? super K, ? super V, ? extends U> transformer,
4845 <             Consumer<? super U> action) {
4846 <            if (transformer == null || action == null)
4847 <                throw new NullPointerException();
4848 <            return new ForEachTransformedMappingTask<K,V,U>
4849 <                (map, null, -1, transformer, action);
4850 <        }
4851 <
4852 <        /**
4853 <         * Returns a task that when invoked, returns a non-null result
4854 <         * from applying the given search function on each (key,
4855 <         * value), or null if none. Upon success, further element
4856 <         * processing is suppressed and the results of any other
4857 <         * parallel invocations of the search function are ignored.
4858 <         *
4859 <         * @param map the map
4860 <         * @param searchFunction a function returning a non-null
4861 <         * result on success, else null
4862 <         * @return the task
4863 <         */
4864 <        public static <K,V,U> ForkJoinTask<U> search
4865 <            (ConcurrentHashMap<K,V> map,
4866 <             BiFunction<? super K, ? super V, ? extends U> searchFunction) {
4867 <            if (searchFunction == null) throw new NullPointerException();
4868 <            return new SearchMappingsTask<K,V,U>
4869 <                (map, null, -1, searchFunction,
4870 <                 new AtomicReference<U>());
4871 <        }
4872 <
4873 <        /**
4874 <         * Returns a task that when invoked, returns the result of
4875 <         * accumulating the given transformation of all (key, value) pairs
4876 <         * using the given reducer to combine values, or null if none.
4877 <         *
4878 <         * @param map the map
4879 <         * @param transformer a function returning the transformation
4880 <         * for an element, or null if there is no transformation (in
4881 <         * which case it is not combined)
4882 <         * @param reducer a commutative associative combining function
4883 <         * @return the task
4884 <         */
4885 <        public static <K,V,U> ForkJoinTask<U> reduce
4886 <            (ConcurrentHashMap<K,V> map,
4887 <             BiFunction<? super K, ? super V, ? extends U> transformer,
4888 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
4889 <            if (transformer == null || reducer == null)
4890 <                throw new NullPointerException();
4891 <            return new MapReduceMappingsTask<K,V,U>
4892 <                (map, null, -1, null, transformer, reducer);
4893 <        }
4894 <
4895 <        /**
4896 <         * Returns a task that when invoked, returns the result of
4897 <         * accumulating the given transformation of all (key, value) pairs
4898 <         * using the given reducer to combine values, and the given
4899 <         * basis as an identity value.
4900 <         *
4901 <         * @param map the map
4902 <         * @param transformer a function returning the transformation
4903 <         * for an element
4904 <         * @param basis the identity (initial default value) for the reduction
4905 <         * @param reducer a commutative associative combining function
4906 <         * @return the task
4907 <         */
4908 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4909 <            (ConcurrentHashMap<K,V> map,
4910 <             ToDoubleBiFunction<? super K, ? super V> transformer,
4911 <             double basis,
4912 <             DoubleBinaryOperator reducer) {
4913 <            if (transformer == null || reducer == null)
4914 <                throw new NullPointerException();
4915 <            return new MapReduceMappingsToDoubleTask<K,V>
4916 <                (map, null, -1, null, transformer, basis, reducer);
4917 <        }
4918 <
4919 <        /**
4920 <         * Returns a task that when invoked, returns the result of
4921 <         * accumulating the given transformation of all (key, value) pairs
4922 <         * using the given reducer to combine values, and the given
4923 <         * basis as an identity value.
4924 <         *
4925 <         * @param map the map
4926 <         * @param transformer a function returning the transformation
4927 <         * for an element
4928 <         * @param basis the identity (initial default value) for the reduction
4929 <         * @param reducer a commutative associative combining function
4930 <         * @return the task
4931 <         */
4932 <        public static <K,V> ForkJoinTask<Long> reduceToLong
4933 <            (ConcurrentHashMap<K,V> map,
4934 <             ToLongBiFunction<? super K, ? super V> transformer,
4935 <             long basis,
4936 <             LongBinaryOperator reducer) {
4937 <            if (transformer == null || reducer == null)
4938 <                throw new NullPointerException();
4939 <            return new MapReduceMappingsToLongTask<K,V>
4940 <                (map, null, -1, null, transformer, basis, reducer);
4941 <        }
4942 <
4943 <        /**
4944 <         * Returns a task that when invoked, returns the result of
4945 <         * accumulating the given transformation of all (key, value) pairs
4946 <         * using the given reducer to combine values, and the given
4947 <         * basis as an identity value.
4948 <         *
4949 <         * @param transformer a function returning the transformation
4950 <         * for an element
4951 <         * @param basis the identity (initial default value) for the reduction
4952 <         * @param reducer a commutative associative combining function
4953 <         * @return the task
4954 <         */
4955 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
4956 <            (ConcurrentHashMap<K,V> map,
4957 <             ToIntBiFunction<? super K, ? super V> transformer,
4958 <             int basis,
4959 <             IntBinaryOperator reducer) {
4960 <            if (transformer == null || reducer == null)
4961 <                throw new NullPointerException();
4962 <            return new MapReduceMappingsToIntTask<K,V>
4963 <                (map, null, -1, null, transformer, basis, reducer);
4964 <        }
4965 <
4966 <        /**
4967 <         * Returns a task that when invoked, performs the given action
4968 <         * for each key.
4969 <         *
4970 <         * @param map the map
4971 <         * @param action the action
4972 <         * @return the task
4973 <         */
4974 <        public static <K,V> ForkJoinTask<Void> forEachKey
4975 <            (ConcurrentHashMap<K,V> map,
4976 <             Consumer<? super K> action) {
4977 <            if (action == null) throw new NullPointerException();
4978 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
4979 <        }
4980 <
4981 <        /**
4982 <         * Returns a task that when invoked, performs the given action
4983 <         * for each non-null transformation of each key.
4984 <         *
4985 <         * @param map the map
4986 <         * @param transformer a function returning the transformation
4987 <         * for an element, or null if there is no transformation (in
4988 <         * which case the action is not applied)
4989 <         * @param action the action
4990 <         * @return the task
4991 <         */
4992 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
4993 <            (ConcurrentHashMap<K,V> map,
4994 <             Function<? super K, ? extends U> transformer,
4995 <             Consumer<? super U> action) {
4996 <            if (transformer == null || action == null)
4997 <                throw new NullPointerException();
4998 <            return new ForEachTransformedKeyTask<K,V,U>
4999 <                (map, null, -1, transformer, action);
5000 <        }
5001 <
5002 <        /**
5003 <         * Returns a task that when invoked, returns a non-null result
5004 <         * from applying the given search function on each key, or
5005 <         * null if none.  Upon success, further element processing is
5006 <         * suppressed and the results of any other parallel
5007 <         * invocations of the search function are ignored.
5008 <         *
5009 <         * @param map the map
5010 <         * @param searchFunction a function returning a non-null
5011 <         * result on success, else null
5012 <         * @return the task
5013 <         */
5014 <        public static <K,V,U> ForkJoinTask<U> searchKeys
5015 <            (ConcurrentHashMap<K,V> map,
5016 <             Function<? super K, ? extends U> searchFunction) {
5017 <            if (searchFunction == null) throw new NullPointerException();
5018 <            return new SearchKeysTask<K,V,U>
5019 <                (map, null, -1, searchFunction,
5020 <                 new AtomicReference<U>());
5021 <        }
5022 <
5023 <        /**
5024 <         * Returns a task that when invoked, returns the result of
5025 <         * accumulating all keys using the given reducer to combine
5026 <         * values, or null if none.
5027 <         *
5028 <         * @param map the map
5029 <         * @param reducer a commutative associative combining function
5030 <         * @return the task
5031 <         */
5032 <        public static <K,V> ForkJoinTask<K> reduceKeys
5033 <            (ConcurrentHashMap<K,V> map,
5034 <             BiFunction<? super K, ? super K, ? extends K> reducer) {
5035 <            if (reducer == null) throw new NullPointerException();
5036 <            return new ReduceKeysTask<K,V>
5037 <                (map, null, -1, null, reducer);
5038 <        }
5039 <
5040 <        /**
5041 <         * Returns a task that when invoked, returns the result of
5042 <         * accumulating the given transformation of all keys using the given
5043 <         * reducer to combine values, or null if none.
5044 <         *
5045 <         * @param map the map
5046 <         * @param transformer a function returning the transformation
5047 <         * for an element, or null if there is no transformation (in
5048 <         * which case it is not combined)
5049 <         * @param reducer a commutative associative combining function
5050 <         * @return the task
5051 <         */
5052 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
5053 <            (ConcurrentHashMap<K,V> map,
5054 <             Function<? super K, ? extends U> transformer,
5055 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5056 <            if (transformer == null || reducer == null)
5057 <                throw new NullPointerException();
5058 <            return new MapReduceKeysTask<K,V,U>
5059 <                (map, null, -1, null, transformer, reducer);
5060 <        }
5061 <
5062 <        /**
5063 <         * Returns a task that when invoked, returns the result of
5064 <         * accumulating the given transformation of all keys using the given
5065 <         * reducer to combine values, and the given basis as an
5066 <         * identity value.
5067 <         *
5068 <         * @param map the map
5069 <         * @param transformer a function returning the transformation
5070 <         * for an element
5071 <         * @param basis the identity (initial default value) for the reduction
5072 <         * @param reducer a commutative associative combining function
5073 <         * @return the task
5074 <         */
5075 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5076 <            (ConcurrentHashMap<K,V> map,
5077 <             ToDoubleFunction<? super K> transformer,
5078 <             double basis,
5079 <             DoubleBinaryOperator reducer) {
5080 <            if (transformer == null || reducer == null)
5081 <                throw new NullPointerException();
5082 <            return new MapReduceKeysToDoubleTask<K,V>
5083 <                (map, null, -1, null, transformer, basis, reducer);
5084 <        }
5085 <
5086 <        /**
5087 <         * Returns a task that when invoked, returns the result of
5088 <         * accumulating the given transformation of all keys using the given
5089 <         * reducer to combine values, and the given basis as an
5090 <         * identity value.
5091 <         *
5092 <         * @param map the map
5093 <         * @param transformer a function returning the transformation
5094 <         * for an element
5095 <         * @param basis the identity (initial default value) for the reduction
5096 <         * @param reducer a commutative associative combining function
5097 <         * @return the task
5098 <         */
5099 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5100 <            (ConcurrentHashMap<K,V> map,
5101 <             ToLongFunction<? super K> transformer,
5102 <             long basis,
5103 <             LongBinaryOperator reducer) {
5104 <            if (transformer == null || reducer == null)
5105 <                throw new NullPointerException();
5106 <            return new MapReduceKeysToLongTask<K,V>
5107 <                (map, null, -1, null, transformer, basis, reducer);
5108 <        }
5109 <
5110 <        /**
5111 <         * Returns a task that when invoked, returns the result of
5112 <         * accumulating the given transformation of all keys using the given
5113 <         * reducer to combine values, and the given basis as an
5114 <         * identity value.
5115 <         *
5116 <         * @param map the map
5117 <         * @param transformer a function returning the transformation
5118 <         * for an element
5119 <         * @param basis the identity (initial default value) for the reduction
5120 <         * @param reducer a commutative associative combining function
5121 <         * @return the task
5122 <         */
5123 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5124 <            (ConcurrentHashMap<K,V> map,
5125 <             ToIntFunction<? super K> transformer,
5126 <             int basis,
5127 <             IntBinaryOperator reducer) {
5128 <            if (transformer == null || reducer == null)
5129 <                throw new NullPointerException();
5130 <            return new MapReduceKeysToIntTask<K,V>
5131 <                (map, null, -1, null, transformer, basis, reducer);
5132 <        }
5133 <
5134 <        /**
5135 <         * Returns a task that when invoked, performs the given action
5136 <         * for each value.
5137 <         *
5138 <         * @param map the map
5139 <         * @param action the action
5140 <         * @return the task
5141 <         */
5142 <        public static <K,V> ForkJoinTask<Void> forEachValue
5143 <            (ConcurrentHashMap<K,V> map,
5144 <             Consumer<? super V> action) {
5145 <            if (action == null) throw new NullPointerException();
5146 <            return new ForEachValueTask<K,V>(map, null, -1, action);
5147 <        }
5148 <
5149 <        /**
5150 <         * Returns a task that when invoked, performs the given action
5151 <         * for each non-null transformation of each value.
5152 <         *
5153 <         * @param map the map
5154 <         * @param transformer a function returning the transformation
5155 <         * for an element, or null if there is no transformation (in
5156 <         * which case the action is not applied)
5157 <         * @param action the action
5158 <         * @return the task
5159 <         */
5160 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
5161 <            (ConcurrentHashMap<K,V> map,
5162 <             Function<? super V, ? extends U> transformer,
5163 <             Consumer<? super U> action) {
5164 <            if (transformer == null || action == null)
5165 <                throw new NullPointerException();
5166 <            return new ForEachTransformedValueTask<K,V,U>
5167 <                (map, null, -1, transformer, action);
5168 <        }
5169 <
5170 <        /**
5171 <         * Returns a task that when invoked, returns a non-null result
5172 <         * from applying the given search function on each value, or
5173 <         * null if none.  Upon success, further element processing is
5174 <         * suppressed and the results of any other parallel
5175 <         * invocations of the search function are ignored.
5176 <         *
5177 <         * @param map the map
5178 <         * @param searchFunction a function returning a non-null
5179 <         * result on success, else null
5180 <         * @return the task
5181 <         */
5182 <        public static <K,V,U> ForkJoinTask<U> searchValues
5183 <            (ConcurrentHashMap<K,V> map,
5184 <             Function<? super V, ? extends U> searchFunction) {
5185 <            if (searchFunction == null) throw new NullPointerException();
5186 <            return new SearchValuesTask<K,V,U>
5187 <                (map, null, -1, searchFunction,
5188 <                 new AtomicReference<U>());
5189 <        }
5190 <
5191 <        /**
5192 <         * Returns a task that when invoked, returns the result of
5193 <         * accumulating all values using the given reducer to combine
5194 <         * values, or null if none.
5195 <         *
5196 <         * @param map the map
5197 <         * @param reducer a commutative associative combining function
5198 <         * @return the task
5199 <         */
5200 <        public static <K,V> ForkJoinTask<V> reduceValues
5201 <            (ConcurrentHashMap<K,V> map,
5202 <             BiFunction<? super V, ? super V, ? extends V> reducer) {
5203 <            if (reducer == null) throw new NullPointerException();
5204 <            return new ReduceValuesTask<K,V>
5205 <                (map, null, -1, null, reducer);
5206 <        }
5207 <
5208 <        /**
5209 <         * Returns a task that when invoked, returns the result of
5210 <         * accumulating the given transformation of all values using the
5211 <         * given reducer to combine values, or null if none.
5212 <         *
5213 <         * @param map the map
5214 <         * @param transformer a function returning the transformation
5215 <         * for an element, or null if there is no transformation (in
5216 <         * which case it is not combined)
5217 <         * @param reducer a commutative associative combining function
5218 <         * @return the task
5219 <         */
5220 <        public static <K,V,U> ForkJoinTask<U> reduceValues
5221 <            (ConcurrentHashMap<K,V> map,
5222 <             Function<? super V, ? extends U> transformer,
5223 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5224 <            if (transformer == null || reducer == null)
5225 <                throw new NullPointerException();
5226 <            return new MapReduceValuesTask<K,V,U>
5227 <                (map, null, -1, null, transformer, reducer);
5228 <        }
5229 <
5230 <        /**
5231 <         * Returns a task that when invoked, returns the result of
5232 <         * accumulating the given transformation of all values using the
5233 <         * given reducer to combine values, and the given basis as an
5234 <         * identity value.
5235 <         *
5236 <         * @param map the map
5237 <         * @param transformer a function returning the transformation
5238 <         * for an element
5239 <         * @param basis the identity (initial default value) for the reduction
5240 <         * @param reducer a commutative associative combining function
5241 <         * @return the task
5242 <         */
5243 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5244 <            (ConcurrentHashMap<K,V> map,
5245 <             ToDoubleFunction<? super V> transformer,
5246 <             double basis,
5247 <             DoubleBinaryOperator reducer) {
5248 <            if (transformer == null || reducer == null)
5249 <                throw new NullPointerException();
5250 <            return new MapReduceValuesToDoubleTask<K,V>
5251 <                (map, null, -1, null, transformer, basis, reducer);
5252 <        }
5253 <
5254 <        /**
5255 <         * Returns a task that when invoked, returns the result of
5256 <         * accumulating the given transformation of all values using the
5257 <         * given reducer to combine values, and the given basis as an
5258 <         * identity value.
5259 <         *
5260 <         * @param map the map
5261 <         * @param transformer a function returning the transformation
5262 <         * for an element
5263 <         * @param basis the identity (initial default value) for the reduction
5264 <         * @param reducer a commutative associative combining function
5265 <         * @return the task
5266 <         */
5267 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5268 <            (ConcurrentHashMap<K,V> map,
5269 <             ToLongFunction<? super V> transformer,
5270 <             long basis,
5271 <             LongBinaryOperator reducer) {
5272 <            if (transformer == null || reducer == null)
5273 <                throw new NullPointerException();
5274 <            return new MapReduceValuesToLongTask<K,V>
5275 <                (map, null, -1, null, transformer, basis, reducer);
5276 <        }
5277 <
5278 <        /**
5279 <         * Returns a task that when invoked, returns the result of
5280 <         * accumulating the given transformation of all values using the
5281 <         * given reducer to combine values, and the given basis as an
5282 <         * identity value.
5283 <         *
5284 <         * @param map the map
5285 <         * @param transformer a function returning the transformation
5286 <         * for an element
5287 <         * @param basis the identity (initial default value) for the reduction
5288 <         * @param reducer a commutative associative combining function
5289 <         * @return the task
5290 <         */
5291 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5292 <            (ConcurrentHashMap<K,V> map,
5293 <             ToIntFunction<? super V> transformer,
5294 <             int basis,
5295 <             IntBinaryOperator reducer) {
5296 <            if (transformer == null || reducer == null)
5297 <                throw new NullPointerException();
5298 <            return new MapReduceValuesToIntTask<K,V>
5299 <                (map, null, -1, null, transformer, basis, reducer);
5300 <        }
5301 <
5302 <        /**
5303 <         * Returns a task that when invoked, perform the given action
5304 <         * for each entry.
5305 <         *
5306 <         * @param map the map
5307 <         * @param action the action
5308 <         * @return the task
5309 <         */
5310 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5311 <            (ConcurrentHashMap<K,V> map,
5312 <             Consumer<? super Map.Entry<K,V>> action) {
5313 <            if (action == null) throw new NullPointerException();
5314 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
5315 <        }
5316 <
5317 <        /**
5318 <         * Returns a task that when invoked, perform the given action
5319 <         * for each non-null transformation of each entry.
5320 <         *
5321 <         * @param map the map
5322 <         * @param transformer a function returning the transformation
5323 <         * for an element, or null if there is no transformation (in
5324 <         * which case the action is not applied)
5325 <         * @param action the action
5326 <         * @return the task
5327 <         */
5328 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5329 <            (ConcurrentHashMap<K,V> map,
5330 <             Function<Map.Entry<K,V>, ? extends U> transformer,
5331 <             Consumer<? super U> action) {
5332 <            if (transformer == null || action == null)
5333 <                throw new NullPointerException();
5334 <            return new ForEachTransformedEntryTask<K,V,U>
5335 <                (map, null, -1, transformer, action);
5336 <        }
5337 <
5338 <        /**
5339 <         * Returns a task that when invoked, returns a non-null result
5340 <         * from applying the given search function on each entry, or
5341 <         * null if none.  Upon success, further element processing is
5342 <         * suppressed and the results of any other parallel
5343 <         * invocations of the search function are ignored.
5344 <         *
5345 <         * @param map the map
5346 <         * @param searchFunction a function returning a non-null
5347 <         * result on success, else null
5348 <         * @return the task
5349 <         */
5350 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5351 <            (ConcurrentHashMap<K,V> map,
5352 <             Function<Map.Entry<K,V>, ? extends U> searchFunction) {
5353 <            if (searchFunction == null) throw new NullPointerException();
5354 <            return new SearchEntriesTask<K,V,U>
5355 <                (map, null, -1, searchFunction,
5356 <                 new AtomicReference<U>());
5357 <        }
5358 <
5359 <        /**
5360 <         * Returns a task that when invoked, returns the result of
5361 <         * accumulating all entries using the given reducer to combine
5362 <         * values, or null if none.
5363 <         *
5364 <         * @param map the map
5365 <         * @param reducer a commutative associative combining function
5366 <         * @return the task
5367 <         */
5368 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5369 <            (ConcurrentHashMap<K,V> map,
5370 <             BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5371 <            if (reducer == null) throw new NullPointerException();
5372 <            return new ReduceEntriesTask<K,V>
5373 <                (map, null, -1, null, reducer);
5374 <        }
5375 <
5376 <        /**
5377 <         * Returns a task that when invoked, returns the result of
5378 <         * accumulating the given transformation of all entries using the
5379 <         * given reducer to combine values, or null if none.
5380 <         *
5381 <         * @param map the map
5382 <         * @param transformer a function returning the transformation
5383 <         * for an element, or null if there is no transformation (in
5384 <         * which case it is not combined)
5385 <         * @param reducer a commutative associative combining function
5386 <         * @return the task
5387 <         */
5388 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5389 <            (ConcurrentHashMap<K,V> map,
5390 <             Function<Map.Entry<K,V>, ? extends U> transformer,
5391 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5392 <            if (transformer == null || reducer == null)
5393 <                throw new NullPointerException();
5394 <            return new MapReduceEntriesTask<K,V,U>
5395 <                (map, null, -1, null, transformer, reducer);
5396 <        }
5397 <
5398 <        /**
5399 <         * Returns a task that when invoked, returns the result of
5400 <         * accumulating the given transformation of all entries using the
5401 <         * given reducer to combine values, and the given basis as an
5402 <         * identity value.
5403 <         *
5404 <         * @param map the map
5405 <         * @param transformer a function returning the transformation
5406 <         * for an element
5407 <         * @param basis the identity (initial default value) for the reduction
5408 <         * @param reducer a commutative associative combining function
5409 <         * @return the task
5410 <         */
5411 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5412 <            (ConcurrentHashMap<K,V> map,
5413 <             ToDoubleFunction<Map.Entry<K,V>> transformer,
5414 <             double basis,
5415 <             DoubleBinaryOperator reducer) {
5416 <            if (transformer == null || reducer == null)
5417 <                throw new NullPointerException();
5418 <            return new MapReduceEntriesToDoubleTask<K,V>
5419 <                (map, null, -1, null, transformer, basis, reducer);
4780 >    @SuppressWarnings("serial")
4781 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4782 >        Node<K,V>[] tab;        // same as Traverser
4783 >        Node<K,V> next;
4784 >        TableStack<K,V> stack, spare;
4785 >        int index;
4786 >        int baseIndex;
4787 >        int baseLimit;
4788 >        final int baseSize;
4789 >        int batch;              // split control
4790 >
4791 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4792 >            super(par);
4793 >            this.batch = b;
4794 >            this.index = this.baseIndex = i;
4795 >            if ((this.tab = t) == null)
4796 >                this.baseSize = this.baseLimit = 0;
4797 >            else if (par == null)
4798 >                this.baseSize = this.baseLimit = t.length;
4799 >            else {
4800 >                this.baseLimit = f;
4801 >                this.baseSize = par.baseSize;
4802 >            }
4803          }
4804  
4805          /**
4806 <         * Returns a task that when invoked, returns the result of
5424 <         * accumulating the given transformation of all entries using the
5425 <         * given reducer to combine values, and the given basis as an
5426 <         * identity value.
5427 <         *
5428 <         * @param map the map
5429 <         * @param transformer a function returning the transformation
5430 <         * for an element
5431 <         * @param basis the identity (initial default value) for the reduction
5432 <         * @param reducer a commutative associative combining function
5433 <         * @return the task
4806 >         * Same as Traverser version
4807           */
4808 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4809 <            (ConcurrentHashMap<K,V> map,
4810 <             ToLongFunction<Map.Entry<K,V>> transformer,
4811 <             long basis,
4812 <             LongBinaryOperator reducer) {
4813 <            if (transformer == null || reducer == null)
4814 <                throw new NullPointerException();
4815 <            return new MapReduceEntriesToLongTask<K,V>
4816 <                (map, null, -1, null, transformer, basis, reducer);
4808 >        final Node<K,V> advance() {
4809 >            Node<K,V> e;
4810 >            if ((e = next) != null)
4811 >                e = e.next;
4812 >            for (;;) {
4813 >                Node<K,V>[] t; int i, n;
4814 >                if (e != null)
4815 >                    return next = e;
4816 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4817 >                    (n = t.length) <= (i = index) || i < 0)
4818 >                    return next = null;
4819 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
4820 >                    if (e instanceof ForwardingNode) {
4821 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4822 >                        e = null;
4823 >                        pushState(t, i, n);
4824 >                        continue;
4825 >                    }
4826 >                    else if (e instanceof TreeBin)
4827 >                        e = ((TreeBin<K,V>)e).first;
4828 >                    else
4829 >                        e = null;
4830 >                }
4831 >                if (stack != null)
4832 >                    recoverState(n);
4833 >                else if ((index = i + baseSize) >= n)
4834 >                    index = ++baseIndex;
4835 >            }
4836          }
4837  
4838 <        /**
4839 <         * Returns a task that when invoked, returns the result of
4840 <         * accumulating the given transformation of all entries using the
4841 <         * given reducer to combine values, and the given basis as an
4842 <         * identity value.
4843 <         *
4844 <         * @param map the map
4845 <         * @param transformer a function returning the transformation
4846 <         * for an element
4847 <         * @param basis the identity (initial default value) for the reduction
4848 <         * @param reducer a commutative associative combining function
4849 <         * @return the task
4850 <         */
4851 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4852 <            (ConcurrentHashMap<K,V> map,
4853 <             ToIntFunction<Map.Entry<K,V>> transformer,
4854 <             int basis,
4855 <             IntBinaryOperator reducer) {
4856 <            if (transformer == null || reducer == null)
4857 <                throw new NullPointerException();
4858 <            return new MapReduceEntriesToIntTask<K,V>
4859 <                (map, null, -1, null, transformer, basis, reducer);
4838 >        private void pushState(Node<K,V>[] t, int i, int n) {
4839 >            TableStack<K,V> s = spare;
4840 >            if (s != null)
4841 >                spare = s.next;
4842 >            else
4843 >                s = new TableStack<K,V>();
4844 >            s.tab = t;
4845 >            s.length = n;
4846 >            s.index = i;
4847 >            s.next = stack;
4848 >            stack = s;
4849 >        }
4850 >
4851 >        private void recoverState(int n) {
4852 >            TableStack<K,V> s; int len;
4853 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
4854 >                n = len;
4855 >                index = s.index;
4856 >                tab = s.tab;
4857 >                s.tab = null;
4858 >                TableStack<K,V> next = s.next;
4859 >                s.next = spare; // save for reuse
4860 >                stack = next;
4861 >                spare = s;
4862 >            }
4863 >            if (s == null && (index += baseSize) >= n)
4864 >                index = ++baseIndex;
4865          }
4866      }
4867  
5471    // -------------------------------------------------------
5472
4868      /*
4869       * Task classes. Coded in a regular but ugly format/style to
4870       * simplify checks that each variant differs in the right way from
# Line 5477 | Line 4872 | public class ConcurrentHashMap<K, V>
4872       * that we've already null-checked task arguments, so we force
4873       * simplest hoisted bypass to help avoid convoluted traps.
4874       */
4875 <
4876 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4877 <        extends Traverser<K,V,Void> {
4875 >    @SuppressWarnings("serial")
4876 >    static final class ForEachKeyTask<K,V>
4877 >        extends BulkTask<K,V,Void> {
4878          final Consumer<? super K> action;
4879          ForEachKeyTask
4880 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4880 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4881               Consumer<? super K> action) {
4882 <            super(m, p, b);
4882 >            super(p, b, i, f, t);
4883              this.action = action;
4884          }
4885          public final void compute() {
4886              final Consumer<? super K> action;
4887              if ((action = this.action) != null) {
4888 <                for (int b; (b = preSplit()) > 0;)
4889 <                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
4890 <                while (advance() != null)
4891 <                    action.accept(nextKey);
4888 >                for (int i = baseIndex, f, h; batch > 0 &&
4889 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4890 >                    addToPendingCount(1);
4891 >                    new ForEachKeyTask<K,V>
4892 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4893 >                         action).fork();
4894 >                }
4895 >                for (Node<K,V> p; (p = advance()) != null;)
4896 >                    action.accept(p.key);
4897                  propagateCompletion();
4898              }
4899          }
4900      }
4901  
4902 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4903 <        extends Traverser<K,V,Void> {
4902 >    @SuppressWarnings("serial")
4903 >    static final class ForEachValueTask<K,V>
4904 >        extends BulkTask<K,V,Void> {
4905          final Consumer<? super V> action;
4906          ForEachValueTask
4907 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4907 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4908               Consumer<? super V> action) {
4909 <            super(m, p, b);
4909 >            super(p, b, i, f, t);
4910              this.action = action;
4911          }
4912          public final void compute() {
4913              final Consumer<? super V> action;
4914              if ((action = this.action) != null) {
4915 <                for (int b; (b = preSplit()) > 0;)
4916 <                    new ForEachValueTask<K,V>(map, this, b, action).fork();
4917 <                V v;
4918 <                while ((v = advance()) != null)
4919 <                    action.accept(v);
4915 >                for (int i = baseIndex, f, h; batch > 0 &&
4916 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4917 >                    addToPendingCount(1);
4918 >                    new ForEachValueTask<K,V>
4919 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4920 >                         action).fork();
4921 >                }
4922 >                for (Node<K,V> p; (p = advance()) != null;)
4923 >                    action.accept(p.val);
4924                  propagateCompletion();
4925              }
4926          }
4927      }
4928  
4929 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4930 <        extends Traverser<K,V,Void> {
4929 >    @SuppressWarnings("serial")
4930 >    static final class ForEachEntryTask<K,V>
4931 >        extends BulkTask<K,V,Void> {
4932          final Consumer<? super Entry<K,V>> action;
4933          ForEachEntryTask
4934 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4934 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4935               Consumer<? super Entry<K,V>> action) {
4936 <            super(m, p, b);
4936 >            super(p, b, i, f, t);
4937              this.action = action;
4938          }
4939          public final void compute() {
4940              final Consumer<? super Entry<K,V>> action;
4941              if ((action = this.action) != null) {
4942 <                for (int b; (b = preSplit()) > 0;)
4943 <                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
4944 <                V v;
4945 <                while ((v = advance()) != null)
4946 <                    action.accept(entryFor(nextKey, v));
4942 >                for (int i = baseIndex, f, h; batch > 0 &&
4943 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4944 >                    addToPendingCount(1);
4945 >                    new ForEachEntryTask<K,V>
4946 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4947 >                         action).fork();
4948 >                }
4949 >                for (Node<K,V> p; (p = advance()) != null; )
4950 >                    action.accept(p);
4951                  propagateCompletion();
4952              }
4953          }
4954      }
4955  
4956 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4957 <        extends Traverser<K,V,Void> {
4956 >    @SuppressWarnings("serial")
4957 >    static final class ForEachMappingTask<K,V>
4958 >        extends BulkTask<K,V,Void> {
4959          final BiConsumer<? super K, ? super V> action;
4960          ForEachMappingTask
4961 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4961 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4962               BiConsumer<? super K,? super V> action) {
4963 <            super(m, p, b);
4963 >            super(p, b, i, f, t);
4964              this.action = action;
4965          }
4966          public final void compute() {
4967              final BiConsumer<? super K, ? super V> action;
4968              if ((action = this.action) != null) {
4969 <                for (int b; (b = preSplit()) > 0;)
4970 <                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
4971 <                V v;
4972 <                while ((v = advance()) != null)
4973 <                    action.accept(nextKey, v);
4969 >                for (int i = baseIndex, f, h; batch > 0 &&
4970 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4971 >                    addToPendingCount(1);
4972 >                    new ForEachMappingTask<K,V>
4973 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4974 >                         action).fork();
4975 >                }
4976 >                for (Node<K,V> p; (p = advance()) != null; )
4977 >                    action.accept(p.key, p.val);
4978                  propagateCompletion();
4979              }
4980          }
4981      }
4982  
4983 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4984 <        extends Traverser<K,V,Void> {
4983 >    @SuppressWarnings("serial")
4984 >    static final class ForEachTransformedKeyTask<K,V,U>
4985 >        extends BulkTask<K,V,Void> {
4986          final Function<? super K, ? extends U> transformer;
4987          final Consumer<? super U> action;
4988          ForEachTransformedKeyTask
4989 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4989 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4990               Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
4991 <            super(m, p, b);
4991 >            super(p, b, i, f, t);
4992              this.transformer = transformer; this.action = action;
4993          }
4994          public final void compute() {
# Line 5580 | Line 4996 | public class ConcurrentHashMap<K, V>
4996              final Consumer<? super U> action;
4997              if ((transformer = this.transformer) != null &&
4998                  (action = this.action) != null) {
4999 <                for (int b; (b = preSplit()) > 0;)
4999 >                for (int i = baseIndex, f, h; batch > 0 &&
5000 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5001 >                    addToPendingCount(1);
5002                      new ForEachTransformedKeyTask<K,V,U>
5003 <                        (map, this, b, transformer, action).fork();
5004 <                U u;
5005 <                while (advance() != null) {
5006 <                    if ((u = transformer.apply(nextKey)) != null)
5003 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5004 >                         transformer, action).fork();
5005 >                }
5006 >                for (Node<K,V> p; (p = advance()) != null; ) {
5007 >                    U u;
5008 >                    if ((u = transformer.apply(p.key)) != null)
5009                          action.accept(u);
5010                  }
5011                  propagateCompletion();
# Line 5593 | Line 5013 | public class ConcurrentHashMap<K, V>
5013          }
5014      }
5015  
5016 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5017 <        extends Traverser<K,V,Void> {
5016 >    @SuppressWarnings("serial")
5017 >    static final class ForEachTransformedValueTask<K,V,U>
5018 >        extends BulkTask<K,V,Void> {
5019          final Function<? super V, ? extends U> transformer;
5020          final Consumer<? super U> action;
5021          ForEachTransformedValueTask
5022 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5022 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5023               Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5024 <            super(m, p, b);
5024 >            super(p, b, i, f, t);
5025              this.transformer = transformer; this.action = action;
5026          }
5027          public final void compute() {
# Line 5608 | Line 5029 | public class ConcurrentHashMap<K, V>
5029              final Consumer<? super U> action;
5030              if ((transformer = this.transformer) != null &&
5031                  (action = this.action) != null) {
5032 <                for (int b; (b = preSplit()) > 0;)
5032 >                for (int i = baseIndex, f, h; batch > 0 &&
5033 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5034 >                    addToPendingCount(1);
5035                      new ForEachTransformedValueTask<K,V,U>
5036 <                        (map, this, b, transformer, action).fork();
5037 <                V v; U u;
5038 <                while ((v = advance()) != null) {
5039 <                    if ((u = transformer.apply(v)) != null)
5036 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5037 >                         transformer, action).fork();
5038 >                }
5039 >                for (Node<K,V> p; (p = advance()) != null; ) {
5040 >                    U u;
5041 >                    if ((u = transformer.apply(p.val)) != null)
5042                          action.accept(u);
5043                  }
5044                  propagateCompletion();
# Line 5621 | Line 5046 | public class ConcurrentHashMap<K, V>
5046          }
5047      }
5048  
5049 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5050 <        extends Traverser<K,V,Void> {
5049 >    @SuppressWarnings("serial")
5050 >    static final class ForEachTransformedEntryTask<K,V,U>
5051 >        extends BulkTask<K,V,Void> {
5052          final Function<Map.Entry<K,V>, ? extends U> transformer;
5053          final Consumer<? super U> action;
5054          ForEachTransformedEntryTask
5055 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5055 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5056               Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5057 <            super(m, p, b);
5057 >            super(p, b, i, f, t);
5058              this.transformer = transformer; this.action = action;
5059          }
5060          public final void compute() {
# Line 5636 | Line 5062 | public class ConcurrentHashMap<K, V>
5062              final Consumer<? super U> action;
5063              if ((transformer = this.transformer) != null &&
5064                  (action = this.action) != null) {
5065 <                for (int b; (b = preSplit()) > 0;)
5065 >                for (int i = baseIndex, f, h; batch > 0 &&
5066 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5067 >                    addToPendingCount(1);
5068                      new ForEachTransformedEntryTask<K,V,U>
5069 <                        (map, this, b, transformer, action).fork();
5070 <                V v; U u;
5071 <                while ((v = advance()) != null) {
5072 <                    if ((u = transformer.apply(entryFor(nextKey,
5073 <                                                        v))) != null)
5069 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5070 >                         transformer, action).fork();
5071 >                }
5072 >                for (Node<K,V> p; (p = advance()) != null; ) {
5073 >                    U u;
5074 >                    if ((u = transformer.apply(p)) != null)
5075                          action.accept(u);
5076                  }
5077                  propagateCompletion();
# Line 5650 | Line 5079 | public class ConcurrentHashMap<K, V>
5079          }
5080      }
5081  
5082 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5083 <        extends Traverser<K,V,Void> {
5082 >    @SuppressWarnings("serial")
5083 >    static final class ForEachTransformedMappingTask<K,V,U>
5084 >        extends BulkTask<K,V,Void> {
5085          final BiFunction<? super K, ? super V, ? extends U> transformer;
5086          final Consumer<? super U> action;
5087          ForEachTransformedMappingTask
5088 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5088 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5089               BiFunction<? super K, ? super V, ? extends U> transformer,
5090               Consumer<? super U> action) {
5091 <            super(m, p, b);
5091 >            super(p, b, i, f, t);
5092              this.transformer = transformer; this.action = action;
5093          }
5094          public final void compute() {
# Line 5666 | Line 5096 | public class ConcurrentHashMap<K, V>
5096              final Consumer<? super U> action;
5097              if ((transformer = this.transformer) != null &&
5098                  (action = this.action) != null) {
5099 <                for (int b; (b = preSplit()) > 0;)
5099 >                for (int i = baseIndex, f, h; batch > 0 &&
5100 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5101 >                    addToPendingCount(1);
5102                      new ForEachTransformedMappingTask<K,V,U>
5103 <                        (map, this, b, transformer, action).fork();
5104 <                V v; U u;
5105 <                while ((v = advance()) != null) {
5106 <                    if ((u = transformer.apply(nextKey, v)) != null)
5103 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5104 >                         transformer, action).fork();
5105 >                }
5106 >                for (Node<K,V> p; (p = advance()) != null; ) {
5107 >                    U u;
5108 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5109                          action.accept(u);
5110                  }
5111                  propagateCompletion();
# Line 5679 | Line 5113 | public class ConcurrentHashMap<K, V>
5113          }
5114      }
5115  
5116 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5117 <        extends Traverser<K,V,U> {
5116 >    @SuppressWarnings("serial")
5117 >    static final class SearchKeysTask<K,V,U>
5118 >        extends BulkTask<K,V,U> {
5119          final Function<? super K, ? extends U> searchFunction;
5120          final AtomicReference<U> result;
5121          SearchKeysTask
5122 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5122 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5123               Function<? super K, ? extends U> searchFunction,
5124               AtomicReference<U> result) {
5125 <            super(m, p, b);
5125 >            super(p, b, i, f, t);
5126              this.searchFunction = searchFunction; this.result = result;
5127          }
5128          public final U getRawResult() { return result.get(); }
# Line 5696 | Line 5131 | public class ConcurrentHashMap<K, V>
5131              final AtomicReference<U> result;
5132              if ((searchFunction = this.searchFunction) != null &&
5133                  (result = this.result) != null) {
5134 <                for (int b;;) {
5134 >                for (int i = baseIndex, f, h; batch > 0 &&
5135 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5136                      if (result.get() != null)
5137                          return;
5138 <                    if ((b = preSplit()) <= 0)
5703 <                        break;
5138 >                    addToPendingCount(1);
5139                      new SearchKeysTask<K,V,U>
5140 <                        (map, this, b, searchFunction, result).fork();
5140 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5141 >                         searchFunction, result).fork();
5142                  }
5143                  while (result.get() == null) {
5144                      U u;
5145 <                    if (advance() == null) {
5145 >                    Node<K,V> p;
5146 >                    if ((p = advance()) == null) {
5147                          propagateCompletion();
5148                          break;
5149                      }
5150 <                    if ((u = searchFunction.apply(nextKey)) != null) {
5150 >                    if ((u = searchFunction.apply(p.key)) != null) {
5151                          if (result.compareAndSet(null, u))
5152                              quietlyCompleteRoot();
5153                          break;
# Line 5720 | Line 5157 | public class ConcurrentHashMap<K, V>
5157          }
5158      }
5159  
5160 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5161 <        extends Traverser<K,V,U> {
5160 >    @SuppressWarnings("serial")
5161 >    static final class SearchValuesTask<K,V,U>
5162 >        extends BulkTask<K,V,U> {
5163          final Function<? super V, ? extends U> searchFunction;
5164          final AtomicReference<U> result;
5165          SearchValuesTask
5166 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5166 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5167               Function<? super V, ? extends U> searchFunction,
5168               AtomicReference<U> result) {
5169 <            super(m, p, b);
5169 >            super(p, b, i, f, t);
5170              this.searchFunction = searchFunction; this.result = result;
5171          }
5172          public final U getRawResult() { return result.get(); }
# Line 5737 | Line 5175 | public class ConcurrentHashMap<K, V>
5175              final AtomicReference<U> result;
5176              if ((searchFunction = this.searchFunction) != null &&
5177                  (result = this.result) != null) {
5178 <                for (int b;;) {
5178 >                for (int i = baseIndex, f, h; batch > 0 &&
5179 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5180                      if (result.get() != null)
5181                          return;
5182 <                    if ((b = preSplit()) <= 0)
5744 <                        break;
5182 >                    addToPendingCount(1);
5183                      new SearchValuesTask<K,V,U>
5184 <                        (map, this, b, searchFunction, result).fork();
5184 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5185 >                         searchFunction, result).fork();
5186                  }
5187                  while (result.get() == null) {
5188 <                    V v; U u;
5189 <                    if ((v = advance()) == null) {
5188 >                    U u;
5189 >                    Node<K,V> p;
5190 >                    if ((p = advance()) == null) {
5191                          propagateCompletion();
5192                          break;
5193                      }
5194 <                    if ((u = searchFunction.apply(v)) != null) {
5194 >                    if ((u = searchFunction.apply(p.val)) != null) {
5195                          if (result.compareAndSet(null, u))
5196                              quietlyCompleteRoot();
5197                          break;
# Line 5761 | Line 5201 | public class ConcurrentHashMap<K, V>
5201          }
5202      }
5203  
5204 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5205 <        extends Traverser<K,V,U> {
5204 >    @SuppressWarnings("serial")
5205 >    static final class SearchEntriesTask<K,V,U>
5206 >        extends BulkTask<K,V,U> {
5207          final Function<Entry<K,V>, ? extends U> searchFunction;
5208          final AtomicReference<U> result;
5209          SearchEntriesTask
5210 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5210 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5211               Function<Entry<K,V>, ? extends U> searchFunction,
5212               AtomicReference<U> result) {
5213 <            super(m, p, b);
5213 >            super(p, b, i, f, t);
5214              this.searchFunction = searchFunction; this.result = result;
5215          }
5216          public final U getRawResult() { return result.get(); }
# Line 5778 | Line 5219 | public class ConcurrentHashMap<K, V>
5219              final AtomicReference<U> result;
5220              if ((searchFunction = this.searchFunction) != null &&
5221                  (result = this.result) != null) {
5222 <                for (int b;;) {
5222 >                for (int i = baseIndex, f, h; batch > 0 &&
5223 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5224                      if (result.get() != null)
5225                          return;
5226 <                    if ((b = preSplit()) <= 0)
5785 <                        break;
5226 >                    addToPendingCount(1);
5227                      new SearchEntriesTask<K,V,U>
5228 <                        (map, this, b, searchFunction, result).fork();
5228 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5229 >                         searchFunction, result).fork();
5230                  }
5231                  while (result.get() == null) {
5232 <                    V v; U u;
5233 <                    if ((v = advance()) == null) {
5232 >                    U u;
5233 >                    Node<K,V> p;
5234 >                    if ((p = advance()) == null) {
5235                          propagateCompletion();
5236                          break;
5237                      }
5238 <                    if ((u = searchFunction.apply(entryFor(nextKey,
5796 <                                                           v))) != null) {
5238 >                    if ((u = searchFunction.apply(p)) != null) {
5239                          if (result.compareAndSet(null, u))
5240                              quietlyCompleteRoot();
5241                          return;
# Line 5803 | Line 5245 | public class ConcurrentHashMap<K, V>
5245          }
5246      }
5247  
5248 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5249 <        extends Traverser<K,V,U> {
5248 >    @SuppressWarnings("serial")
5249 >    static final class SearchMappingsTask<K,V,U>
5250 >        extends BulkTask<K,V,U> {
5251          final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5252          final AtomicReference<U> result;
5253          SearchMappingsTask
5254 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5254 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5255               BiFunction<? super K, ? super V, ? extends U> searchFunction,
5256               AtomicReference<U> result) {
5257 <            super(m, p, b);
5257 >            super(p, b, i, f, t);
5258              this.searchFunction = searchFunction; this.result = result;
5259          }
5260          public final U getRawResult() { return result.get(); }
# Line 5820 | Line 5263 | public class ConcurrentHashMap<K, V>
5263              final AtomicReference<U> result;
5264              if ((searchFunction = this.searchFunction) != null &&
5265                  (result = this.result) != null) {
5266 <                for (int b;;) {
5266 >                for (int i = baseIndex, f, h; batch > 0 &&
5267 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5268                      if (result.get() != null)
5269                          return;
5270 <                    if ((b = preSplit()) <= 0)
5827 <                        break;
5270 >                    addToPendingCount(1);
5271                      new SearchMappingsTask<K,V,U>
5272 <                        (map, this, b, searchFunction, result).fork();
5272 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5273 >                         searchFunction, result).fork();
5274                  }
5275                  while (result.get() == null) {
5276 <                    V v; U u;
5277 <                    if ((v = advance()) == null) {
5276 >                    U u;
5277 >                    Node<K,V> p;
5278 >                    if ((p = advance()) == null) {
5279                          propagateCompletion();
5280                          break;
5281                      }
5282 <                    if ((u = searchFunction.apply(nextKey, v)) != null) {
5282 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5283                          if (result.compareAndSet(null, u))
5284                              quietlyCompleteRoot();
5285                          break;
# Line 5844 | Line 5289 | public class ConcurrentHashMap<K, V>
5289          }
5290      }
5291  
5292 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5293 <        extends Traverser<K,V,K> {
5292 >    @SuppressWarnings("serial")
5293 >    static final class ReduceKeysTask<K,V>
5294 >        extends BulkTask<K,V,K> {
5295          final BiFunction<? super K, ? super K, ? extends K> reducer;
5296          K result;
5297          ReduceKeysTask<K,V> rights, nextRight;
5298          ReduceKeysTask
5299 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5299 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5300               ReduceKeysTask<K,V> nextRight,
5301               BiFunction<? super K, ? super K, ? extends K> reducer) {
5302 <            super(m, p, b); this.nextRight = nextRight;
5302 >            super(p, b, i, f, t); this.nextRight = nextRight;
5303              this.reducer = reducer;
5304          }
5305          public final K getRawResult() { return result; }
5306 <        @SuppressWarnings("unchecked") public final void compute() {
5306 >        public final void compute() {
5307              final BiFunction<? super K, ? super K, ? extends K> reducer;
5308              if ((reducer = this.reducer) != null) {
5309 <                for (int b; (b = preSplit()) > 0;)
5309 >                for (int i = baseIndex, f, h; batch > 0 &&
5310 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5311 >                    addToPendingCount(1);
5312                      (rights = new ReduceKeysTask<K,V>
5313 <                     (map, this, b, rights, reducer)).fork();
5313 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5314 >                      rights, reducer)).fork();
5315 >                }
5316                  K r = null;
5317 <                while (advance() != null) {
5318 <                    K u = nextKey;
5317 >                for (Node<K,V> p; (p = advance()) != null; ) {
5318 >                    K u = p.key;
5319                      r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5320                  }
5321                  result = r;
5322                  CountedCompleter<?> c;
5323                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5324 +                    @SuppressWarnings("unchecked")
5325                      ReduceKeysTask<K,V>
5326                          t = (ReduceKeysTask<K,V>)c,
5327                          s = t.rights;
# Line 5886 | Line 5337 | public class ConcurrentHashMap<K, V>
5337          }
5338      }
5339  
5340 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5341 <        extends Traverser<K,V,V> {
5340 >    @SuppressWarnings("serial")
5341 >    static final class ReduceValuesTask<K,V>
5342 >        extends BulkTask<K,V,V> {
5343          final BiFunction<? super V, ? super V, ? extends V> reducer;
5344          V result;
5345          ReduceValuesTask<K,V> rights, nextRight;
5346          ReduceValuesTask
5347 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5347 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5348               ReduceValuesTask<K,V> nextRight,
5349               BiFunction<? super V, ? super V, ? extends V> reducer) {
5350 <            super(m, p, b); this.nextRight = nextRight;
5350 >            super(p, b, i, f, t); this.nextRight = nextRight;
5351              this.reducer = reducer;
5352          }
5353          public final V getRawResult() { return result; }
5354 <        @SuppressWarnings("unchecked") public final void compute() {
5354 >        public final void compute() {
5355              final BiFunction<? super V, ? super V, ? extends V> reducer;
5356              if ((reducer = this.reducer) != null) {
5357 <                for (int b; (b = preSplit()) > 0;)
5357 >                for (int i = baseIndex, f, h; batch > 0 &&
5358 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5359 >                    addToPendingCount(1);
5360                      (rights = new ReduceValuesTask<K,V>
5361 <                     (map, this, b, rights, reducer)).fork();
5362 <                V r = null, v;
5363 <                while ((v = advance()) != null)
5361 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5362 >                      rights, reducer)).fork();
5363 >                }
5364 >                V r = null;
5365 >                for (Node<K,V> p; (p = advance()) != null; ) {
5366 >                    V v = p.val;
5367                      r = (r == null) ? v : reducer.apply(r, v);
5368 +                }
5369                  result = r;
5370                  CountedCompleter<?> c;
5371                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5372 +                    @SuppressWarnings("unchecked")
5373                      ReduceValuesTask<K,V>
5374                          t = (ReduceValuesTask<K,V>)c,
5375                          s = t.rights;
# Line 5926 | Line 5385 | public class ConcurrentHashMap<K, V>
5385          }
5386      }
5387  
5388 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5389 <        extends Traverser<K,V,Map.Entry<K,V>> {
5388 >    @SuppressWarnings("serial")
5389 >    static final class ReduceEntriesTask<K,V>
5390 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5391          final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5392          Map.Entry<K,V> result;
5393          ReduceEntriesTask<K,V> rights, nextRight;
5394          ReduceEntriesTask
5395 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5395 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5396               ReduceEntriesTask<K,V> nextRight,
5397               BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5398 <            super(m, p, b); this.nextRight = nextRight;
5398 >            super(p, b, i, f, t); this.nextRight = nextRight;
5399              this.reducer = reducer;
5400          }
5401          public final Map.Entry<K,V> getRawResult() { return result; }
5402 <        @SuppressWarnings("unchecked") public final void compute() {
5402 >        public final void compute() {
5403              final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5404              if ((reducer = this.reducer) != null) {
5405 <                for (int b; (b = preSplit()) > 0;)
5405 >                for (int i = baseIndex, f, h; batch > 0 &&
5406 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5407 >                    addToPendingCount(1);
5408                      (rights = new ReduceEntriesTask<K,V>
5409 <                     (map, this, b, rights, reducer)).fork();
5410 <                Map.Entry<K,V> r = null;
5949 <                V v;
5950 <                while ((v = advance()) != null) {
5951 <                    Map.Entry<K,V> u = entryFor(nextKey, v);
5952 <                    r = (r == null) ? u : reducer.apply(r, u);
5409 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5410 >                      rights, reducer)).fork();
5411                  }
5412 +                Map.Entry<K,V> r = null;
5413 +                for (Node<K,V> p; (p = advance()) != null; )
5414 +                    r = (r == null) ? p : reducer.apply(r, p);
5415                  result = r;
5416                  CountedCompleter<?> c;
5417                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5418 +                    @SuppressWarnings("unchecked")
5419                      ReduceEntriesTask<K,V>
5420                          t = (ReduceEntriesTask<K,V>)c,
5421                          s = t.rights;
# Line 5969 | Line 5431 | public class ConcurrentHashMap<K, V>
5431          }
5432      }
5433  
5434 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5435 <        extends Traverser<K,V,U> {
5434 >    @SuppressWarnings("serial")
5435 >    static final class MapReduceKeysTask<K,V,U>
5436 >        extends BulkTask<K,V,U> {
5437          final Function<? super K, ? extends U> transformer;
5438          final BiFunction<? super U, ? super U, ? extends U> reducer;
5439          U result;
5440          MapReduceKeysTask<K,V,U> rights, nextRight;
5441          MapReduceKeysTask
5442 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5442 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5443               MapReduceKeysTask<K,V,U> nextRight,
5444               Function<? super K, ? extends U> transformer,
5445               BiFunction<? super U, ? super U, ? extends U> reducer) {
5446 <            super(m, p, b); this.nextRight = nextRight;
5446 >            super(p, b, i, f, t); this.nextRight = nextRight;
5447              this.transformer = transformer;
5448              this.reducer = reducer;
5449          }
5450          public final U getRawResult() { return result; }
5451 <        @SuppressWarnings("unchecked") public final void compute() {
5451 >        public final void compute() {
5452              final Function<? super K, ? extends U> transformer;
5453              final BiFunction<? super U, ? super U, ? extends U> reducer;
5454              if ((transformer = this.transformer) != null &&
5455                  (reducer = this.reducer) != null) {
5456 <                for (int b; (b = preSplit()) > 0;)
5456 >                for (int i = baseIndex, f, h; batch > 0 &&
5457 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5458 >                    addToPendingCount(1);
5459                      (rights = new MapReduceKeysTask<K,V,U>
5460 <                     (map, this, b, rights, transformer, reducer)).fork();
5461 <                U r = null, u;
5462 <                while (advance() != null) {
5463 <                    if ((u = transformer.apply(nextKey)) != null)
5460 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5461 >                      rights, transformer, reducer)).fork();
5462 >                }
5463 >                U r = null;
5464 >                for (Node<K,V> p; (p = advance()) != null; ) {
5465 >                    U u;
5466 >                    if ((u = transformer.apply(p.key)) != null)
5467                          r = (r == null) ? u : reducer.apply(r, u);
5468                  }
5469                  result = r;
5470                  CountedCompleter<?> c;
5471                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5472 +                    @SuppressWarnings("unchecked")
5473                      MapReduceKeysTask<K,V,U>
5474                          t = (MapReduceKeysTask<K,V,U>)c,
5475                          s = t.rights;
# Line 6016 | Line 5485 | public class ConcurrentHashMap<K, V>
5485          }
5486      }
5487  
5488 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5489 <        extends Traverser<K,V,U> {
5488 >    @SuppressWarnings("serial")
5489 >    static final class MapReduceValuesTask<K,V,U>
5490 >        extends BulkTask<K,V,U> {
5491          final Function<? super V, ? extends U> transformer;
5492          final BiFunction<? super U, ? super U, ? extends U> reducer;
5493          U result;
5494          MapReduceValuesTask<K,V,U> rights, nextRight;
5495          MapReduceValuesTask
5496 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5496 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5497               MapReduceValuesTask<K,V,U> nextRight,
5498               Function<? super V, ? extends U> transformer,
5499               BiFunction<? super U, ? super U, ? extends U> reducer) {
5500 <            super(m, p, b); this.nextRight = nextRight;
5500 >            super(p, b, i, f, t); this.nextRight = nextRight;
5501              this.transformer = transformer;
5502              this.reducer = reducer;
5503          }
5504          public final U getRawResult() { return result; }
5505 <        @SuppressWarnings("unchecked") public final void compute() {
5505 >        public final void compute() {
5506              final Function<? super V, ? extends U> transformer;
5507              final BiFunction<? super U, ? super U, ? extends U> reducer;
5508              if ((transformer = this.transformer) != null &&
5509                  (reducer = this.reducer) != null) {
5510 <                for (int b; (b = preSplit()) > 0;)
5510 >                for (int i = baseIndex, f, h; batch > 0 &&
5511 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5512 >                    addToPendingCount(1);
5513                      (rights = new MapReduceValuesTask<K,V,U>
5514 <                     (map, this, b, rights, transformer, reducer)).fork();
5515 <                U r = null, u;
5516 <                V v;
5517 <                while ((v = advance()) != null) {
5518 <                    if ((u = transformer.apply(v)) != null)
5514 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5515 >                      rights, transformer, reducer)).fork();
5516 >                }
5517 >                U r = null;
5518 >                for (Node<K,V> p; (p = advance()) != null; ) {
5519 >                    U u;
5520 >                    if ((u = transformer.apply(p.val)) != null)
5521                          r = (r == null) ? u : reducer.apply(r, u);
5522                  }
5523                  result = r;
5524                  CountedCompleter<?> c;
5525                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5526 +                    @SuppressWarnings("unchecked")
5527                      MapReduceValuesTask<K,V,U>
5528                          t = (MapReduceValuesTask<K,V,U>)c,
5529                          s = t.rights;
# Line 6064 | Line 5539 | public class ConcurrentHashMap<K, V>
5539          }
5540      }
5541  
5542 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5543 <        extends Traverser<K,V,U> {
5542 >    @SuppressWarnings("serial")
5543 >    static final class MapReduceEntriesTask<K,V,U>
5544 >        extends BulkTask<K,V,U> {
5545          final Function<Map.Entry<K,V>, ? extends U> transformer;
5546          final BiFunction<? super U, ? super U, ? extends U> reducer;
5547          U result;
5548          MapReduceEntriesTask<K,V,U> rights, nextRight;
5549          MapReduceEntriesTask
5550 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5550 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5551               MapReduceEntriesTask<K,V,U> nextRight,
5552               Function<Map.Entry<K,V>, ? extends U> transformer,
5553               BiFunction<? super U, ? super U, ? extends U> reducer) {
5554 <            super(m, p, b); this.nextRight = nextRight;
5554 >            super(p, b, i, f, t); this.nextRight = nextRight;
5555              this.transformer = transformer;
5556              this.reducer = reducer;
5557          }
5558          public final U getRawResult() { return result; }
5559 <        @SuppressWarnings("unchecked") public final void compute() {
5559 >        public final void compute() {
5560              final Function<Map.Entry<K,V>, ? extends U> transformer;
5561              final BiFunction<? super U, ? super U, ? extends U> reducer;
5562              if ((transformer = this.transformer) != null &&
5563                  (reducer = this.reducer) != null) {
5564 <                for (int b; (b = preSplit()) > 0;)
5564 >                for (int i = baseIndex, f, h; batch > 0 &&
5565 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5566 >                    addToPendingCount(1);
5567                      (rights = new MapReduceEntriesTask<K,V,U>
5568 <                     (map, this, b, rights, transformer, reducer)).fork();
5569 <                U r = null, u;
5570 <                V v;
5571 <                while ((v = advance()) != null) {
5572 <                    if ((u = transformer.apply(entryFor(nextKey,
5573 <                                                        v))) != null)
5568 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5569 >                      rights, transformer, reducer)).fork();
5570 >                }
5571 >                U r = null;
5572 >                for (Node<K,V> p; (p = advance()) != null; ) {
5573 >                    U u;
5574 >                    if ((u = transformer.apply(p)) != null)
5575                          r = (r == null) ? u : reducer.apply(r, u);
5576                  }
5577                  result = r;
5578                  CountedCompleter<?> c;
5579                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5580 +                    @SuppressWarnings("unchecked")
5581                      MapReduceEntriesTask<K,V,U>
5582                          t = (MapReduceEntriesTask<K,V,U>)c,
5583                          s = t.rights;
# Line 6113 | Line 5593 | public class ConcurrentHashMap<K, V>
5593          }
5594      }
5595  
5596 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5597 <        extends Traverser<K,V,U> {
5596 >    @SuppressWarnings("serial")
5597 >    static final class MapReduceMappingsTask<K,V,U>
5598 >        extends BulkTask<K,V,U> {
5599          final BiFunction<? super K, ? super V, ? extends U> transformer;
5600          final BiFunction<? super U, ? super U, ? extends U> reducer;
5601          U result;
5602          MapReduceMappingsTask<K,V,U> rights, nextRight;
5603          MapReduceMappingsTask
5604 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5604 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5605               MapReduceMappingsTask<K,V,U> nextRight,
5606               BiFunction<? super K, ? super V, ? extends U> transformer,
5607               BiFunction<? super U, ? super U, ? extends U> reducer) {
5608 <            super(m, p, b); this.nextRight = nextRight;
5608 >            super(p, b, i, f, t); this.nextRight = nextRight;
5609              this.transformer = transformer;
5610              this.reducer = reducer;
5611          }
5612          public final U getRawResult() { return result; }
5613 <        @SuppressWarnings("unchecked") public final void compute() {
5613 >        public final void compute() {
5614              final BiFunction<? super K, ? super V, ? extends U> transformer;
5615              final BiFunction<? super U, ? super U, ? extends U> reducer;
5616              if ((transformer = this.transformer) != null &&
5617                  (reducer = this.reducer) != null) {
5618 <                for (int b; (b = preSplit()) > 0;)
5618 >                for (int i = baseIndex, f, h; batch > 0 &&
5619 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5620 >                    addToPendingCount(1);
5621                      (rights = new MapReduceMappingsTask<K,V,U>
5622 <                     (map, this, b, rights, transformer, reducer)).fork();
5623 <                U r = null, u;
5624 <                V v;
5625 <                while ((v = advance()) != null) {
5626 <                    if ((u = transformer.apply(nextKey, v)) != null)
5622 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5623 >                      rights, transformer, reducer)).fork();
5624 >                }
5625 >                U r = null;
5626 >                for (Node<K,V> p; (p = advance()) != null; ) {
5627 >                    U u;
5628 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5629                          r = (r == null) ? u : reducer.apply(r, u);
5630                  }
5631                  result = r;
5632                  CountedCompleter<?> c;
5633                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5634 +                    @SuppressWarnings("unchecked")
5635                      MapReduceMappingsTask<K,V,U>
5636                          t = (MapReduceMappingsTask<K,V,U>)c,
5637                          s = t.rights;
# Line 6161 | Line 5647 | public class ConcurrentHashMap<K, V>
5647          }
5648      }
5649  
5650 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5651 <        extends Traverser<K,V,Double> {
5650 >    @SuppressWarnings("serial")
5651 >    static final class MapReduceKeysToDoubleTask<K,V>
5652 >        extends BulkTask<K,V,Double> {
5653          final ToDoubleFunction<? super K> transformer;
5654          final DoubleBinaryOperator reducer;
5655          final double basis;
5656          double result;
5657          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5658          MapReduceKeysToDoubleTask
5659 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5659 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5660               MapReduceKeysToDoubleTask<K,V> nextRight,
5661               ToDoubleFunction<? super K> transformer,
5662               double basis,
5663               DoubleBinaryOperator reducer) {
5664 <            super(m, p, b); this.nextRight = nextRight;
5664 >            super(p, b, i, f, t); this.nextRight = nextRight;
5665              this.transformer = transformer;
5666              this.basis = basis; this.reducer = reducer;
5667          }
5668          public final Double getRawResult() { return result; }
5669 <        @SuppressWarnings("unchecked") public final void compute() {
5669 >        public final void compute() {
5670              final ToDoubleFunction<? super K> transformer;
5671              final DoubleBinaryOperator reducer;
5672              if ((transformer = this.transformer) != null &&
5673                  (reducer = this.reducer) != null) {
5674                  double r = this.basis;
5675 <                for (int b; (b = preSplit()) > 0;)
5675 >                for (int i = baseIndex, f, h; batch > 0 &&
5676 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5677 >                    addToPendingCount(1);
5678                      (rights = new MapReduceKeysToDoubleTask<K,V>
5679 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5680 <                while (advance() != null)
5681 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey));
5679 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5680 >                      rights, transformer, r, reducer)).fork();
5681 >                }
5682 >                for (Node<K,V> p; (p = advance()) != null; )
5683 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5684                  result = r;
5685                  CountedCompleter<?> c;
5686                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5687 +                    @SuppressWarnings("unchecked")
5688                      MapReduceKeysToDoubleTask<K,V>
5689                          t = (MapReduceKeysToDoubleTask<K,V>)c,
5690                          s = t.rights;
# Line 6205 | Line 5697 | public class ConcurrentHashMap<K, V>
5697          }
5698      }
5699  
5700 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5701 <        extends Traverser<K,V,Double> {
5700 >    @SuppressWarnings("serial")
5701 >    static final class MapReduceValuesToDoubleTask<K,V>
5702 >        extends BulkTask<K,V,Double> {
5703          final ToDoubleFunction<? super V> transformer;
5704          final DoubleBinaryOperator reducer;
5705          final double basis;
5706          double result;
5707          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5708          MapReduceValuesToDoubleTask
5709 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5709 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5710               MapReduceValuesToDoubleTask<K,V> nextRight,
5711               ToDoubleFunction<? super V> transformer,
5712               double basis,
5713               DoubleBinaryOperator reducer) {
5714 <            super(m, p, b); this.nextRight = nextRight;
5714 >            super(p, b, i, f, t); this.nextRight = nextRight;
5715              this.transformer = transformer;
5716              this.basis = basis; this.reducer = reducer;
5717          }
5718          public final Double getRawResult() { return result; }
5719 <        @SuppressWarnings("unchecked") public final void compute() {
5719 >        public final void compute() {
5720              final ToDoubleFunction<? super V> transformer;
5721              final DoubleBinaryOperator reducer;
5722              if ((transformer = this.transformer) != null &&
5723                  (reducer = this.reducer) != null) {
5724                  double r = this.basis;
5725 <                for (int b; (b = preSplit()) > 0;)
5725 >                for (int i = baseIndex, f, h; batch > 0 &&
5726 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5727 >                    addToPendingCount(1);
5728                      (rights = new MapReduceValuesToDoubleTask<K,V>
5729 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5730 <                V v;
5731 <                while ((v = advance()) != null)
5732 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
5729 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5730 >                      rights, transformer, r, reducer)).fork();
5731 >                }
5732 >                for (Node<K,V> p; (p = advance()) != null; )
5733 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5734                  result = r;
5735                  CountedCompleter<?> c;
5736                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5737 +                    @SuppressWarnings("unchecked")
5738                      MapReduceValuesToDoubleTask<K,V>
5739                          t = (MapReduceValuesToDoubleTask<K,V>)c,
5740                          s = t.rights;
# Line 6250 | Line 5747 | public class ConcurrentHashMap<K, V>
5747          }
5748      }
5749  
5750 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5751 <        extends Traverser<K,V,Double> {
5750 >    @SuppressWarnings("serial")
5751 >    static final class MapReduceEntriesToDoubleTask<K,V>
5752 >        extends BulkTask<K,V,Double> {
5753          final ToDoubleFunction<Map.Entry<K,V>> transformer;
5754          final DoubleBinaryOperator reducer;
5755          final double basis;
5756          double result;
5757          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5758          MapReduceEntriesToDoubleTask
5759 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5759 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5760               MapReduceEntriesToDoubleTask<K,V> nextRight,
5761               ToDoubleFunction<Map.Entry<K,V>> transformer,
5762               double basis,
5763               DoubleBinaryOperator reducer) {
5764 <            super(m, p, b); this.nextRight = nextRight;
5764 >            super(p, b, i, f, t); this.nextRight = nextRight;
5765              this.transformer = transformer;
5766              this.basis = basis; this.reducer = reducer;
5767          }
5768          public final Double getRawResult() { return result; }
5769 <        @SuppressWarnings("unchecked") public final void compute() {
5769 >        public final void compute() {
5770              final ToDoubleFunction<Map.Entry<K,V>> transformer;
5771              final DoubleBinaryOperator reducer;
5772              if ((transformer = this.transformer) != null &&
5773                  (reducer = this.reducer) != null) {
5774                  double r = this.basis;
5775 <                for (int b; (b = preSplit()) > 0;)
5775 >                for (int i = baseIndex, f, h; batch > 0 &&
5776 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5777 >                    addToPendingCount(1);
5778                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5779 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5780 <                V v;
5781 <                while ((v = advance()) != null)
5782 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(nextKey,
5783 <                                                                    v)));
5779 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5780 >                      rights, transformer, r, reducer)).fork();
5781 >                }
5782 >                for (Node<K,V> p; (p = advance()) != null; )
5783 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5784                  result = r;
5785                  CountedCompleter<?> c;
5786                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5787 +                    @SuppressWarnings("unchecked")
5788                      MapReduceEntriesToDoubleTask<K,V>
5789                          t = (MapReduceEntriesToDoubleTask<K,V>)c,
5790                          s = t.rights;
# Line 6296 | Line 5797 | public class ConcurrentHashMap<K, V>
5797          }
5798      }
5799  
5800 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5801 <        extends Traverser<K,V,Double> {
5800 >    @SuppressWarnings("serial")
5801 >    static final class MapReduceMappingsToDoubleTask<K,V>
5802 >        extends BulkTask<K,V,Double> {
5803          final ToDoubleBiFunction<? super K, ? super V> transformer;
5804          final DoubleBinaryOperator reducer;
5805          final double basis;
5806          double result;
5807          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5808          MapReduceMappingsToDoubleTask
5809 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5809 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5810               MapReduceMappingsToDoubleTask<K,V> nextRight,
5811               ToDoubleBiFunction<? super K, ? super V> transformer,
5812               double basis,
5813               DoubleBinaryOperator reducer) {
5814 <            super(m, p, b); this.nextRight = nextRight;
5814 >            super(p, b, i, f, t); this.nextRight = nextRight;
5815              this.transformer = transformer;
5816              this.basis = basis; this.reducer = reducer;
5817          }
5818          public final Double getRawResult() { return result; }
5819 <        @SuppressWarnings("unchecked") public final void compute() {
5819 >        public final void compute() {
5820              final ToDoubleBiFunction<? super K, ? super V> transformer;
5821              final DoubleBinaryOperator reducer;
5822              if ((transformer = this.transformer) != null &&
5823                  (reducer = this.reducer) != null) {
5824                  double r = this.basis;
5825 <                for (int b; (b = preSplit()) > 0;)
5825 >                for (int i = baseIndex, f, h; batch > 0 &&
5826 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5827 >                    addToPendingCount(1);
5828                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5829 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5830 <                V v;
5831 <                while ((v = advance()) != null)
5832 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey, v));
5829 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5830 >                      rights, transformer, r, reducer)).fork();
5831 >                }
5832 >                for (Node<K,V> p; (p = advance()) != null; )
5833 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5834                  result = r;
5835                  CountedCompleter<?> c;
5836                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5837 +                    @SuppressWarnings("unchecked")
5838                      MapReduceMappingsToDoubleTask<K,V>
5839                          t = (MapReduceMappingsToDoubleTask<K,V>)c,
5840                          s = t.rights;
# Line 6341 | Line 5847 | public class ConcurrentHashMap<K, V>
5847          }
5848      }
5849  
5850 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5851 <        extends Traverser<K,V,Long> {
5850 >    @SuppressWarnings("serial")
5851 >    static final class MapReduceKeysToLongTask<K,V>
5852 >        extends BulkTask<K,V,Long> {
5853          final ToLongFunction<? super K> transformer;
5854          final LongBinaryOperator reducer;
5855          final long basis;
5856          long result;
5857          MapReduceKeysToLongTask<K,V> rights, nextRight;
5858          MapReduceKeysToLongTask
5859 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5859 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5860               MapReduceKeysToLongTask<K,V> nextRight,
5861               ToLongFunction<? super K> transformer,
5862               long basis,
5863               LongBinaryOperator reducer) {
5864 <            super(m, p, b); this.nextRight = nextRight;
5864 >            super(p, b, i, f, t); this.nextRight = nextRight;
5865              this.transformer = transformer;
5866              this.basis = basis; this.reducer = reducer;
5867          }
5868          public final Long getRawResult() { return result; }
5869 <        @SuppressWarnings("unchecked") public final void compute() {
5869 >        public final void compute() {
5870              final ToLongFunction<? super K> transformer;
5871              final LongBinaryOperator reducer;
5872              if ((transformer = this.transformer) != null &&
5873                  (reducer = this.reducer) != null) {
5874                  long r = this.basis;
5875 <                for (int b; (b = preSplit()) > 0;)
5875 >                for (int i = baseIndex, f, h; batch > 0 &&
5876 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5877 >                    addToPendingCount(1);
5878                      (rights = new MapReduceKeysToLongTask<K,V>
5879 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5880 <                while (advance() != null)
5881 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey));
5879 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5880 >                      rights, transformer, r, reducer)).fork();
5881 >                }
5882 >                for (Node<K,V> p; (p = advance()) != null; )
5883 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5884                  result = r;
5885                  CountedCompleter<?> c;
5886                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5887 +                    @SuppressWarnings("unchecked")
5888                      MapReduceKeysToLongTask<K,V>
5889                          t = (MapReduceKeysToLongTask<K,V>)c,
5890                          s = t.rights;
# Line 6385 | Line 5897 | public class ConcurrentHashMap<K, V>
5897          }
5898      }
5899  
5900 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5901 <        extends Traverser<K,V,Long> {
5900 >    @SuppressWarnings("serial")
5901 >    static final class MapReduceValuesToLongTask<K,V>
5902 >        extends BulkTask<K,V,Long> {
5903          final ToLongFunction<? super V> transformer;
5904          final LongBinaryOperator reducer;
5905          final long basis;
5906          long result;
5907          MapReduceValuesToLongTask<K,V> rights, nextRight;
5908          MapReduceValuesToLongTask
5909 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5909 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5910               MapReduceValuesToLongTask<K,V> nextRight,
5911               ToLongFunction<? super V> transformer,
5912               long basis,
5913               LongBinaryOperator reducer) {
5914 <            super(m, p, b); this.nextRight = nextRight;
5914 >            super(p, b, i, f, t); this.nextRight = nextRight;
5915              this.transformer = transformer;
5916              this.basis = basis; this.reducer = reducer;
5917          }
5918          public final Long getRawResult() { return result; }
5919 <        @SuppressWarnings("unchecked") public final void compute() {
5919 >        public final void compute() {
5920              final ToLongFunction<? super V> transformer;
5921              final LongBinaryOperator reducer;
5922              if ((transformer = this.transformer) != null &&
5923                  (reducer = this.reducer) != null) {
5924                  long r = this.basis;
5925 <                for (int b; (b = preSplit()) > 0;)
5925 >                for (int i = baseIndex, f, h; batch > 0 &&
5926 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5927 >                    addToPendingCount(1);
5928                      (rights = new MapReduceValuesToLongTask<K,V>
5929 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5930 <                V v;
5931 <                while ((v = advance()) != null)
5932 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(v));
5929 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5930 >                      rights, transformer, r, reducer)).fork();
5931 >                }
5932 >                for (Node<K,V> p; (p = advance()) != null; )
5933 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5934                  result = r;
5935                  CountedCompleter<?> c;
5936                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5937 +                    @SuppressWarnings("unchecked")
5938                      MapReduceValuesToLongTask<K,V>
5939                          t = (MapReduceValuesToLongTask<K,V>)c,
5940                          s = t.rights;
# Line 6430 | Line 5947 | public class ConcurrentHashMap<K, V>
5947          }
5948      }
5949  
5950 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5951 <        extends Traverser<K,V,Long> {
5950 >    @SuppressWarnings("serial")
5951 >    static final class MapReduceEntriesToLongTask<K,V>
5952 >        extends BulkTask<K,V,Long> {
5953          final ToLongFunction<Map.Entry<K,V>> transformer;
5954          final LongBinaryOperator reducer;
5955          final long basis;
5956          long result;
5957          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5958          MapReduceEntriesToLongTask
5959 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5959 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5960               MapReduceEntriesToLongTask<K,V> nextRight,
5961               ToLongFunction<Map.Entry<K,V>> transformer,
5962               long basis,
5963               LongBinaryOperator reducer) {
5964 <            super(m, p, b); this.nextRight = nextRight;
5964 >            super(p, b, i, f, t); this.nextRight = nextRight;
5965              this.transformer = transformer;
5966              this.basis = basis; this.reducer = reducer;
5967          }
5968          public final Long getRawResult() { return result; }
5969 <        @SuppressWarnings("unchecked") public final void compute() {
5969 >        public final void compute() {
5970              final ToLongFunction<Map.Entry<K,V>> transformer;
5971              final LongBinaryOperator reducer;
5972              if ((transformer = this.transformer) != null &&
5973                  (reducer = this.reducer) != null) {
5974                  long r = this.basis;
5975 <                for (int b; (b = preSplit()) > 0;)
5975 >                for (int i = baseIndex, f, h; batch > 0 &&
5976 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5977 >                    addToPendingCount(1);
5978                      (rights = new MapReduceEntriesToLongTask<K,V>
5979 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5980 <                V v;
5981 <                while ((v = advance()) != null)
5982 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(nextKey, v)));
5979 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5980 >                      rights, transformer, r, reducer)).fork();
5981 >                }
5982 >                for (Node<K,V> p; (p = advance()) != null; )
5983 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
5984                  result = r;
5985                  CountedCompleter<?> c;
5986                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5987 +                    @SuppressWarnings("unchecked")
5988                      MapReduceEntriesToLongTask<K,V>
5989                          t = (MapReduceEntriesToLongTask<K,V>)c,
5990                          s = t.rights;
# Line 6475 | Line 5997 | public class ConcurrentHashMap<K, V>
5997          }
5998      }
5999  
6000 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6001 <        extends Traverser<K,V,Long> {
6000 >    @SuppressWarnings("serial")
6001 >    static final class MapReduceMappingsToLongTask<K,V>
6002 >        extends BulkTask<K,V,Long> {
6003          final ToLongBiFunction<? super K, ? super V> transformer;
6004          final LongBinaryOperator reducer;
6005          final long basis;
6006          long result;
6007          MapReduceMappingsToLongTask<K,V> rights, nextRight;
6008          MapReduceMappingsToLongTask
6009 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6009 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6010               MapReduceMappingsToLongTask<K,V> nextRight,
6011               ToLongBiFunction<? super K, ? super V> transformer,
6012               long basis,
6013               LongBinaryOperator reducer) {
6014 <            super(m, p, b); this.nextRight = nextRight;
6014 >            super(p, b, i, f, t); this.nextRight = nextRight;
6015              this.transformer = transformer;
6016              this.basis = basis; this.reducer = reducer;
6017          }
6018          public final Long getRawResult() { return result; }
6019 <        @SuppressWarnings("unchecked") public final void compute() {
6019 >        public final void compute() {
6020              final ToLongBiFunction<? super K, ? super V> transformer;
6021              final LongBinaryOperator reducer;
6022              if ((transformer = this.transformer) != null &&
6023                  (reducer = this.reducer) != null) {
6024                  long r = this.basis;
6025 <                for (int b; (b = preSplit()) > 0;)
6025 >                for (int i = baseIndex, f, h; batch > 0 &&
6026 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6027 >                    addToPendingCount(1);
6028                      (rights = new MapReduceMappingsToLongTask<K,V>
6029 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6030 <                V v;
6031 <                while ((v = advance()) != null)
6032 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey, v));
6029 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6030 >                      rights, transformer, r, reducer)).fork();
6031 >                }
6032 >                for (Node<K,V> p; (p = advance()) != null; )
6033 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
6034                  result = r;
6035                  CountedCompleter<?> c;
6036                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6037 +                    @SuppressWarnings("unchecked")
6038                      MapReduceMappingsToLongTask<K,V>
6039                          t = (MapReduceMappingsToLongTask<K,V>)c,
6040                          s = t.rights;
# Line 6520 | Line 6047 | public class ConcurrentHashMap<K, V>
6047          }
6048      }
6049  
6050 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6051 <        extends Traverser<K,V,Integer> {
6050 >    @SuppressWarnings("serial")
6051 >    static final class MapReduceKeysToIntTask<K,V>
6052 >        extends BulkTask<K,V,Integer> {
6053          final ToIntFunction<? super K> transformer;
6054          final IntBinaryOperator reducer;
6055          final int basis;
6056          int result;
6057          MapReduceKeysToIntTask<K,V> rights, nextRight;
6058          MapReduceKeysToIntTask
6059 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6059 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6060               MapReduceKeysToIntTask<K,V> nextRight,
6061               ToIntFunction<? super K> transformer,
6062               int basis,
6063               IntBinaryOperator reducer) {
6064 <            super(m, p, b); this.nextRight = nextRight;
6064 >            super(p, b, i, f, t); this.nextRight = nextRight;
6065              this.transformer = transformer;
6066              this.basis = basis; this.reducer = reducer;
6067          }
6068          public final Integer getRawResult() { return result; }
6069 <        @SuppressWarnings("unchecked") public final void compute() {
6069 >        public final void compute() {
6070              final ToIntFunction<? super K> transformer;
6071              final IntBinaryOperator reducer;
6072              if ((transformer = this.transformer) != null &&
6073                  (reducer = this.reducer) != null) {
6074                  int r = this.basis;
6075 <                for (int b; (b = preSplit()) > 0;)
6075 >                for (int i = baseIndex, f, h; batch > 0 &&
6076 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6077 >                    addToPendingCount(1);
6078                      (rights = new MapReduceKeysToIntTask<K,V>
6079 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6080 <                while (advance() != null)
6081 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey));
6079 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6080 >                      rights, transformer, r, reducer)).fork();
6081 >                }
6082 >                for (Node<K,V> p; (p = advance()) != null; )
6083 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
6084                  result = r;
6085                  CountedCompleter<?> c;
6086                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6087 +                    @SuppressWarnings("unchecked")
6088                      MapReduceKeysToIntTask<K,V>
6089                          t = (MapReduceKeysToIntTask<K,V>)c,
6090                          s = t.rights;
# Line 6564 | Line 6097 | public class ConcurrentHashMap<K, V>
6097          }
6098      }
6099  
6100 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6101 <        extends Traverser<K,V,Integer> {
6100 >    @SuppressWarnings("serial")
6101 >    static final class MapReduceValuesToIntTask<K,V>
6102 >        extends BulkTask<K,V,Integer> {
6103          final ToIntFunction<? super V> transformer;
6104          final IntBinaryOperator reducer;
6105          final int basis;
6106          int result;
6107          MapReduceValuesToIntTask<K,V> rights, nextRight;
6108          MapReduceValuesToIntTask
6109 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6109 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6110               MapReduceValuesToIntTask<K,V> nextRight,
6111               ToIntFunction<? super V> transformer,
6112               int basis,
6113               IntBinaryOperator reducer) {
6114 <            super(m, p, b); this.nextRight = nextRight;
6114 >            super(p, b, i, f, t); this.nextRight = nextRight;
6115              this.transformer = transformer;
6116              this.basis = basis; this.reducer = reducer;
6117          }
6118          public final Integer getRawResult() { return result; }
6119 <        @SuppressWarnings("unchecked") public final void compute() {
6119 >        public final void compute() {
6120              final ToIntFunction<? super V> transformer;
6121              final IntBinaryOperator reducer;
6122              if ((transformer = this.transformer) != null &&
6123                  (reducer = this.reducer) != null) {
6124                  int r = this.basis;
6125 <                for (int b; (b = preSplit()) > 0;)
6125 >                for (int i = baseIndex, f, h; batch > 0 &&
6126 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6127 >                    addToPendingCount(1);
6128                      (rights = new MapReduceValuesToIntTask<K,V>
6129 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6130 <                V v;
6131 <                while ((v = advance()) != null)
6132 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(v));
6129 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6130 >                      rights, transformer, r, reducer)).fork();
6131 >                }
6132 >                for (Node<K,V> p; (p = advance()) != null; )
6133 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
6134                  result = r;
6135                  CountedCompleter<?> c;
6136                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6137 +                    @SuppressWarnings("unchecked")
6138                      MapReduceValuesToIntTask<K,V>
6139                          t = (MapReduceValuesToIntTask<K,V>)c,
6140                          s = t.rights;
# Line 6609 | Line 6147 | public class ConcurrentHashMap<K, V>
6147          }
6148      }
6149  
6150 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6151 <        extends Traverser<K,V,Integer> {
6150 >    @SuppressWarnings("serial")
6151 >    static final class MapReduceEntriesToIntTask<K,V>
6152 >        extends BulkTask<K,V,Integer> {
6153          final ToIntFunction<Map.Entry<K,V>> transformer;
6154          final IntBinaryOperator reducer;
6155          final int basis;
6156          int result;
6157          MapReduceEntriesToIntTask<K,V> rights, nextRight;
6158          MapReduceEntriesToIntTask
6159 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6159 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6160               MapReduceEntriesToIntTask<K,V> nextRight,
6161               ToIntFunction<Map.Entry<K,V>> transformer,
6162               int basis,
6163               IntBinaryOperator reducer) {
6164 <            super(m, p, b); this.nextRight = nextRight;
6164 >            super(p, b, i, f, t); this.nextRight = nextRight;
6165              this.transformer = transformer;
6166              this.basis = basis; this.reducer = reducer;
6167          }
6168          public final Integer getRawResult() { return result; }
6169 <        @SuppressWarnings("unchecked") public final void compute() {
6169 >        public final void compute() {
6170              final ToIntFunction<Map.Entry<K,V>> transformer;
6171              final IntBinaryOperator reducer;
6172              if ((transformer = this.transformer) != null &&
6173                  (reducer = this.reducer) != null) {
6174                  int r = this.basis;
6175 <                for (int b; (b = preSplit()) > 0;)
6175 >                for (int i = baseIndex, f, h; batch > 0 &&
6176 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6177 >                    addToPendingCount(1);
6178                      (rights = new MapReduceEntriesToIntTask<K,V>
6179 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6180 <                V v;
6181 <                while ((v = advance()) != null)
6182 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(nextKey,
6183 <                                                                    v)));
6179 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6180 >                      rights, transformer, r, reducer)).fork();
6181 >                }
6182 >                for (Node<K,V> p; (p = advance()) != null; )
6183 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
6184                  result = r;
6185                  CountedCompleter<?> c;
6186                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6187 +                    @SuppressWarnings("unchecked")
6188                      MapReduceEntriesToIntTask<K,V>
6189                          t = (MapReduceEntriesToIntTask<K,V>)c,
6190                          s = t.rights;
# Line 6655 | Line 6197 | public class ConcurrentHashMap<K, V>
6197          }
6198      }
6199  
6200 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6201 <        extends Traverser<K,V,Integer> {
6200 >    @SuppressWarnings("serial")
6201 >    static final class MapReduceMappingsToIntTask<K,V>
6202 >        extends BulkTask<K,V,Integer> {
6203          final ToIntBiFunction<? super K, ? super V> transformer;
6204          final IntBinaryOperator reducer;
6205          final int basis;
6206          int result;
6207          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6208          MapReduceMappingsToIntTask
6209 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6209 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6210               MapReduceMappingsToIntTask<K,V> nextRight,
6211               ToIntBiFunction<? super K, ? super V> transformer,
6212               int basis,
6213               IntBinaryOperator reducer) {
6214 <            super(m, p, b); this.nextRight = nextRight;
6214 >            super(p, b, i, f, t); this.nextRight = nextRight;
6215              this.transformer = transformer;
6216              this.basis = basis; this.reducer = reducer;
6217          }
6218          public final Integer getRawResult() { return result; }
6219 <        @SuppressWarnings("unchecked") public final void compute() {
6219 >        public final void compute() {
6220              final ToIntBiFunction<? super K, ? super V> transformer;
6221              final IntBinaryOperator reducer;
6222              if ((transformer = this.transformer) != null &&
6223                  (reducer = this.reducer) != null) {
6224                  int r = this.basis;
6225 <                for (int b; (b = preSplit()) > 0;)
6225 >                for (int i = baseIndex, f, h; batch > 0 &&
6226 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6227 >                    addToPendingCount(1);
6228                      (rights = new MapReduceMappingsToIntTask<K,V>
6229 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6230 <                V v;
6231 <                while ((v = advance()) != null)
6232 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey, v));
6229 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6230 >                      rights, transformer, r, reducer)).fork();
6231 >                }
6232 >                for (Node<K,V> p; (p = advance()) != null; )
6233 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6234                  result = r;
6235                  CountedCompleter<?> c;
6236                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6237 +                    @SuppressWarnings("unchecked")
6238                      MapReduceMappingsToIntTask<K,V>
6239                          t = (MapReduceMappingsToIntTask<K,V>)c,
6240                          s = t.rights;
# Line 6704 | Line 6251 | public class ConcurrentHashMap<K, V>
6251      private static final sun.misc.Unsafe U;
6252      private static final long SIZECTL;
6253      private static final long TRANSFERINDEX;
6707    private static final long TRANSFERORIGIN;
6254      private static final long BASECOUNT;
6255      private static final long CELLSBUSY;
6256      private static final long CELLVALUE;
# Line 6719 | Line 6265 | public class ConcurrentHashMap<K, V>
6265                  (k.getDeclaredField("sizeCtl"));
6266              TRANSFERINDEX = U.objectFieldOffset
6267                  (k.getDeclaredField("transferIndex"));
6722            TRANSFERORIGIN = U.objectFieldOffset
6723                (k.getDeclaredField("transferOrigin"));
6268              BASECOUNT = U.objectFieldOffset
6269                  (k.getDeclaredField("baseCount"));
6270              CELLSBUSY = U.objectFieldOffset
6271                  (k.getDeclaredField("cellsBusy"));
6272 <            Class<?> ck = Cell.class;
6272 >            Class<?> ck = CounterCell.class;
6273              CELLVALUE = U.objectFieldOffset
6274                  (ck.getDeclaredField("value"));
6275 <            Class<?> sc = Node[].class;
6276 <            ABASE = U.arrayBaseOffset(sc);
6277 <            int scale = U.arrayIndexScale(sc);
6275 >            Class<?> ak = Node[].class;
6276 >            ABASE = U.arrayBaseOffset(ak);
6277 >            int scale = U.arrayIndexScale(ak);
6278              if ((scale & (scale - 1)) != 0)
6279                  throw new Error("data type scale not a power of two");
6280              ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
# Line 6738 | Line 6282 | public class ConcurrentHashMap<K, V>
6282              throw new Error(e);
6283          }
6284      }
6741
6285   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines