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.165 by jsr166, Fri Jan 18 04:23:28 2013 UTC vs.
Revision 1.299 by jsr166, Sat Mar 18 19:19:04 2017 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;
21 < import java.util.AbstractSet;
22 < import java.util.AbstractCollection;
23 < import java.util.Hashtable;
16 > import java.util.Enumeration;
17   import java.util.HashMap;
18 + import java.util.Hashtable;
19   import java.util.Iterator;
20 < import java.util.Enumeration;
27 < import java.util.ConcurrentModificationException;
20 > import java.util.Map;
21   import java.util.NoSuchElementException;
22 < import java.util.concurrent.ConcurrentMap;
23 < import java.util.concurrent.locks.AbstractQueuedSynchronizer;
31 < import java.util.concurrent.atomic.AtomicInteger;
22 > import java.util.Set;
23 > import java.util.Spliterator;
24   import java.util.concurrent.atomic.AtomicReference;
25 < import java.io.Serializable;
25 > import java.util.concurrent.locks.LockSupport;
26 > import java.util.concurrent.locks.ReentrantLock;
27 > import java.util.function.BiConsumer;
28 > import java.util.function.BiFunction;
29 > import java.util.function.Consumer;
30 > import java.util.function.DoubleBinaryOperator;
31 > import java.util.function.Function;
32 > import java.util.function.IntBinaryOperator;
33 > import java.util.function.LongBinaryOperator;
34 > import java.util.function.Predicate;
35 > import java.util.function.ToDoubleBiFunction;
36 > import java.util.function.ToDoubleFunction;
37 > import java.util.function.ToIntBiFunction;
38 > import java.util.function.ToIntFunction;
39 > import java.util.function.ToLongBiFunction;
40 > import java.util.function.ToLongFunction;
41 > import java.util.stream.Stream;
42 > import jdk.internal.misc.Unsafe;
43  
44   /**
45   * A hash table supporting full concurrency of retrievals and
# Line 53 | Line 62 | import java.io.Serializable;
62   * that key reporting the updated value.)  For aggregate operations
63   * such as {@code putAll} and {@code clear}, concurrent retrievals may
64   * reflect insertion or removal of only some entries.  Similarly,
65 < * Iterators and Enumerations return elements reflecting the state of
66 < * the hash table at some point at or since the creation of the
65 > * Iterators, Spliterators and Enumerations return elements reflecting the
66 > * state of the hash table at some point at or since the creation of the
67   * iterator/enumeration.  They do <em>not</em> throw {@link
68 < * ConcurrentModificationException}.  However, iterators are designed
69 < * to be used by only one thread at a time.  Bear in mind that the
70 < * results of aggregate status methods including {@code size}, {@code
71 < * isEmpty}, and {@code containsValue} are typically useful only when
72 < * a map is not undergoing concurrent updates in other threads.
68 > * java.util.ConcurrentModificationException ConcurrentModificationException}.
69 > * However, iterators are designed to be used by only one thread at a time.
70 > * Bear in mind that the results of aggregate status methods including
71 > * {@code size}, {@code isEmpty}, and {@code containsValue} are typically
72 > * useful only when a map is not undergoing concurrent updates in other threads.
73   * Otherwise the results of these methods reflect transient states
74   * that may be adequate for monitoring or estimation purposes, but not
75   * for program control.
# Line 84 | Line 93 | import java.io.Serializable;
93   * expected {@code concurrencyLevel} as an additional hint for
94   * internal sizing.  Note that using many keys with exactly the same
95   * {@code hashCode()} is a sure way to slow down performance of any
96 < * hash table.
96 > * hash table. To ameliorate impact, when keys are {@link Comparable},
97 > * this class may use comparison order among keys to help break ties.
98   *
99   * <p>A {@link Set} projection of a ConcurrentHashMap may be created
100   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
# Line 92 | Line 102 | import java.io.Serializable;
102   * mapped values are (perhaps transiently) not used or all take the
103   * same mapping value.
104   *
105 < * <p>A ConcurrentHashMap can be used as scalable frequency map (a
105 > * <p>A ConcurrentHashMap can be used as a scalable frequency map (a
106   * form of histogram or multiset) by using {@link
107   * java.util.concurrent.atomic.LongAdder} values and initializing via
108 < * {@link #computeIfAbsent}. For example, to add a count to a {@code
109 < * ConcurrentHashMap<String,LongAdder> freqs}, you can use {@code
110 < * freqs.computeIfAbsent(k -> new LongAdder()).increment();}
108 > * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count
109 > * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
110 > * {@code freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}
111   *
112   * <p>This class and its views and iterators implement all of the
113   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
# Line 106 | Line 116 | import java.io.Serializable;
116   * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
117   * does <em>not</em> allow {@code null} to be used as a key or value.
118   *
119 < * <p>ConcurrentHashMaps support sequential and parallel operations
120 < * bulk operations. (Parallel forms use the {@link
121 < * ForkJoinPool#commonPool()}). Tasks that may be used in other
122 < * contexts are available in class {@link ForkJoinTasks}. These
123 < * operations are designed to be safely, and often sensibly, applied
124 < * even with maps that are being concurrently updated by other
125 < * threads; for example, when computing a snapshot summary of the
126 < * values in a shared registry.  There are three kinds of operation,
127 < * each with four forms, accepting functions with Keys, Values,
128 < * Entries, and (Key, Value) arguments and/or return values. Because
129 < * the elements of a ConcurrentHashMap are not ordered in any
130 < * particular way, and may be processed in different orders in
131 < * different parallel executions, the correctness of supplied
132 < * functions should not depend on any ordering, or on any other
133 < * objects or values that may transiently change while computation is
134 < * in progress; and except for forEach actions, should ideally be
125 < * side-effect-free.
119 > * <p>ConcurrentHashMaps support a set of sequential and parallel bulk
120 > * operations that, unlike most {@link Stream} methods, are designed
121 > * to be safely, and often sensibly, applied even with maps that are
122 > * being concurrently updated by other threads; for example, when
123 > * computing a snapshot summary of the values in a shared registry.
124 > * There are three kinds of operation, each with four forms, accepting
125 > * functions with keys, values, entries, and (key, value) pairs as
126 > * arguments and/or return values. Because the elements of a
127 > * ConcurrentHashMap are not ordered in any particular way, and may be
128 > * processed in different orders in different parallel executions, the
129 > * correctness of supplied functions should not depend on any
130 > * ordering, or on any other objects or values that may transiently
131 > * change while computation is in progress; and except for forEach
132 > * actions, should ideally be side-effect-free. Bulk operations on
133 > * {@link java.util.Map.Entry} objects do not support method {@code
134 > * setValue}.
135   *
136   * <ul>
137 < * <li> forEach: Perform a given action on each element.
137 > * <li>forEach: Performs a given action on each element.
138   * A variant form applies a given transformation on each element
139 < * before performing the action.</li>
139 > * before performing the action.
140   *
141 < * <li> search: Return the first available non-null result of
141 > * <li>search: Returns the first available non-null result of
142   * applying a given function on each element; skipping further
143 < * search when a result is found.</li>
143 > * search when a result is found.
144   *
145 < * <li> reduce: Accumulate each element.  The supplied reduction
145 > * <li>reduce: Accumulates each element.  The supplied reduction
146   * function cannot rely on ordering (more formally, it should be
147   * both associative and commutative).  There are five variants:
148   *
149   * <ul>
150   *
151 < * <li> Plain reductions. (There is not a form of this method for
151 > * <li>Plain reductions. (There is not a form of this method for
152   * (key, value) function arguments since there is no corresponding
153 < * return type.)</li>
153 > * return type.)
154   *
155 < * <li> Mapped reductions that accumulate the results of a given
156 < * function applied to each element.</li>
155 > * <li>Mapped reductions that accumulate the results of a given
156 > * function applied to each element.
157   *
158 < * <li> Reductions to scalar doubles, longs, and ints, using a
159 < * given basis value.</li>
158 > * <li>Reductions to scalar doubles, longs, and ints, using a
159 > * given basis value.
160   *
152 * </li>
161   * </ul>
162   * </ul>
163   *
164 + * <p>These bulk operations accept a {@code parallelismThreshold}
165 + * argument. Methods proceed sequentially if the current map size is
166 + * estimated to be less than the given threshold. Using a value of
167 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
168 + * of {@code 1} results in maximal parallelism by partitioning into
169 + * enough subtasks to fully utilize the {@link
170 + * ForkJoinPool#commonPool()} that is used for all parallel
171 + * computations. Normally, you would initially choose one of these
172 + * extreme values, and then measure performance of using in-between
173 + * values that trade off overhead versus throughput.
174 + *
175   * <p>The concurrency properties of bulk operations follow
176   * from those of ConcurrentHashMap: Any non-null result returned
177   * from {@code get(key)} and related access methods bears a
# Line 214 | Line 233 | import java.io.Serializable;
233   * @param <K> the type of keys maintained by this map
234   * @param <V> the type of mapped values
235   */
236 < public class ConcurrentHashMap<K, V>
237 <    implements ConcurrentMap<K, V>, Serializable {
236 > public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
237 >    implements ConcurrentMap<K,V>, Serializable {
238      private static final long serialVersionUID = 7249069246763182397L;
239  
240      /*
# Line 228 | Line 247 | public class ConcurrentHashMap<K, V>
247       * the same or better than java.util.HashMap, and to support high
248       * initial insertion rates on an empty table by many threads.
249       *
250 <     * Each key-value mapping is held in a Node.  Because Node key
251 <     * fields can contain special values, they are defined using plain
252 <     * Object types (not type "K"). This leads to a lot of explicit
253 <     * casting (and many explicit warning suppressions to tell
254 <     * compilers not to complain about it). It also allows some of the
255 <     * public methods to be factored into a smaller number of internal
256 <     * methods (although sadly not so for the five variants of
257 <     * put-related operations). The validation-based approach
258 <     * explained below leads to a lot of code sprawl because
259 <     * retry-control precludes factoring into smaller methods.
250 >     * This map usually acts as a binned (bucketed) hash table.  Each
251 >     * key-value mapping is held in a Node.  Most nodes are instances
252 >     * of the basic Node class with hash, key, value, and next
253 >     * fields. However, various subclasses exist: TreeNodes are
254 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
255 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
256 >     * of bins during resizing. ReservationNodes are used as
257 >     * placeholders while establishing values in computeIfAbsent and
258 >     * related methods.  The types TreeBin, ForwardingNode, and
259 >     * ReservationNode do not hold normal user keys, values, or
260 >     * hashes, and are readily distinguishable during search etc
261 >     * because they have negative hash fields and null key and value
262 >     * fields. (These special nodes are either uncommon or transient,
263 >     * so the impact of carrying around some unused fields is
264 >     * insignificant.)
265       *
266       * The table is lazily initialized to a power-of-two size upon the
267       * first insertion.  Each bin in the table normally contains a
# Line 245 | Line 269 | public class ConcurrentHashMap<K, V>
269       * Table accesses require volatile/atomic reads, writes, and
270       * CASes.  Because there is no other way to arrange this without
271       * adding further indirections, we use intrinsics
272 <     * (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.
272 >     * (jdk.internal.misc.Unsafe) operations.
273       *
274       * We use the top (sign) bit of Node hash fields for control
275       * purposes -- it is available anyway because of addressing
276 <     * constraints.  Nodes with negative hash fields are forwarding
277 <     * 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.
276 >     * constraints.  Nodes with negative hash fields are specially
277 >     * handled or ignored in map methods.
278       *
279       * Insertion (via put or its variants) of the first node in an
280       * empty bin is performed by just CASing it to the bin.  This is
# Line 272 | Line 291 | public class ConcurrentHashMap<K, V>
291       * validate that it is still the first node after locking it, and
292       * retry if not. Because new nodes are always appended to lists,
293       * once a node is first in a bin, it remains first until deleted
294 <     * 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.
294 >     * or the bin becomes invalidated (upon resizing).
295       *
296       * The main disadvantage of per-bin locks is that other update
297       * operations on other nodes in a bin list protected by the same
# Line 308 | Line 324 | public class ConcurrentHashMap<K, V>
324       * sometimes deviate significantly from uniform randomness.  This
325       * includes the case when N > (1<<30), so some keys MUST collide.
326       * Similarly for dumb or hostile usages in which multiple keys are
327 <     * designed to have identical hash codes. Also, although we guard
328 <     * against the worst effects of this (see method spread), sets of
329 <     * hashes may differ only in bits that do not impact their bin
330 <     * index for a given power-of-two mask.  So we use a secondary
331 <     * strategy that applies when the number of nodes in a bin exceeds
332 <     * 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
327 >     * designed to have identical hash codes or ones that differs only
328 >     * in masked-out high bits. So we use a secondary strategy that
329 >     * applies when the number of nodes in a bin exceeds a
330 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
331 >     * specialized form of red-black trees), bounding search time to
332 >     * O(log N).  Each search step in a TreeBin is at least twice as
333       * slow as in a regular list, but given that N cannot exceed
334       * (1<<64) (before running out of addresses) this bounds search
335       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 329 | Line 342 | public class ConcurrentHashMap<K, V>
342       * The table is resized when occupancy exceeds a percentage
343       * threshold (nominally, 0.75, but see below).  Any thread
344       * noticing an overfull bin may assist in resizing after the
345 <     * initiating thread allocates and sets up the replacement
346 <     * array. However, rather than stalling, these other threads may
347 <     * proceed with insertions etc.  The use of TreeBins shields us
348 <     * from the worst case effects of overfilling while resizes are in
345 >     * initiating thread allocates and sets up the replacement array.
346 >     * However, rather than stalling, these other threads may proceed
347 >     * with insertions etc.  The use of TreeBins shields us from the
348 >     * worst case effects of overfilling while resizes are in
349       * progress.  Resizing proceeds by transferring bins, one by one,
350 <     * from the table to the next table. To enable concurrency, the
351 <     * next table must be (incrementally) prefilled with place-holders
352 <     * serving as reverse forwarders to the old table.  Because we are
350 >     * from the table to the next table. However, threads claim small
351 >     * blocks of indices to transfer (via field transferIndex) before
352 >     * doing so, reducing contention.  A generation stamp in field
353 >     * sizeCtl ensures that resizings do not overlap. Because we are
354       * using power-of-two expansion, the elements from each bin must
355       * either stay at same index, or move with a power of two
356       * offset. We eliminate unnecessary node creation by catching
# Line 357 | Line 371 | public class ConcurrentHashMap<K, V>
371       * locks, average aggregate waits become shorter as resizing
372       * progresses.  The transfer operation must also ensure that all
373       * accessible bins in both the old and new table are usable by any
374 <     * traversal.  This is arranged by proceeding from the last bin
375 <     * (table.length - 1) up towards the first.  Upon seeing a
376 <     * forwarding node, traversals (see class Traverser) arrange to
377 <     * move to the new table without revisiting nodes.  However, to
378 <     * ensure that no intervening nodes are skipped, bin splitting can
379 <     * only begin after the associated reverse-forwarders are in
380 <     * place.
374 >     * traversal.  This is arranged in part by proceeding from the
375 >     * last bin (table.length - 1) up towards the first.  Upon seeing
376 >     * a forwarding node, traversals (see class Traverser) arrange to
377 >     * move to the new table without revisiting nodes.  To ensure that
378 >     * no intervening nodes are skipped even when moved out of order,
379 >     * a stack (see class TableStack) is created on first encounter of
380 >     * a forwarding node during a traversal, to maintain its place if
381 >     * later processing the current table. The need for these
382 >     * save/restore mechanics is relatively rare, but when one
383 >     * forwarding node is encountered, typically many more will be.
384 >     * So Traversers use a simple caching scheme to avoid creating so
385 >     * many new TableStack nodes. (Thanks to Peter Levart for
386 >     * suggesting use of a stack here.)
387       *
388       * The traversal scheme also applies to partial traversals of
389       * ranges of bins (via an alternate Traverser constructor)
# Line 382 | Line 402 | public class ConcurrentHashMap<K, V>
402       * LongAdder. We need to incorporate a specialization rather than
403       * just use a LongAdder in order to access implicit
404       * contention-sensing that leads to creation of multiple
405 <     * Cells.  The counter mechanics avoid contention on
405 >     * CounterCells.  The counter mechanics avoid contention on
406       * updates but can encounter cache thrashing if read too
407       * frequently during concurrent access. To avoid reading so often,
408       * resizing under contention is attempted only upon adding to a
409       * bin already holding two or more nodes. Under uniform hash
410       * distributions, the probability of this occurring at threshold
411       * is around 13%, meaning that only about 1 in 8 puts check
412 <     * threshold (and after resizing, many fewer do so). The bulk
413 <     * putAll operation further reduces contention by only committing
414 <     * count updates upon these size checks.
412 >     * threshold (and after resizing, many fewer do so).
413 >     *
414 >     * TreeBins use a special form of comparison for search and
415 >     * related operations (which is the main reason we cannot use
416 >     * existing collections such as TreeMaps). TreeBins contain
417 >     * Comparable elements, but may contain others, as well as
418 >     * elements that are Comparable but not necessarily Comparable for
419 >     * the same T, so we cannot invoke compareTo among them. To handle
420 >     * this, the tree is ordered primarily by hash value, then by
421 >     * Comparable.compareTo order if applicable.  On lookup at a node,
422 >     * if elements are not comparable or compare as 0 then both left
423 >     * and right children may need to be searched in the case of tied
424 >     * hash values. (This corresponds to the full list search that
425 >     * would be necessary if all elements were non-Comparable and had
426 >     * tied hashes.) On insertion, to keep a total ordering (or as
427 >     * close as is required here) across rebalancings, we compare
428 >     * classes and identityHashCodes as tie-breakers. The red-black
429 >     * balancing code is updated from pre-jdk-collections
430 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
431 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
432 >     * Algorithms" (CLR).
433 >     *
434 >     * TreeBins also require an additional locking mechanism.  While
435 >     * list traversal is always possible by readers even during
436 >     * updates, tree traversal is not, mainly because of tree-rotations
437 >     * that may change the root node and/or its linkages.  TreeBins
438 >     * include a simple read-write lock mechanism parasitic on the
439 >     * main bin-synchronization strategy: Structural adjustments
440 >     * associated with an insertion or removal are already bin-locked
441 >     * (and so cannot conflict with other writers) but must wait for
442 >     * ongoing readers to finish. Since there can be only one such
443 >     * waiter, we use a simple scheme using a single "waiter" field to
444 >     * block writers.  However, readers need never block.  If the root
445 >     * lock is held, they proceed along the slow traversal path (via
446 >     * next-pointers) until the lock becomes available or the list is
447 >     * exhausted, whichever comes first. These cases are not fast, but
448 >     * maximize aggregate expected throughput.
449       *
450       * Maintaining API and serialization compatibility with previous
451       * versions of this class introduces several oddities. Mainly: We
452 <     * leave untouched but unused constructor arguments refering to
452 >     * leave untouched but unused constructor arguments referring to
453       * concurrencyLevel. We accept a loadFactor constructor argument,
454       * but apply it only to initial table capacity (which is the only
455       * time that we can guarantee to honor it.) We also declare an
456       * unused "Segment" class that is instantiated in minimal form
457       * only when serializing.
458 +     *
459 +     * Also, solely for compatibility with previous versions of this
460 +     * class, it extends AbstractMap, even though all of its methods
461 +     * are overridden, so it is just useless baggage.
462 +     *
463 +     * This file is organized to make things a little easier to follow
464 +     * while reading than they might otherwise: First the main static
465 +     * declarations and utilities, then fields, then main public
466 +     * methods (with a few factorings of multiple public methods into
467 +     * internal ones), then sizing methods, trees, traversers, and
468 +     * bulk operations.
469       */
470  
471      /* ---------------- Constants -------------- */
# Line 443 | Line 508 | public class ConcurrentHashMap<K, V>
508  
509      /**
510       * The bin count threshold for using a tree rather than list for a
511 <     * bin.  The value reflects the approximate break-even point for
512 <     * using tree-based operations.
511 >     * bin.  Bins are converted to trees when adding an element to a
512 >     * bin with at least this many nodes. The value must be greater
513 >     * than 2, and should be at least 8 to mesh with assumptions in
514 >     * tree removal about conversion back to plain bins upon
515 >     * shrinkage.
516 >     */
517 >    static final int TREEIFY_THRESHOLD = 8;
518 >
519 >    /**
520 >     * The bin count threshold for untreeifying a (split) bin during a
521 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
522 >     * most 6 to mesh with shrinkage detection under removal.
523 >     */
524 >    static final int UNTREEIFY_THRESHOLD = 6;
525 >
526 >    /**
527 >     * The smallest table capacity for which bins may be treeified.
528 >     * (Otherwise the table is resized if too many nodes in a bin.)
529 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
530 >     * conflicts between resizing and treeification thresholds.
531       */
532 <    private static final int TREE_THRESHOLD = 8;
532 >    static final int MIN_TREEIFY_CAPACITY = 64;
533  
534      /**
535       * Minimum number of rebinnings per transfer step. Ranges are
# Line 457 | Line 540 | public class ConcurrentHashMap<K, V>
540       */
541      private static final int MIN_TRANSFER_STRIDE = 16;
542  
543 +    /**
544 +     * The number of bits used for generation stamp in sizeCtl.
545 +     * Must be at least 6 for 32bit arrays.
546 +     */
547 +    private static final int RESIZE_STAMP_BITS = 16;
548 +
549 +    /**
550 +     * The maximum number of threads that can help resize.
551 +     * Must fit in 32 - RESIZE_STAMP_BITS bits.
552 +     */
553 +    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
554 +
555 +    /**
556 +     * The bit shift for recording size stamp in sizeCtl.
557 +     */
558 +    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
559 +
560      /*
561       * Encodings for Node hash fields. See above for explanation.
562       */
563 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
563 >    static final int MOVED     = -1; // hash for forwarding nodes
564 >    static final int TREEBIN   = -2; // hash for roots of trees
565 >    static final int RESERVED  = -3; // hash for transient reservations
566      static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
567  
568      /** Number of CPUS, to place bounds on some sizings */
569      static final int NCPU = Runtime.getRuntime().availableProcessors();
570  
571 <    /* ---------------- Counters -------------- */
571 >    /**
572 >     * Serialized pseudo-fields, provided only for jdk7 compatibility.
573 >     * @serialField segments Segment[]
574 >     *   The segments, each of which is a specialized hash table.
575 >     * @serialField segmentMask int
576 >     *   Mask value for indexing into segments. The upper bits of a
577 >     *   key's hash code are used to choose the segment.
578 >     * @serialField segmentShift int
579 >     *   Shift value for indexing within segments.
580 >     */
581 >    private static final ObjectStreamField[] serialPersistentFields = {
582 >        new ObjectStreamField("segments", Segment[].class),
583 >        new ObjectStreamField("segmentMask", Integer.TYPE),
584 >        new ObjectStreamField("segmentShift", Integer.TYPE),
585 >    };
586 >
587 >    /* ---------------- Nodes -------------- */
588  
589 <    // Adapted from LongAdder and Striped64.
590 <    // See their internal docs for explanation.
589 >    /**
590 >     * Key-value entry.  This class is never exported out as a
591 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
592 >     * MapEntry below), but can be used for read-only traversals used
593 >     * in bulk tasks.  Subclasses of Node with a negative hash field
594 >     * are special, and contain null keys and values (but are never
595 >     * exported).  Otherwise, keys and vals are never null.
596 >     */
597 >    static class Node<K,V> implements Map.Entry<K,V> {
598 >        final int hash;
599 >        final K key;
600 >        volatile V val;
601 >        volatile Node<K,V> next;
602  
603 <    // A padded cell for distributing counts
604 <    static final class Cell {
605 <        volatile long p0, p1, p2, p3, p4, p5, p6;
606 <        volatile long value;
607 <        volatile long q0, q1, q2, q3, q4, q5, q6;
608 <        Cell(long x) { value = x; }
603 >        Node(int hash, K key, V val) {
604 >            this.hash = hash;
605 >            this.key = key;
606 >            this.val = val;
607 >        }
608 >
609 >        Node(int hash, K key, V val, Node<K,V> next) {
610 >            this(hash, key, val);
611 >            this.next = next;
612 >        }
613 >
614 >        public final K getKey()     { return key; }
615 >        public final V getValue()   { return val; }
616 >        public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
617 >        public final String toString() {
618 >            return Helpers.mapEntryToString(key, val);
619 >        }
620 >        public final V setValue(V value) {
621 >            throw new UnsupportedOperationException();
622 >        }
623 >
624 >        public final boolean equals(Object o) {
625 >            Object k, v, u; Map.Entry<?,?> e;
626 >            return ((o instanceof Map.Entry) &&
627 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
628 >                    (v = e.getValue()) != null &&
629 >                    (k == key || k.equals(key)) &&
630 >                    (v == (u = val) || v.equals(u)));
631 >        }
632 >
633 >        /**
634 >         * Virtualized support for map.get(); overridden in subclasses.
635 >         */
636 >        Node<K,V> find(int h, Object k) {
637 >            Node<K,V> e = this;
638 >            if (k != null) {
639 >                do {
640 >                    K ek;
641 >                    if (e.hash == h &&
642 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
643 >                        return e;
644 >                } while ((e = e.next) != null);
645 >            }
646 >            return null;
647 >        }
648 >    }
649 >
650 >    /* ---------------- Static utilities -------------- */
651 >
652 >    /**
653 >     * Spreads (XORs) higher bits of hash to lower and also forces top
654 >     * bit to 0. Because the table uses power-of-two masking, sets of
655 >     * hashes that vary only in bits above the current mask will
656 >     * always collide. (Among known examples are sets of Float keys
657 >     * holding consecutive whole numbers in small tables.)  So we
658 >     * apply a transform that spreads the impact of higher bits
659 >     * downward. There is a tradeoff between speed, utility, and
660 >     * quality of bit-spreading. Because many common sets of hashes
661 >     * are already reasonably distributed (so don't benefit from
662 >     * spreading), and because we use trees to handle large sets of
663 >     * collisions in bins, we just XOR some shifted bits in the
664 >     * cheapest possible way to reduce systematic lossage, as well as
665 >     * to incorporate impact of the highest bits that would otherwise
666 >     * never be used in index calculations because of table bounds.
667 >     */
668 >    static final int spread(int h) {
669 >        return (h ^ (h >>> 16)) & HASH_BITS;
670 >    }
671 >
672 >    /**
673 >     * Returns a power of two table size for the given desired capacity.
674 >     * See Hackers Delight, sec 3.2
675 >     */
676 >    private static final int tableSizeFor(int c) {
677 >        int n = c - 1;
678 >        n |= n >>> 1;
679 >        n |= n >>> 2;
680 >        n |= n >>> 4;
681 >        n |= n >>> 8;
682 >        n |= n >>> 16;
683 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
684 >    }
685 >
686 >    /**
687 >     * Returns x's Class if it is of the form "class C implements
688 >     * Comparable<C>", else null.
689 >     */
690 >    static Class<?> comparableClassFor(Object x) {
691 >        if (x instanceof Comparable) {
692 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
693 >            if ((c = x.getClass()) == String.class) // bypass checks
694 >                return c;
695 >            if ((ts = c.getGenericInterfaces()) != null) {
696 >                for (int i = 0; i < ts.length; ++i) {
697 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
698 >                        ((p = (ParameterizedType)t).getRawType() ==
699 >                         Comparable.class) &&
700 >                        (as = p.getActualTypeArguments()) != null &&
701 >                        as.length == 1 && as[0] == c) // type arg is c
702 >                        return c;
703 >                }
704 >            }
705 >        }
706 >        return null;
707 >    }
708 >
709 >    /**
710 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
711 >     * class), else 0.
712 >     */
713 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
714 >    static int compareComparables(Class<?> kc, Object k, Object x) {
715 >        return (x == null || x.getClass() != kc ? 0 :
716 >                ((Comparable)k).compareTo(x));
717 >    }
718 >
719 >    /* ---------------- Table element access -------------- */
720 >
721 >    /*
722 >     * Atomic access methods are used for table elements as well as
723 >     * elements of in-progress next table while resizing.  All uses of
724 >     * the tab arguments must be null checked by callers.  All callers
725 >     * also paranoically precheck that tab's length is not zero (or an
726 >     * equivalent check), thus ensuring that any index argument taking
727 >     * the form of a hash value anded with (length - 1) is a valid
728 >     * index.  Note that, to be correct wrt arbitrary concurrency
729 >     * errors by users, these checks must operate on local variables,
730 >     * which accounts for some odd-looking inline assignments below.
731 >     * Note that calls to setTabAt always occur within locked regions,
732 >     * and so require only release ordering.
733 >     */
734 >
735 >    @SuppressWarnings("unchecked")
736 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
737 >        return (Node<K,V>)U.getObjectAcquire(tab, ((long)i << ASHIFT) + ABASE);
738 >    }
739 >
740 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
741 >                                        Node<K,V> c, Node<K,V> v) {
742 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
743 >    }
744 >
745 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
746 >        U.putObjectRelease(tab, ((long)i << ASHIFT) + ABASE, v);
747      }
748  
749      /* ---------------- Fields -------------- */
# Line 485 | Line 752 | public class ConcurrentHashMap<K, V>
752       * The array of bins. Lazily initialized upon first insertion.
753       * Size is always a power of two. Accessed directly by iterators.
754       */
755 <    transient volatile Node<V>[] table;
755 >    transient volatile Node<K,V>[] table;
756  
757      /**
758       * The next table to use; non-null only while resizing.
759       */
760 <    private transient volatile Node<V>[] nextTable;
760 >    private transient volatile Node<K,V>[] nextTable;
761  
762      /**
763       * Base counter value, used mainly when there is no contention,
# Line 515 | Line 782 | public class ConcurrentHashMap<K, V>
782      private transient volatile int transferIndex;
783  
784      /**
785 <     * 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.
785 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
786       */
787      private transient volatile int cellsBusy;
788  
789      /**
790       * Table of counter cells. When non-null, size is a power of 2.
791       */
792 <    private transient volatile Cell[] counterCells;
792 >    private transient volatile CounterCell[] counterCells;
793  
794      // views
795      private transient KeySetView<K,V> keySet;
796      private transient ValuesView<K,V> values;
797      private transient EntrySetView<K,V> entrySet;
798  
537    /** For serialization compatibility. Null unless serialized; see below */
538    private Segment<K,V>[] segments;
799  
800 <    /* ---------------- Table element access -------------- */
800 >    /* ---------------- Public operations -------------- */
801  
802 <    /*
803 <     * Volatile access methods are used for table elements as well as
804 <     * elements of in-progress next table while resizing.  Uses are
805 <     * null checked by callers, and implicitly bounds-checked, relying
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);
802 >    /**
803 >     * Creates a new, empty map with the default initial table size (16).
804 >     */
805 >    public ConcurrentHashMap() {
806      }
807  
808 <    private static final <V> boolean casTabAt
809 <        (Node<V>[] tab, int i, Node<V> c, Node<V> v) {
810 <        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
808 >    /**
809 >     * Creates a new, empty map with an initial table size
810 >     * accommodating the specified number of elements without the need
811 >     * to dynamically resize.
812 >     *
813 >     * @param initialCapacity The implementation performs internal
814 >     * sizing to accommodate this many elements.
815 >     * @throws IllegalArgumentException if the initial capacity of
816 >     * elements is negative
817 >     */
818 >    public ConcurrentHashMap(int initialCapacity) {
819 >        if (initialCapacity < 0)
820 >            throw new IllegalArgumentException();
821 >        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
822 >                   MAXIMUM_CAPACITY :
823 >                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
824 >        this.sizeCtl = cap;
825      }
826  
827 <    private static final <V> void setTabAt
828 <        (Node<V>[] tab, int i, Node<V> v) {
829 <        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
827 >    /**
828 >     * Creates a new map with the same mappings as the given map.
829 >     *
830 >     * @param m the map
831 >     */
832 >    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
833 >        this.sizeCtl = DEFAULT_CAPACITY;
834 >        putAll(m);
835      }
836  
569    /* ---------------- Nodes -------------- */
570
837      /**
838 <     * Key-value entry. Note that this is never exported out as a
839 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
840 <     * field of MOVED are special, and do not contain user keys or
841 <     * values.  Otherwise, keys are never null, and null val fields
842 <     * indicate that a node is in the process of being deleted or
843 <     * created. For purposes of read-only access, a key may be read
844 <     * before a val, but can only be used after checking val to be
845 <     * non-null.
838 >     * Creates a new, empty map with an initial table size based on
839 >     * the given number of elements ({@code initialCapacity}) and
840 >     * initial table density ({@code loadFactor}).
841 >     *
842 >     * @param initialCapacity the initial capacity. The implementation
843 >     * performs internal sizing to accommodate this many elements,
844 >     * given the specified load factor.
845 >     * @param loadFactor the load factor (table density) for
846 >     * establishing the initial table size
847 >     * @throws IllegalArgumentException if the initial capacity of
848 >     * elements is negative or the load factor is nonpositive
849 >     *
850 >     * @since 1.6
851       */
852 <    static class Node<V> {
853 <        final int hash;
854 <        final Object key;
584 <        volatile V val;
585 <        volatile Node<V> next;
852 >    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
853 >        this(initialCapacity, loadFactor, 1);
854 >    }
855  
856 <        Node(int hash, Object key, V val, Node<V> next) {
857 <            this.hash = hash;
858 <            this.key = key;
859 <            this.val = val;
860 <            this.next = next;
861 <        }
856 >    /**
857 >     * Creates a new, empty map with an initial table size based on
858 >     * the given number of elements ({@code initialCapacity}), table
859 >     * density ({@code loadFactor}), and number of concurrently
860 >     * updating threads ({@code concurrencyLevel}).
861 >     *
862 >     * @param initialCapacity the initial capacity. The implementation
863 >     * performs internal sizing to accommodate this many elements,
864 >     * given the specified load factor.
865 >     * @param loadFactor the load factor (table density) for
866 >     * establishing the initial table size
867 >     * @param concurrencyLevel the estimated number of concurrently
868 >     * updating threads. The implementation may use this value as
869 >     * a sizing hint.
870 >     * @throws IllegalArgumentException if the initial capacity is
871 >     * negative or the load factor or concurrencyLevel are
872 >     * nonpositive
873 >     */
874 >    public ConcurrentHashMap(int initialCapacity,
875 >                             float loadFactor, int concurrencyLevel) {
876 >        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
877 >            throw new IllegalArgumentException();
878 >        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
879 >            initialCapacity = concurrencyLevel;   // as estimated threads
880 >        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
881 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
882 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
883 >        this.sizeCtl = cap;
884      }
885  
886 <    /* ---------------- TreeBins -------------- */
886 >    // Original (since JDK1.2) Map methods
887  
888      /**
889 <     * Nodes for use in TreeBins
889 >     * {@inheritDoc}
890       */
891 <    static final class TreeNode<V> extends Node<V> {
892 <        TreeNode<V> parent;  // red-black tree links
893 <        TreeNode<V> left;
894 <        TreeNode<V> right;
895 <        TreeNode<V> prev;    // needed to unlink next upon deletion
896 <        boolean red;
891 >    public int size() {
892 >        long n = sumCount();
893 >        return ((n < 0L) ? 0 :
894 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
895 >                (int)n);
896 >    }
897  
898 <        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
899 <            super(hash, key, val, next);
900 <            this.parent = parent;
901 <        }
898 >    /**
899 >     * {@inheritDoc}
900 >     */
901 >    public boolean isEmpty() {
902 >        return sumCount() <= 0L; // ignore transient negative values
903      }
904  
905      /**
906 <     * A specialized form of red-black tree for use in bins
907 <     * whose size exceeds a threshold.
906 >     * Returns the value to which the specified key is mapped,
907 >     * or {@code null} if this map contains no mapping for the key.
908       *
909 <     * TreeBins use a special form of comparison for search and
910 <     * related operations (which is the main reason we cannot use
911 <     * existing collections such as TreeMaps). TreeBins contain
912 <     * Comparable elements, but may contain others, as well as
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).
909 >     * <p>More formally, if this map contains a mapping from a key
910 >     * {@code k} to a value {@code v} such that {@code key.equals(k)},
911 >     * then this method returns {@code v}; otherwise it returns
912 >     * {@code null}.  (There can be at most one such mapping.)
913       *
914 <     * TreeBins also maintain a separate locking discipline than
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.
914 >     * @throws NullPointerException if the specified key is null
915       */
916 <    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
917 <        private static final long serialVersionUID = 2249069246763182397L;
918 <        transient TreeNode<V> root;  // root of tree
919 <        transient TreeNode<V> first; // head of next-pointer list
920 <
921 <        /* AQS overrides */
922 <        public final boolean isHeldExclusively() { return getState() > 0; }
923 <        public final boolean tryAcquire(int ignore) {
924 <            if (compareAndSetState(0, 1)) {
925 <                setExclusiveOwnerThread(Thread.currentThread());
926 <                return true;
927 <            }
928 <            return false;
929 <        }
930 <        public final boolean tryRelease(int ignore) {
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;
916 >    public V get(Object key) {
917 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
918 >        int h = spread(key.hashCode());
919 >        if ((tab = table) != null && (n = tab.length) > 0 &&
920 >            (e = tabAt(tab, (n - 1) & h)) != null) {
921 >            if ((eh = e.hash) == h) {
922 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
923 >                    return e.val;
924 >            }
925 >            else if (eh < 0)
926 >                return (p = e.find(h, key)) != null ? p.val : null;
927 >            while ((e = e.next) != null) {
928 >                if (e.hash == h &&
929 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
930 >                    return e.val;
931              }
932          }
933 +        return null;
934 +    }
935  
936 <        /**
937 <         * Returns the TreeNode (or null if not found) for the given key
938 <         * starting at given root.
939 <         */
940 <        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
941 <            (int h, Object k, TreeNode<V> p) {
942 <            Class<?> c = k.getClass();
943 <            while (p != null) {
944 <                int dir, ph;  Object pk; Class<?> pc;
945 <                if ((ph = p.hash) == h) {
946 <                    if ((pk = p.key) == k || k.equals(pk))
947 <                        return p;
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 <        }
936 >    /**
937 >     * Tests if the specified object is a key in this table.
938 >     *
939 >     * @param  key possible key
940 >     * @return {@code true} if and only if the specified object
941 >     *         is a key in this table, as determined by the
942 >     *         {@code equals} method; {@code false} otherwise
943 >     * @throws NullPointerException if the specified key is null
944 >     */
945 >    public boolean containsKey(Object key) {
946 >        return get(key) != null;
947 >    }
948  
949 <        /**
950 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
951 <         * read-lock to call getTreeNode, but during failure to get
952 <         * lock, searches along next links.
953 <         */
954 <        final V getValue(int h, Object k) {
955 <            Node<V> r = null;
956 <            int c = getState(); // Must read lock state first
957 <            for (Node<V> e = first; e != null; e = e.next) {
958 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
959 <                    try {
960 <                        r = getTreeNode(h, k, root);
961 <                    } finally {
962 <                        releaseShared(0);
963 <                    }
964 <                    break;
965 <                }
966 <                else if (e.hash == h && k.equals(e.key)) {
967 <                    r = e;
968 <                    break;
778 <                }
779 <                else
780 <                    c = getState();
949 >    /**
950 >     * Returns {@code true} if this map maps one or more keys to the
951 >     * specified value. Note: This method may require a full traversal
952 >     * of the map, and is much slower than method {@code containsKey}.
953 >     *
954 >     * @param value value whose presence in this map is to be tested
955 >     * @return {@code true} if this map maps one or more keys to the
956 >     *         specified value
957 >     * @throws NullPointerException if the specified value is null
958 >     */
959 >    public boolean containsValue(Object value) {
960 >        if (value == null)
961 >            throw new NullPointerException();
962 >        Node<K,V>[] t;
963 >        if ((t = table) != null) {
964 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
965 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
966 >                V v;
967 >                if ((v = p.val) == value || (v != null && value.equals(v)))
968 >                    return true;
969              }
782            return r == null ? null : r.val;
970          }
971 +        return false;
972 +    }
973  
974 <        /**
975 <         * Finds or adds a node.
976 <         * @return null if added
977 <         */
978 <        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
979 <            (int h, Object k, V v) {
980 <            Class<?> c = k.getClass();
981 <            TreeNode<V> pp = root, p = null;
982 <            int dir = 0;
983 <            while (pp != null) { // find existing node or leaf to insert at
984 <                int ph;  Object pk; Class<?> pc;
985 <                p = pp;
986 <                if ((ph = p.hash) == h) {
987 <                    if ((pk = p.key) == k || k.equals(pk))
988 <                        return p;
989 <                    if (c != (pc = pk.getClass()) ||
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 <        }
974 >    /**
975 >     * Maps the specified key to the specified value in this table.
976 >     * Neither the key nor the value can be null.
977 >     *
978 >     * <p>The value can be retrieved by calling the {@code get} method
979 >     * with a key that is equal to the original key.
980 >     *
981 >     * @param key key with which the specified value is to be associated
982 >     * @param value value to be associated with the specified key
983 >     * @return the previous value associated with {@code key}, or
984 >     *         {@code null} if there was no mapping for {@code key}
985 >     * @throws NullPointerException if the specified key or value is null
986 >     */
987 >    public V put(K key, V value) {
988 >        return putVal(key, value, false);
989 >    }
990  
991 <        /**
992 <         * Removes the given node, that must be present before this
993 <         * call.  This is messier than typical red-black deletion code
994 <         * because we cannot swap the contents of an interior node
995 <         * with a leaf successor that is pinned by "next" pointers
996 <         * that are accessible independently of lock. So instead we
997 <         * swap the tree linkages.
998 <         */
999 <        final void deleteTreeNode(TreeNode<V> p) {
1000 <            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
1001 <            TreeNode<V> pred = p.prev;
1002 <            if (pred == null)
903 <                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;
991 >    /** Implementation for put and putIfAbsent */
992 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
993 >        if (key == null || value == null) throw new NullPointerException();
994 >        int hash = spread(key.hashCode());
995 >        int binCount = 0;
996 >        for (Node<K,V>[] tab = table;;) {
997 >            Node<K,V> f; int n, i, fh; K fk; V fv;
998 >            if (tab == null || (n = tab.length) == 0)
999 >                tab = initTable();
1000 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
1001 >                if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value)))
1002 >                    break;                   // no lock when adding to empty bin
1003              }
1004 +            else if ((fh = f.hash) == MOVED)
1005 +                tab = helpTransfer(tab, f);
1006 +            else if (onlyIfAbsent // check first node without acquiring lock
1007 +                     && fh == hash
1008 +                     && ((fk = f.key) == key || (fk != null && key.equals(fk)))
1009 +                     && (fv = f.val) != null)
1010 +                return fv;
1011              else {
1012 <                replacement.parent = pp;
1013 <                if (pp == null)
1014 <                    root = replacement;
1015 <                else if (p == pp.left)
1016 <                    pp.left = replacement;
1017 <                else
1018 <                    pp.right = replacement;
1019 <                p.left = p.right = p.parent = null;
1020 <            }
1021 <            if (!p.red) { // rebalance, from CLR
1022 <                TreeNode<V> x = replacement;
1023 <                while (x != null) {
1024 <                    TreeNode<V> xp, xpl;
1025 <                    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;
1012 >                V oldVal = null;
1013 >                synchronized (f) {
1014 >                    if (tabAt(tab, i) == f) {
1015 >                        if (fh >= 0) {
1016 >                            binCount = 1;
1017 >                            for (Node<K,V> e = f;; ++binCount) {
1018 >                                K ek;
1019 >                                if (e.hash == hash &&
1020 >                                    ((ek = e.key) == key ||
1021 >                                     (ek != null && key.equals(ek)))) {
1022 >                                    oldVal = e.val;
1023 >                                    if (!onlyIfAbsent)
1024 >                                        e.val = value;
1025 >                                    break;
1026                                  }
1027 <                                if (xp != null) {
1028 <                                    xp.red = false;
1029 <                                    rotateLeft(xp);
1027 >                                Node<K,V> pred = e;
1028 >                                if ((e = e.next) == null) {
1029 >                                    pred.next = new Node<K,V>(hash, key, value);
1030 >                                    break;
1031                                  }
1009                                x = root;
1032                              }
1033                          }
1034 <                    }
1035 <                    else { // symmetric
1036 <                        TreeNode<V> sib = xpl;
1037 <                        if (sib != null && sib.red) {
1038 <                            sib.red = false;
1039 <                            xp.red = true;
1040 <                            rotateRight(xp);
1041 <                            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;
1034 >                        else if (f instanceof TreeBin) {
1035 >                            Node<K,V> p;
1036 >                            binCount = 2;
1037 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1038 >                                                           value)) != null) {
1039 >                                oldVal = p.val;
1040 >                                if (!onlyIfAbsent)
1041 >                                    p.val = value;
1042                              }
1043                          }
1044 +                        else if (f instanceof ReservationNode)
1045 +                            throw new IllegalStateException("Recursive update");
1046                      }
1047                  }
1048 <            }
1049 <            if (p == replacement && (pp = p.parent) != null) {
1050 <                if (p == pp.left) // detach pointers
1051 <                    pp.left = null;
1052 <                else if (p == pp.right)
1053 <                    pp.right = null;
1054 <                p.parent = null;
1048 >                if (binCount != 0) {
1049 >                    if (binCount >= TREEIFY_THRESHOLD)
1050 >                        treeifyBin(tab, i);
1051 >                    if (oldVal != null)
1052 >                        return oldVal;
1053 >                    break;
1054 >                }
1055              }
1056          }
1057 +        addCount(1L, binCount);
1058 +        return null;
1059      }
1060  
1064    /* ---------------- Collision reduction methods -------------- */
1065
1061      /**
1062 <     * Spreads higher bits to lower, and also forces top bit to 0.
1063 <     * Because the table uses power-of-two masking, sets of hashes
1064 <     * that vary only in bits above the current mask will always
1065 <     * collide. (Among known examples are sets of Float keys holding
1066 <     * 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.
1062 >     * Copies all of the mappings from the specified map to this one.
1063 >     * These mappings replace any mappings that this map had for any of the
1064 >     * keys currently in the specified map.
1065 >     *
1066 >     * @param m mappings to be stored in this map
1067       */
1068 <    private static final int spread(int h) {
1069 <        h ^= (h >>> 18) ^ (h >>> 12);
1070 <        return (h ^ (h >>> 10)) & HASH_BITS;
1068 >    public void putAll(Map<? extends K, ? extends V> m) {
1069 >        tryPresize(m.size());
1070 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1071 >            putVal(e.getKey(), e.getValue(), false);
1072      }
1073  
1074      /**
1075 <     * Replaces a list bin with a tree bin if key is comparable.  Call
1076 <     * only when locked.
1075 >     * Removes the key (and its corresponding value) from this map.
1076 >     * This method does nothing if the key is not in the map.
1077 >     *
1078 >     * @param  key the key that needs to be removed
1079 >     * @return the previous value associated with {@code key}, or
1080 >     *         {@code null} if there was no mapping for {@code key}
1081 >     * @throws NullPointerException if the specified key is null
1082       */
1083 <    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1084 <        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;
1083 >    public V remove(Object key) {
1084 >        return replaceNode(key, null, null);
1085      }
1086  
1087      /**
# Line 1124 | Line 1089 | public class ConcurrentHashMap<K, V>
1089       * Replaces node value with v, conditional upon match of cv if
1090       * non-null.  If resulting value is null, delete.
1091       */
1092 <    @SuppressWarnings("unchecked") private final V internalReplace
1093 <        (Object k, V v, Object cv) {
1094 <        int h = spread(k.hashCode());
1095 <        V oldVal = null;
1096 <        for (Node<V>[] tab = table;;) {
1097 <            Node<V> f; int i, fh; Object fk;
1133 <            if (tab == null ||
1134 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1092 >    final V replaceNode(Object key, V value, Object cv) {
1093 >        int hash = spread(key.hashCode());
1094 >        for (Node<K,V>[] tab = table;;) {
1095 >            Node<K,V> f; int n, i, fh;
1096 >            if (tab == null || (n = tab.length) == 0 ||
1097 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1098                  break;
1099 <            else if ((fh = f.hash) < 0) {
1100 <                if ((fk = f.key) instanceof TreeBin) {
1101 <                    TreeBin<V> t = (TreeBin<V>)fk;
1102 <                    boolean validated = false;
1103 <                    boolean deleted = false;
1104 <                    t.acquire(0);
1105 <                    try {
1106 <                        if (tabAt(tab, i) == f) {
1099 >            else if ((fh = f.hash) == MOVED)
1100 >                tab = helpTransfer(tab, f);
1101 >            else {
1102 >                V oldVal = null;
1103 >                boolean validated = false;
1104 >                synchronized (f) {
1105 >                    if (tabAt(tab, i) == f) {
1106 >                        if (fh >= 0) {
1107                              validated = true;
1108 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1109 <                            if (p != null) {
1108 >                            for (Node<K,V> e = f, pred = null;;) {
1109 >                                K ek;
1110 >                                if (e.hash == hash &&
1111 >                                    ((ek = e.key) == key ||
1112 >                                     (ek != null && key.equals(ek)))) {
1113 >                                    V ev = e.val;
1114 >                                    if (cv == null || cv == ev ||
1115 >                                        (ev != null && cv.equals(ev))) {
1116 >                                        oldVal = ev;
1117 >                                        if (value != null)
1118 >                                            e.val = value;
1119 >                                        else if (pred != null)
1120 >                                            pred.next = e.next;
1121 >                                        else
1122 >                                            setTabAt(tab, i, e.next);
1123 >                                    }
1124 >                                    break;
1125 >                                }
1126 >                                pred = e;
1127 >                                if ((e = e.next) == null)
1128 >                                    break;
1129 >                            }
1130 >                        }
1131 >                        else if (f instanceof TreeBin) {
1132 >                            validated = true;
1133 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1134 >                            TreeNode<K,V> r, p;
1135 >                            if ((r = t.root) != null &&
1136 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1137                                  V pv = p.val;
1138 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1138 >                                if (cv == null || cv == pv ||
1139 >                                    (pv != null && cv.equals(pv))) {
1140                                      oldVal = pv;
1141 <                                    if ((p.val = v) == null) {
1142 <                                        deleted = true;
1143 <                                        t.deleteTreeNode(p);
1144 <                                    }
1141 >                                    if (value != null)
1142 >                                        p.val = value;
1143 >                                    else if (t.removeTreeNode(p))
1144 >                                        setTabAt(tab, i, untreeify(t.first));
1145                                  }
1146                              }
1147                          }
1148 <                    } finally {
1149 <                        t.release(0);
1148 >                        else if (f instanceof ReservationNode)
1149 >                            throw new IllegalStateException("Recursive update");
1150                      }
1151 <                    if (validated) {
1152 <                        if (deleted)
1151 >                }
1152 >                if (validated) {
1153 >                    if (oldVal != null) {
1154 >                        if (value == null)
1155                              addCount(-1L, -1);
1156 <                        break;
1156 >                        return oldVal;
1157                      }
1158 +                    break;
1159                  }
1166                else
1167                    tab = (Node<V>[])fk;
1160              }
1161 <            else if (fh != h && f.next == null) // precheck
1162 <                break;                          // rules out possible existence
1161 >        }
1162 >        return null;
1163 >    }
1164 >
1165 >    /**
1166 >     * Removes all of the mappings from this map.
1167 >     */
1168 >    public void clear() {
1169 >        long delta = 0L; // negative number of deletions
1170 >        int i = 0;
1171 >        Node<K,V>[] tab = table;
1172 >        while (tab != null && i < tab.length) {
1173 >            int fh;
1174 >            Node<K,V> f = tabAt(tab, i);
1175 >            if (f == null)
1176 >                ++i;
1177 >            else if ((fh = f.hash) == MOVED) {
1178 >                tab = helpTransfer(tab, f);
1179 >                i = 0; // restart
1180 >            }
1181              else {
1172                boolean validated = false;
1173                boolean deleted = false;
1182                  synchronized (f) {
1183                      if (tabAt(tab, i) == f) {
1184 <                        validated = true;
1185 <                        for (Node<V> e = f, pred = null;;) {
1186 <                            Object ek; V ev;
1187 <                            if (e.hash == h &&
1188 <                                ((ev = e.val) != null) &&
1189 <                                ((ek = e.key) == k || k.equals(ek))) {
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;
1184 >                        Node<K,V> p = (fh >= 0 ? f :
1185 >                                       (f instanceof TreeBin) ?
1186 >                                       ((TreeBin<K,V>)f).first : null);
1187 >                        while (p != null) {
1188 >                            --delta;
1189 >                            p = p.next;
1190                          }
1191 +                        setTabAt(tab, i++, null);
1192                      }
1193                  }
1194 <                if (validated) {
1195 <                    if (deleted)
1196 <                        addCount(-1L, -1);
1194 >            }
1195 >        }
1196 >        if (delta != 0L)
1197 >            addCount(delta, -1);
1198 >    }
1199 >
1200 >    /**
1201 >     * Returns a {@link Set} view of the keys contained in this map.
1202 >     * The set is backed by the map, so changes to the map are
1203 >     * reflected in the set, and vice-versa. The set supports element
1204 >     * removal, which removes the corresponding mapping from this map,
1205 >     * via the {@code Iterator.remove}, {@code Set.remove},
1206 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1207 >     * operations.  It does not support the {@code add} or
1208 >     * {@code addAll} operations.
1209 >     *
1210 >     * <p>The view's iterators and spliterators are
1211 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1212 >     *
1213 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1214 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1215 >     *
1216 >     * @return the set view
1217 >     */
1218 >    public KeySetView<K,V> keySet() {
1219 >        KeySetView<K,V> ks;
1220 >        if ((ks = keySet) != null) return ks;
1221 >        return keySet = new KeySetView<K,V>(this, null);
1222 >    }
1223 >
1224 >    /**
1225 >     * Returns a {@link Collection} view of the values contained in this map.
1226 >     * The collection is backed by the map, so changes to the map are
1227 >     * reflected in the collection, and vice-versa.  The collection
1228 >     * supports element removal, which removes the corresponding
1229 >     * mapping from this map, via the {@code Iterator.remove},
1230 >     * {@code Collection.remove}, {@code removeAll},
1231 >     * {@code retainAll}, and {@code clear} operations.  It does not
1232 >     * support the {@code add} or {@code addAll} operations.
1233 >     *
1234 >     * <p>The view's iterators and spliterators are
1235 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1236 >     *
1237 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}
1238 >     * and {@link Spliterator#NONNULL}.
1239 >     *
1240 >     * @return the collection view
1241 >     */
1242 >    public Collection<V> values() {
1243 >        ValuesView<K,V> vs;
1244 >        if ((vs = values) != null) return vs;
1245 >        return values = new ValuesView<K,V>(this);
1246 >    }
1247 >
1248 >    /**
1249 >     * Returns a {@link Set} view of the mappings contained in this map.
1250 >     * The set is backed by the map, so changes to the map are
1251 >     * reflected in the set, and vice-versa.  The set supports element
1252 >     * removal, which removes the corresponding mapping from the map,
1253 >     * via the {@code Iterator.remove}, {@code Set.remove},
1254 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1255 >     * operations.
1256 >     *
1257 >     * <p>The view's iterators and spliterators are
1258 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1259 >     *
1260 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1261 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1262 >     *
1263 >     * @return the set view
1264 >     */
1265 >    public Set<Map.Entry<K,V>> entrySet() {
1266 >        EntrySetView<K,V> es;
1267 >        if ((es = entrySet) != null) return es;
1268 >        return entrySet = new EntrySetView<K,V>(this);
1269 >    }
1270 >
1271 >    /**
1272 >     * Returns the hash code value for this {@link Map}, i.e.,
1273 >     * the sum of, for each key-value pair in the map,
1274 >     * {@code key.hashCode() ^ value.hashCode()}.
1275 >     *
1276 >     * @return the hash code value for this map
1277 >     */
1278 >    public int hashCode() {
1279 >        int h = 0;
1280 >        Node<K,V>[] t;
1281 >        if ((t = table) != null) {
1282 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1283 >            for (Node<K,V> p; (p = it.advance()) != null; )
1284 >                h += p.key.hashCode() ^ p.val.hashCode();
1285 >        }
1286 >        return h;
1287 >    }
1288 >
1289 >    /**
1290 >     * Returns a string representation of this map.  The string
1291 >     * representation consists of a list of key-value mappings (in no
1292 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1293 >     * mappings are separated by the characters {@code ", "} (comma
1294 >     * and space).  Each key-value mapping is rendered as the key
1295 >     * followed by an equals sign ("{@code =}") followed by the
1296 >     * associated value.
1297 >     *
1298 >     * @return a string representation of this map
1299 >     */
1300 >    public String toString() {
1301 >        Node<K,V>[] t;
1302 >        int f = (t = table) == null ? 0 : t.length;
1303 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1304 >        StringBuilder sb = new StringBuilder();
1305 >        sb.append('{');
1306 >        Node<K,V> p;
1307 >        if ((p = it.advance()) != null) {
1308 >            for (;;) {
1309 >                K k = p.key;
1310 >                V v = p.val;
1311 >                sb.append(k == this ? "(this Map)" : k);
1312 >                sb.append('=');
1313 >                sb.append(v == this ? "(this Map)" : v);
1314 >                if ((p = it.advance()) == null)
1315                      break;
1316 <                }
1316 >                sb.append(',').append(' ');
1317              }
1318          }
1319 <        return oldVal;
1319 >        return sb.append('}').toString();
1320      }
1321  
1322 <    /*
1323 <     * Internal versions of insertion methods
1324 <     * All have the same basic structure as the first (internalPut):
1325 <     *  1. If table uninitialized, create
1326 <     *  2. If bin empty, try to CAS new node
1327 <     *  3. If bin stale, use new table
1328 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1329 <     *  5. Lock and validate; if valid, scan and add or update
1330 <     *
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.
1322 >    /**
1323 >     * Compares the specified object with this map for equality.
1324 >     * Returns {@code true} if the given object is a map with the same
1325 >     * mappings as this map.  This operation may return misleading
1326 >     * results if either map is concurrently modified during execution
1327 >     * of this method.
1328 >     *
1329 >     * @param o object to be compared for equality with this map
1330 >     * @return {@code true} if the specified object is equal to this map
1331       */
1332 +    public boolean equals(Object o) {
1333 +        if (o != this) {
1334 +            if (!(o instanceof Map))
1335 +                return false;
1336 +            Map<?,?> m = (Map<?,?>) o;
1337 +            Node<K,V>[] t;
1338 +            int f = (t = table) == null ? 0 : t.length;
1339 +            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1340 +            for (Node<K,V> p; (p = it.advance()) != null; ) {
1341 +                V val = p.val;
1342 +                Object v = m.get(p.key);
1343 +                if (v == null || (v != val && !v.equals(val)))
1344 +                    return false;
1345 +            }
1346 +            for (Map.Entry<?,?> e : m.entrySet()) {
1347 +                Object mk, mv, v;
1348 +                if ((mk = e.getKey()) == null ||
1349 +                    (mv = e.getValue()) == null ||
1350 +                    (v = get(mk)) == null ||
1351 +                    (mv != v && !mv.equals(v)))
1352 +                    return false;
1353 +            }
1354 +        }
1355 +        return true;
1356 +    }
1357  
1358 <    /** Implementation for put and putIfAbsent */
1359 <    @SuppressWarnings("unchecked") private final V internalPut
1360 <        (K k, V v, boolean onlyIfAbsent) {
1361 <        if (k == null || v == null) throw new NullPointerException();
1362 <        int h = spread(k.hashCode());
1363 <        int len = 0;
1364 <        for (Node<V>[] tab = table;;) {
1365 <            int i, fh; Node<V> f; Object fk; V fv;
1366 <            if (tab == null)
1367 <                tab = initTable();
1368 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1369 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1370 <                    break;                   // no lock when adding to empty bin
1358 >    /**
1359 >     * Stripped-down version of helper class used in previous version,
1360 >     * declared for the sake of serialization compatibility.
1361 >     */
1362 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1363 >        private static final long serialVersionUID = 2249069246763182397L;
1364 >        final float loadFactor;
1365 >        Segment(float lf) { this.loadFactor = lf; }
1366 >    }
1367 >
1368 >    /**
1369 >     * Saves the state of the {@code ConcurrentHashMap} instance to a
1370 >     * stream (i.e., serializes it).
1371 >     * @param s the stream
1372 >     * @throws java.io.IOException if an I/O error occurs
1373 >     * @serialData
1374 >     * the serialized fields, followed by the key (Object) and value
1375 >     * (Object) for each key-value mapping, followed by a null pair.
1376 >     * The key-value mappings are emitted in no particular order.
1377 >     */
1378 >    private void writeObject(java.io.ObjectOutputStream s)
1379 >        throws java.io.IOException {
1380 >        // For serialization compatibility
1381 >        // Emulate segment calculation from previous version of this class
1382 >        int sshift = 0;
1383 >        int ssize = 1;
1384 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1385 >            ++sshift;
1386 >            ssize <<= 1;
1387 >        }
1388 >        int segmentShift = 32 - sshift;
1389 >        int segmentMask = ssize - 1;
1390 >        @SuppressWarnings("unchecked")
1391 >        Segment<K,V>[] segments = (Segment<K,V>[])
1392 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1393 >        for (int i = 0; i < segments.length; ++i)
1394 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1395 >        java.io.ObjectOutputStream.PutField streamFields = s.putFields();
1396 >        streamFields.put("segments", segments);
1397 >        streamFields.put("segmentShift", segmentShift);
1398 >        streamFields.put("segmentMask", segmentMask);
1399 >        s.writeFields();
1400 >
1401 >        Node<K,V>[] t;
1402 >        if ((t = table) != null) {
1403 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1404 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1405 >                s.writeObject(p.key);
1406 >                s.writeObject(p.val);
1407              }
1408 <            else if ((fh = f.hash) < 0) {
1409 <                if ((fk = f.key) instanceof TreeBin) {
1410 <                    TreeBin<V> t = (TreeBin<V>)fk;
1411 <                    V oldVal = null;
1412 <                    t.acquire(0);
1413 <                    try {
1414 <                        if (tabAt(tab, i) == f) {
1415 <                            len = 2;
1416 <                            TreeNode<V> p = t.putTreeNode(h, k, v);
1417 <                            if (p != null) {
1418 <                                oldVal = p.val;
1419 <                                if (!onlyIfAbsent)
1420 <                                    p.val = v;
1421 <                            }
1422 <                        }
1423 <                    } finally {
1424 <                        t.release(0);
1425 <                    }
1426 <                    if (len != 0) {
1427 <                        if (oldVal != null)
1428 <                            return oldVal;
1429 <                        break;
1430 <                    }
1431 <                }
1432 <                else
1433 <                    tab = (Node<V>[])fk;
1408 >        }
1409 >        s.writeObject(null);
1410 >        s.writeObject(null);
1411 >    }
1412 >
1413 >    /**
1414 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1415 >     * @param s the stream
1416 >     * @throws ClassNotFoundException if the class of a serialized object
1417 >     *         could not be found
1418 >     * @throws java.io.IOException if an I/O error occurs
1419 >     */
1420 >    private void readObject(java.io.ObjectInputStream s)
1421 >        throws java.io.IOException, ClassNotFoundException {
1422 >        /*
1423 >         * To improve performance in typical cases, we create nodes
1424 >         * while reading, then place in table once size is known.
1425 >         * However, we must also validate uniqueness and deal with
1426 >         * overpopulated bins while doing so, which requires
1427 >         * specialized versions of putVal mechanics.
1428 >         */
1429 >        sizeCtl = -1; // force exclusion for table construction
1430 >        s.defaultReadObject();
1431 >        long size = 0L;
1432 >        Node<K,V> p = null;
1433 >        for (;;) {
1434 >            @SuppressWarnings("unchecked")
1435 >            K k = (K) s.readObject();
1436 >            @SuppressWarnings("unchecked")
1437 >            V v = (V) s.readObject();
1438 >            if (k != null && v != null) {
1439 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1440 >                ++size;
1441              }
1442 <            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1443 <                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1444 <                return fv;
1442 >            else
1443 >                break;
1444 >        }
1445 >        if (size == 0L)
1446 >            sizeCtl = 0;
1447 >        else {
1448 >            int n;
1449 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1450 >                n = MAXIMUM_CAPACITY;
1451              else {
1452 <                V oldVal = null;
1453 <                synchronized (f) {
1454 <                    if (tabAt(tab, i) == f) {
1455 <                        len = 1;
1456 <                        for (Node<V> e = f;; ++len) {
1457 <                            Object ek; V ev;
1458 <                            if (e.hash == h &&
1459 <                                (ev = e.val) != null &&
1460 <                                ((ek = e.key) == k || k.equals(ek))) {
1461 <                                oldVal = ev;
1462 <                                if (!onlyIfAbsent)
1463 <                                    e.val = v;
1452 >                int sz = (int)size;
1453 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1454 >            }
1455 >            @SuppressWarnings("unchecked")
1456 >            Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1457 >            int mask = n - 1;
1458 >            long added = 0L;
1459 >            while (p != null) {
1460 >                boolean insertAtFront;
1461 >                Node<K,V> next = p.next, first;
1462 >                int h = p.hash, j = h & mask;
1463 >                if ((first = tabAt(tab, j)) == null)
1464 >                    insertAtFront = true;
1465 >                else {
1466 >                    K k = p.key;
1467 >                    if (first.hash < 0) {
1468 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1469 >                        if (t.putTreeVal(h, k, p.val) == null)
1470 >                            ++added;
1471 >                        insertAtFront = false;
1472 >                    }
1473 >                    else {
1474 >                        int binCount = 0;
1475 >                        insertAtFront = true;
1476 >                        Node<K,V> q; K qk;
1477 >                        for (q = first; q != null; q = q.next) {
1478 >                            if (q.hash == h &&
1479 >                                ((qk = q.key) == k ||
1480 >                                 (qk != null && k.equals(qk)))) {
1481 >                                insertAtFront = false;
1482                                  break;
1483                              }
1484 <                            Node<V> last = e;
1485 <                            if ((e = e.next) == null) {
1486 <                                last.next = new Node<V>(h, k, v, null);
1487 <                                if (len >= TREE_THRESHOLD)
1488 <                                    replaceWithTreeBin(tab, i, k);
1489 <                                break;
1484 >                            ++binCount;
1485 >                        }
1486 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1487 >                            insertAtFront = false;
1488 >                            ++added;
1489 >                            p.next = first;
1490 >                            TreeNode<K,V> hd = null, tl = null;
1491 >                            for (q = p; q != null; q = q.next) {
1492 >                                TreeNode<K,V> t = new TreeNode<K,V>
1493 >                                    (q.hash, q.key, q.val, null, null);
1494 >                                if ((t.prev = tl) == null)
1495 >                                    hd = t;
1496 >                                else
1497 >                                    tl.next = t;
1498 >                                tl = t;
1499                              }
1500 +                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1501                          }
1502                      }
1503                  }
1504 <                if (len != 0) {
1505 <                    if (oldVal != null)
1506 <                        return oldVal;
1507 <                    break;
1504 >                if (insertAtFront) {
1505 >                    ++added;
1506 >                    p.next = first;
1507 >                    setTabAt(tab, j, p);
1508 >                }
1509 >                p = next;
1510 >            }
1511 >            table = tab;
1512 >            sizeCtl = n - (n >>> 2);
1513 >            baseCount = added;
1514 >        }
1515 >    }
1516 >
1517 >    // ConcurrentMap methods
1518 >
1519 >    /**
1520 >     * {@inheritDoc}
1521 >     *
1522 >     * @return the previous value associated with the specified key,
1523 >     *         or {@code null} if there was no mapping for the key
1524 >     * @throws NullPointerException if the specified key or value is null
1525 >     */
1526 >    public V putIfAbsent(K key, V value) {
1527 >        return putVal(key, value, true);
1528 >    }
1529 >
1530 >    /**
1531 >     * {@inheritDoc}
1532 >     *
1533 >     * @throws NullPointerException if the specified key is null
1534 >     */
1535 >    public boolean remove(Object key, Object value) {
1536 >        if (key == null)
1537 >            throw new NullPointerException();
1538 >        return value != null && replaceNode(key, null, value) != null;
1539 >    }
1540 >
1541 >    /**
1542 >     * {@inheritDoc}
1543 >     *
1544 >     * @throws NullPointerException if any of the arguments are null
1545 >     */
1546 >    public boolean replace(K key, V oldValue, V newValue) {
1547 >        if (key == null || oldValue == null || newValue == null)
1548 >            throw new NullPointerException();
1549 >        return replaceNode(key, newValue, oldValue) != null;
1550 >    }
1551 >
1552 >    /**
1553 >     * {@inheritDoc}
1554 >     *
1555 >     * @return the previous value associated with the specified key,
1556 >     *         or {@code null} if there was no mapping for the key
1557 >     * @throws NullPointerException if the specified key or value is null
1558 >     */
1559 >    public V replace(K key, V value) {
1560 >        if (key == null || value == null)
1561 >            throw new NullPointerException();
1562 >        return replaceNode(key, value, null);
1563 >    }
1564 >
1565 >    // Overrides of JDK8+ Map extension method defaults
1566 >
1567 >    /**
1568 >     * Returns the value to which the specified key is mapped, or the
1569 >     * given default value if this map contains no mapping for the
1570 >     * key.
1571 >     *
1572 >     * @param key the key whose associated value is to be returned
1573 >     * @param defaultValue the value to return if this map contains
1574 >     * no mapping for the given key
1575 >     * @return the mapping for the key, if present; else the default value
1576 >     * @throws NullPointerException if the specified key is null
1577 >     */
1578 >    public V getOrDefault(Object key, V defaultValue) {
1579 >        V v;
1580 >        return (v = get(key)) == null ? defaultValue : v;
1581 >    }
1582 >
1583 >    public void forEach(BiConsumer<? super K, ? super V> action) {
1584 >        if (action == null) throw new NullPointerException();
1585 >        Node<K,V>[] t;
1586 >        if ((t = table) != null) {
1587 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1588 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1589 >                action.accept(p.key, p.val);
1590 >            }
1591 >        }
1592 >    }
1593 >
1594 >    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1595 >        if (function == null) throw new NullPointerException();
1596 >        Node<K,V>[] t;
1597 >        if ((t = table) != null) {
1598 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1599 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1600 >                V oldValue = p.val;
1601 >                for (K key = p.key;;) {
1602 >                    V newValue = function.apply(key, oldValue);
1603 >                    if (newValue == null)
1604 >                        throw new NullPointerException();
1605 >                    if (replaceNode(key, newValue, oldValue) != null ||
1606 >                        (oldValue = get(key)) == null)
1607 >                        break;
1608                  }
1609              }
1610          }
1305        addCount(1L, len);
1306        return null;
1611      }
1612  
1613 <    /** Implementation for computeIfAbsent */
1614 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1615 <        (K k, Function<? super K, ? extends V> mf) {
1616 <        if (k == null || mf == null)
1613 >    /**
1614 >     * Helper method for EntrySetView.removeIf.
1615 >     */
1616 >    boolean removeEntryIf(Predicate<? super Entry<K,V>> function) {
1617 >        if (function == null) throw new NullPointerException();
1618 >        Node<K,V>[] t;
1619 >        boolean removed = false;
1620 >        if ((t = table) != null) {
1621 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1622 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1623 >                K k = p.key;
1624 >                V v = p.val;
1625 >                Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v);
1626 >                if (function.test(e) && replaceNode(k, null, v) != null)
1627 >                    removed = true;
1628 >            }
1629 >        }
1630 >        return removed;
1631 >    }
1632 >
1633 >    /**
1634 >     * Helper method for ValuesView.removeIf.
1635 >     */
1636 >    boolean removeValueIf(Predicate<? super V> function) {
1637 >        if (function == null) throw new NullPointerException();
1638 >        Node<K,V>[] t;
1639 >        boolean removed = false;
1640 >        if ((t = table) != null) {
1641 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1642 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1643 >                K k = p.key;
1644 >                V v = p.val;
1645 >                if (function.test(v) && replaceNode(k, null, v) != null)
1646 >                    removed = true;
1647 >            }
1648 >        }
1649 >        return removed;
1650 >    }
1651 >
1652 >    /**
1653 >     * If the specified key is not already associated with a value,
1654 >     * attempts to compute its value using the given mapping function
1655 >     * and enters it into this map unless {@code null}.  The entire
1656 >     * method invocation is performed atomically, so the function is
1657 >     * applied at most once per key.  Some attempted update operations
1658 >     * on this map by other threads may be blocked while computation
1659 >     * is in progress, so the computation should be short and simple,
1660 >     * and must not attempt to update any other mappings of this map.
1661 >     *
1662 >     * @param key key with which the specified value is to be associated
1663 >     * @param mappingFunction the function to compute a value
1664 >     * @return the current (existing or computed) value associated with
1665 >     *         the specified key, or null if the computed value is null
1666 >     * @throws NullPointerException if the specified key or mappingFunction
1667 >     *         is null
1668 >     * @throws IllegalStateException if the computation detectably
1669 >     *         attempts a recursive update to this map that would
1670 >     *         otherwise never complete
1671 >     * @throws RuntimeException or Error if the mappingFunction does so,
1672 >     *         in which case the mapping is left unestablished
1673 >     */
1674 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1675 >        if (key == null || mappingFunction == null)
1676              throw new NullPointerException();
1677 <        int h = spread(k.hashCode());
1677 >        int h = spread(key.hashCode());
1678          V val = null;
1679 <        int len = 0;
1680 <        for (Node<V>[] tab = table;;) {
1681 <            Node<V> f; int i; Object fk;
1682 <            if (tab == null)
1679 >        int binCount = 0;
1680 >        for (Node<K,V>[] tab = table;;) {
1681 >            Node<K,V> f; int n, i, fh; K fk; V fv;
1682 >            if (tab == null || (n = tab.length) == 0)
1683                  tab = initTable();
1684 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1685 <                Node<V> node = new Node<V>(h, k, null, null);
1686 <                synchronized (node) {
1687 <                    if (casTabAt(tab, i, null, node)) {
1688 <                        len = 1;
1684 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1685 >                Node<K,V> r = new ReservationNode<K,V>();
1686 >                synchronized (r) {
1687 >                    if (casTabAt(tab, i, null, r)) {
1688 >                        binCount = 1;
1689 >                        Node<K,V> node = null;
1690                          try {
1691 <                            if ((val = mf.apply(k)) != null)
1692 <                                node.val = val;
1691 >                            if ((val = mappingFunction.apply(key)) != null)
1692 >                                node = new Node<K,V>(h, key, val);
1693                          } finally {
1694 <                            if (val == null)
1331 <                                setTabAt(tab, i, null);
1694 >                            setTabAt(tab, i, node);
1695                          }
1696                      }
1697                  }
1698 <                if (len != 0)
1698 >                if (binCount != 0)
1699                      break;
1700              }
1701 <            else if (f.hash < 0) {
1702 <                if ((fk = f.key) instanceof TreeBin) {
1703 <                    TreeBin<V> t = (TreeBin<V>)fk;
1704 <                    boolean added = false;
1705 <                    t.acquire(0);
1706 <                    try {
1707 <                        if (tabAt(tab, i) == f) {
1708 <                            len = 1;
1709 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1710 <                            if (p != null)
1701 >            else if ((fh = f.hash) == MOVED)
1702 >                tab = helpTransfer(tab, f);
1703 >            else if (fh == h    // check first node without acquiring lock
1704 >                     && ((fk = f.key) == key || (fk != null && key.equals(fk)))
1705 >                     && (fv = f.val) != null)
1706 >                return fv;
1707 >            else {
1708 >                boolean added = false;
1709 >                synchronized (f) {
1710 >                    if (tabAt(tab, i) == f) {
1711 >                        if (fh >= 0) {
1712 >                            binCount = 1;
1713 >                            for (Node<K,V> e = f;; ++binCount) {
1714 >                                K ek;
1715 >                                if (e.hash == h &&
1716 >                                    ((ek = e.key) == key ||
1717 >                                     (ek != null && key.equals(ek)))) {
1718 >                                    val = e.val;
1719 >                                    break;
1720 >                                }
1721 >                                Node<K,V> pred = e;
1722 >                                if ((e = e.next) == null) {
1723 >                                    if ((val = mappingFunction.apply(key)) != null) {
1724 >                                        if (pred.next != null)
1725 >                                            throw new IllegalStateException("Recursive update");
1726 >                                        added = true;
1727 >                                        pred.next = new Node<K,V>(h, key, val);
1728 >                                    }
1729 >                                    break;
1730 >                                }
1731 >                            }
1732 >                        }
1733 >                        else if (f instanceof TreeBin) {
1734 >                            binCount = 2;
1735 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1736 >                            TreeNode<K,V> r, p;
1737 >                            if ((r = t.root) != null &&
1738 >                                (p = r.findTreeNode(h, key, null)) != null)
1739                                  val = p.val;
1740 <                            else if ((val = mf.apply(k)) != null) {
1740 >                            else if ((val = mappingFunction.apply(key)) != null) {
1741                                  added = true;
1742 <                                len = 2;
1352 <                                t.putTreeNode(h, k, val);
1742 >                                t.putTreeVal(h, key, val);
1743                              }
1744                          }
1745 <                    } finally {
1746 <                        t.release(0);
1357 <                    }
1358 <                    if (len != 0) {
1359 <                        if (!added)
1360 <                            return val;
1361 <                        break;
1745 >                        else if (f instanceof ReservationNode)
1746 >                            throw new IllegalStateException("Recursive update");
1747                      }
1748                  }
1749 <                else
1750 <                    tab = (Node<V>[])fk;
1749 >                if (binCount != 0) {
1750 >                    if (binCount >= TREEIFY_THRESHOLD)
1751 >                        treeifyBin(tab, i);
1752 >                    if (!added)
1753 >                        return val;
1754 >                    break;
1755 >                }
1756              }
1757 +        }
1758 +        if (val != null)
1759 +            addCount(1L, binCount);
1760 +        return val;
1761 +    }
1762 +
1763 +    /**
1764 +     * If the value for the specified key is present, attempts to
1765 +     * compute a new mapping given the key and its current mapped
1766 +     * value.  The entire method invocation is performed atomically.
1767 +     * Some attempted update operations on this map by other threads
1768 +     * may be blocked while computation is in progress, so the
1769 +     * computation should be short and simple, and must not attempt to
1770 +     * update any other mappings of this map.
1771 +     *
1772 +     * @param key key with which a value may be associated
1773 +     * @param remappingFunction the function to compute a value
1774 +     * @return the new value associated with the specified key, or null if none
1775 +     * @throws NullPointerException if the specified key or remappingFunction
1776 +     *         is null
1777 +     * @throws IllegalStateException if the computation detectably
1778 +     *         attempts a recursive update to this map that would
1779 +     *         otherwise never complete
1780 +     * @throws RuntimeException or Error if the remappingFunction does so,
1781 +     *         in which case the mapping is unchanged
1782 +     */
1783 +    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1784 +        if (key == null || remappingFunction == null)
1785 +            throw new NullPointerException();
1786 +        int h = spread(key.hashCode());
1787 +        V val = null;
1788 +        int delta = 0;
1789 +        int binCount = 0;
1790 +        for (Node<K,V>[] tab = table;;) {
1791 +            Node<K,V> f; int n, i, fh;
1792 +            if (tab == null || (n = tab.length) == 0)
1793 +                tab = initTable();
1794 +            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1795 +                break;
1796 +            else if ((fh = f.hash) == MOVED)
1797 +                tab = helpTransfer(tab, f);
1798              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;
1799                  synchronized (f) {
1800                      if (tabAt(tab, i) == f) {
1801 <                        len = 1;
1802 <                        for (Node<V> e = f;; ++len) {
1803 <                            Object ek; V ev;
1804 <                            if (e.hash == h &&
1805 <                                (ev = e.val) != null &&
1806 <                                ((ek = e.key) == k || k.equals(ek))) {
1807 <                                val = ev;
1808 <                                break;
1801 >                        if (fh >= 0) {
1802 >                            binCount = 1;
1803 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1804 >                                K ek;
1805 >                                if (e.hash == h &&
1806 >                                    ((ek = e.key) == key ||
1807 >                                     (ek != null && key.equals(ek)))) {
1808 >                                    val = remappingFunction.apply(key, e.val);
1809 >                                    if (val != null)
1810 >                                        e.val = val;
1811 >                                    else {
1812 >                                        delta = -1;
1813 >                                        Node<K,V> en = e.next;
1814 >                                        if (pred != null)
1815 >                                            pred.next = en;
1816 >                                        else
1817 >                                            setTabAt(tab, i, en);
1818 >                                    }
1819 >                                    break;
1820 >                                }
1821 >                                pred = e;
1822 >                                if ((e = e.next) == null)
1823 >                                    break;
1824                              }
1825 <                            Node<V> last = e;
1826 <                            if ((e = e.next) == null) {
1827 <                                if ((val = mf.apply(k)) != null) {
1828 <                                    added = true;
1829 <                                    last.next = new Node<V>(h, k, val, null);
1830 <                                    if (len >= TREE_THRESHOLD)
1831 <                                        replaceWithTreeBin(tab, i, k);
1825 >                        }
1826 >                        else if (f instanceof TreeBin) {
1827 >                            binCount = 2;
1828 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1829 >                            TreeNode<K,V> r, p;
1830 >                            if ((r = t.root) != null &&
1831 >                                (p = r.findTreeNode(h, key, null)) != null) {
1832 >                                val = remappingFunction.apply(key, p.val);
1833 >                                if (val != null)
1834 >                                    p.val = val;
1835 >                                else {
1836 >                                    delta = -1;
1837 >                                    if (t.removeTreeNode(p))
1838 >                                        setTabAt(tab, i, untreeify(t.first));
1839                                  }
1394                                break;
1840                              }
1841                          }
1842 +                        else if (f instanceof ReservationNode)
1843 +                            throw new IllegalStateException("Recursive update");
1844                      }
1845                  }
1846 <                if (len != 0) {
1400 <                    if (!added)
1401 <                        return val;
1846 >                if (binCount != 0)
1847                      break;
1403                }
1848              }
1849          }
1850 <        if (val != null)
1851 <            addCount(1L, len);
1850 >        if (delta != 0)
1851 >            addCount((long)delta, binCount);
1852          return val;
1853      }
1854  
1855 <    /** Implementation for compute */
1856 <    @SuppressWarnings("unchecked") private final V internalCompute
1857 <        (K k, boolean onlyIfPresent,
1858 <         BiFunction<? super K, ? super V, ? extends V> mf) {
1859 <        if (k == null || mf == null)
1855 >    /**
1856 >     * Attempts to compute a mapping for the specified key and its
1857 >     * current mapped value (or {@code null} if there is no current
1858 >     * mapping). The entire method invocation is performed atomically.
1859 >     * Some attempted update operations on this map by other threads
1860 >     * may be blocked while computation is in progress, so the
1861 >     * computation should be short and simple, and must not attempt to
1862 >     * update any other mappings of this Map.
1863 >     *
1864 >     * @param key key with which the specified value is to be associated
1865 >     * @param remappingFunction the function to compute a value
1866 >     * @return the new value associated with the specified key, or null if none
1867 >     * @throws NullPointerException if the specified key or remappingFunction
1868 >     *         is null
1869 >     * @throws IllegalStateException if the computation detectably
1870 >     *         attempts a recursive update to this map that would
1871 >     *         otherwise never complete
1872 >     * @throws RuntimeException or Error if the remappingFunction does so,
1873 >     *         in which case the mapping is unchanged
1874 >     */
1875 >    public V compute(K key,
1876 >                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1877 >        if (key == null || remappingFunction == null)
1878              throw new NullPointerException();
1879 <        int h = spread(k.hashCode());
1879 >        int h = spread(key.hashCode());
1880          V val = null;
1881          int delta = 0;
1882 <        int len = 0;
1883 <        for (Node<V>[] tab = table;;) {
1884 <            Node<V> f; int i, fh; Object fk;
1885 <            if (tab == null)
1882 >        int binCount = 0;
1883 >        for (Node<K,V>[] tab = table;;) {
1884 >            Node<K,V> f; int n, i, fh;
1885 >            if (tab == null || (n = tab.length) == 0)
1886                  tab = initTable();
1887 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1888 <                if (onlyIfPresent)
1889 <                    break;
1890 <                Node<V> node = new Node<V>(h, k, null, null);
1891 <                synchronized (node) {
1892 <                    if (casTabAt(tab, i, null, node)) {
1887 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1888 >                Node<K,V> r = new ReservationNode<K,V>();
1889 >                synchronized (r) {
1890 >                    if (casTabAt(tab, i, null, r)) {
1891 >                        binCount = 1;
1892 >                        Node<K,V> node = null;
1893                          try {
1894 <                            len = 1;
1433 <                            if ((val = mf.apply(k, null)) != null) {
1434 <                                node.val = val;
1894 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1895                                  delta = 1;
1896 +                                node = new Node<K,V>(h, key, val);
1897                              }
1898                          } finally {
1899 <                            if (delta == 0)
1439 <                                setTabAt(tab, i, null);
1899 >                            setTabAt(tab, i, node);
1900                          }
1901                      }
1902                  }
1903 <                if (len != 0)
1903 >                if (binCount != 0)
1904                      break;
1905              }
1906 <            else if ((fh = f.hash) < 0) {
1907 <                if ((fk = f.key) instanceof TreeBin) {
1908 <                    TreeBin<V> t = (TreeBin<V>)fk;
1909 <                    t.acquire(0);
1910 <                    try {
1911 <                        if (tabAt(tab, i) == f) {
1912 <                            len = 1;
1913 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1914 <                            if (p == null && onlyIfPresent)
1915 <                                break;
1906 >            else if ((fh = f.hash) == MOVED)
1907 >                tab = helpTransfer(tab, f);
1908 >            else {
1909 >                synchronized (f) {
1910 >                    if (tabAt(tab, i) == f) {
1911 >                        if (fh >= 0) {
1912 >                            binCount = 1;
1913 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1914 >                                K ek;
1915 >                                if (e.hash == h &&
1916 >                                    ((ek = e.key) == key ||
1917 >                                     (ek != null && key.equals(ek)))) {
1918 >                                    val = remappingFunction.apply(key, e.val);
1919 >                                    if (val != null)
1920 >                                        e.val = val;
1921 >                                    else {
1922 >                                        delta = -1;
1923 >                                        Node<K,V> en = e.next;
1924 >                                        if (pred != null)
1925 >                                            pred.next = en;
1926 >                                        else
1927 >                                            setTabAt(tab, i, en);
1928 >                                    }
1929 >                                    break;
1930 >                                }
1931 >                                pred = e;
1932 >                                if ((e = e.next) == null) {
1933 >                                    val = remappingFunction.apply(key, null);
1934 >                                    if (val != null) {
1935 >                                        if (pred.next != null)
1936 >                                            throw new IllegalStateException("Recursive update");
1937 >                                        delta = 1;
1938 >                                        pred.next = new Node<K,V>(h, key, val);
1939 >                                    }
1940 >                                    break;
1941 >                                }
1942 >                            }
1943 >                        }
1944 >                        else if (f instanceof TreeBin) {
1945 >                            binCount = 1;
1946 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1947 >                            TreeNode<K,V> r, p;
1948 >                            if ((r = t.root) != null)
1949 >                                p = r.findTreeNode(h, key, null);
1950 >                            else
1951 >                                p = null;
1952                              V pv = (p == null) ? null : p.val;
1953 <                            if ((val = mf.apply(k, pv)) != null) {
1953 >                            val = remappingFunction.apply(key, pv);
1954 >                            if (val != null) {
1955                                  if (p != null)
1956                                      p.val = val;
1957                                  else {
1461                                    len = 2;
1958                                      delta = 1;
1959 <                                    t.putTreeNode(h, k, val);
1959 >                                    t.putTreeVal(h, key, val);
1960                                  }
1961                              }
1962                              else if (p != null) {
1963                                  delta = -1;
1964 <                                t.deleteTreeNode(p);
1965 <                            }
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;
1964 >                                if (t.removeTreeNode(p))
1965 >                                    setTabAt(tab, i, untreeify(t.first));
1966                              }
1967                          }
1968 +                        else if (f instanceof ReservationNode)
1969 +                            throw new IllegalStateException("Recursive update");
1970                      }
1971                  }
1972 <                if (len != 0)
1972 >                if (binCount != 0) {
1973 >                    if (binCount >= TREEIFY_THRESHOLD)
1974 >                        treeifyBin(tab, i);
1975                      break;
1976 +                }
1977              }
1978          }
1979          if (delta != 0)
1980 <            addCount((long)delta, len);
1980 >            addCount((long)delta, binCount);
1981          return val;
1982      }
1983  
1984 <    /** Implementation for merge */
1985 <    @SuppressWarnings("unchecked") private final V internalMerge
1986 <        (K k, V v, BiFunction<? super V, ? super V, ? extends V> mf) {
1987 <        if (k == null || v == null || mf == null)
1984 >    /**
1985 >     * If the specified key is not already associated with a
1986 >     * (non-null) value, associates it with the given value.
1987 >     * Otherwise, replaces the value with the results of the given
1988 >     * remapping function, or removes if {@code null}. The entire
1989 >     * method invocation is performed atomically.  Some attempted
1990 >     * update operations on this map by other threads may be blocked
1991 >     * while computation is in progress, so the computation should be
1992 >     * short and simple, and must not attempt to update any other
1993 >     * mappings of this Map.
1994 >     *
1995 >     * @param key key with which the specified value is to be associated
1996 >     * @param value the value to use if absent
1997 >     * @param remappingFunction the function to recompute a value if present
1998 >     * @return the new value associated with the specified key, or null if none
1999 >     * @throws NullPointerException if the specified key or the
2000 >     *         remappingFunction is null
2001 >     * @throws RuntimeException or Error if the remappingFunction does so,
2002 >     *         in which case the mapping is unchanged
2003 >     */
2004 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2005 >        if (key == null || value == null || remappingFunction == null)
2006              throw new NullPointerException();
2007 <        int h = spread(k.hashCode());
2007 >        int h = spread(key.hashCode());
2008          V val = null;
2009          int delta = 0;
2010 <        int len = 0;
2011 <        for (Node<V>[] tab = table;;) {
2012 <            int i; Node<V> f; Object fk; V fv;
2013 <            if (tab == null)
2010 >        int binCount = 0;
2011 >        for (Node<K,V>[] tab = table;;) {
2012 >            Node<K,V> f; int n, i, fh;
2013 >            if (tab == null || (n = tab.length) == 0)
2014                  tab = initTable();
2015 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
2016 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
2015 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
2016 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value))) {
2017                      delta = 1;
2018 <                    val = v;
2018 >                    val = value;
2019                      break;
2020                  }
2021              }
2022 <            else if (f.hash < 0) {
2023 <                if ((fk = f.key) instanceof TreeBin) {
2024 <                    TreeBin<V> t = (TreeBin<V>)fk;
2025 <                    t.acquire(0);
2026 <                    try {
2027 <                        if (tabAt(tab, i) == f) {
2028 <                            len = 1;
2029 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
2030 <                            val = (p == null) ? v : mf.apply(p.val, v);
2022 >            else if ((fh = f.hash) == MOVED)
2023 >                tab = helpTransfer(tab, f);
2024 >            else {
2025 >                synchronized (f) {
2026 >                    if (tabAt(tab, i) == f) {
2027 >                        if (fh >= 0) {
2028 >                            binCount = 1;
2029 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
2030 >                                K ek;
2031 >                                if (e.hash == h &&
2032 >                                    ((ek = e.key) == key ||
2033 >                                     (ek != null && key.equals(ek)))) {
2034 >                                    val = remappingFunction.apply(e.val, value);
2035 >                                    if (val != null)
2036 >                                        e.val = val;
2037 >                                    else {
2038 >                                        delta = -1;
2039 >                                        Node<K,V> en = e.next;
2040 >                                        if (pred != null)
2041 >                                            pred.next = en;
2042 >                                        else
2043 >                                            setTabAt(tab, i, en);
2044 >                                    }
2045 >                                    break;
2046 >                                }
2047 >                                pred = e;
2048 >                                if ((e = e.next) == null) {
2049 >                                    delta = 1;
2050 >                                    val = value;
2051 >                                    pred.next = new Node<K,V>(h, key, val);
2052 >                                    break;
2053 >                                }
2054 >                            }
2055 >                        }
2056 >                        else if (f instanceof TreeBin) {
2057 >                            binCount = 2;
2058 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2059 >                            TreeNode<K,V> r = t.root;
2060 >                            TreeNode<K,V> p = (r == null) ? null :
2061 >                                r.findTreeNode(h, key, null);
2062 >                            val = (p == null) ? value :
2063 >                                remappingFunction.apply(p.val, value);
2064                              if (val != null) {
2065                                  if (p != null)
2066                                      p.val = val;
2067                                  else {
1558                                    len = 2;
2068                                      delta = 1;
2069 <                                    t.putTreeNode(h, k, val);
2069 >                                    t.putTreeVal(h, key, val);
2070                                  }
2071                              }
2072                              else if (p != null) {
2073                                  delta = -1;
2074 <                                t.deleteTreeNode(p);
2074 >                                if (t.removeTreeNode(p))
2075 >                                    setTabAt(tab, i, untreeify(t.first));
2076                              }
2077                          }
2078 <                    } finally {
2079 <                        t.release(0);
2078 >                        else if (f instanceof ReservationNode)
2079 >                            throw new IllegalStateException("Recursive update");
2080                      }
1571                    if (len != 0)
1572                        break;
2081                  }
2082 <                else
2083 <                    tab = (Node<V>[])fk;
2084 <            }
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)
2082 >                if (binCount != 0) {
2083 >                    if (binCount >= TREEIFY_THRESHOLD)
2084 >                        treeifyBin(tab, i);
2085                      break;
2086 +                }
2087              }
2088          }
2089          if (delta != 0)
2090 <            addCount((long)delta, len);
2090 >            addCount((long)delta, binCount);
2091          return val;
2092      }
2093  
2094 <    /** Implementation for putAll */
2095 <    @SuppressWarnings("unchecked") private final void internalPutAll
2096 <        (Map<? extends K, ? extends V> m) {
2097 <        tryPresize(m.size());
2098 <        long delta = 0L;     // number of uncommitted additions
2099 <        boolean npe = false; // to throw exception on exit for nulls
2100 <        try {                // to clean up counts on other exceptions
2101 <            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
2102 <                Object k; V v;
2103 <                if (entry == null || (k = entry.getKey()) == null ||
2104 <                    (v = entry.getValue()) == null) {
2105 <                    npe = true;
2106 <                    break;
2107 <                }
2108 <                int h = spread(k.hashCode());
2109 <                for (Node<V>[] tab = table;;) {
2110 <                    int i; Node<V> f; int fh; Object fk;
2111 <                    if (tab == null)
2112 <                        tab = initTable();
2113 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
2114 <                        if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
2115 <                            ++delta;
2116 <                            break;
2117 <                        }
2118 <                    }
2119 <                    else if ((fh = f.hash) < 0) {
2120 <                        if ((fk = f.key) instanceof TreeBin) {
2121 <                            TreeBin<V> t = (TreeBin<V>)fk;
2122 <                            boolean validated = false;
2123 <                            t.acquire(0);
2124 <                            try {
2125 <                                if (tabAt(tab, i) == f) {
2126 <                                    validated = true;
2127 <                                    TreeNode<V> p = t.getTreeNode(h, k, t.root);
2128 <                                    if (p != null)
2129 <                                        p.val = v;
2130 <                                    else {
2131 <                                        t.putTreeNode(h, k, v);
2132 <                                        ++delta;
2133 <                                    }
2134 <                                }
2135 <                            } finally {
2136 <                                t.release(0);
2137 <                            }
2138 <                            if (validated)
2139 <                                break;
2094 >    // Hashtable legacy methods
2095 >
2096 >    /**
2097 >     * Tests if some key maps into the specified value in this table.
2098 >     *
2099 >     * <p>Note that this method is identical in functionality to
2100 >     * {@link #containsValue(Object)}, and exists solely to ensure
2101 >     * full compatibility with class {@link java.util.Hashtable},
2102 >     * which supported this method prior to introduction of the
2103 >     * Java Collections Framework.
2104 >     *
2105 >     * @param  value a value to search for
2106 >     * @return {@code true} if and only if some key maps to the
2107 >     *         {@code value} argument in this table as
2108 >     *         determined by the {@code equals} method;
2109 >     *         {@code false} otherwise
2110 >     * @throws NullPointerException if the specified value is null
2111 >     */
2112 >    public boolean contains(Object value) {
2113 >        return containsValue(value);
2114 >    }
2115 >
2116 >    /**
2117 >     * Returns an enumeration of the keys in this table.
2118 >     *
2119 >     * @return an enumeration of the keys in this table
2120 >     * @see #keySet()
2121 >     */
2122 >    public Enumeration<K> keys() {
2123 >        Node<K,V>[] t;
2124 >        int f = (t = table) == null ? 0 : t.length;
2125 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2126 >    }
2127 >
2128 >    /**
2129 >     * Returns an enumeration of the values in this table.
2130 >     *
2131 >     * @return an enumeration of the values in this table
2132 >     * @see #values()
2133 >     */
2134 >    public Enumeration<V> elements() {
2135 >        Node<K,V>[] t;
2136 >        int f = (t = table) == null ? 0 : t.length;
2137 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2138 >    }
2139 >
2140 >    // ConcurrentHashMap-only methods
2141 >
2142 >    /**
2143 >     * Returns the number of mappings. This method should be used
2144 >     * instead of {@link #size} because a ConcurrentHashMap may
2145 >     * contain more mappings than can be represented as an int. The
2146 >     * value returned is an estimate; the actual count may differ if
2147 >     * there are concurrent insertions or removals.
2148 >     *
2149 >     * @return the number of mappings
2150 >     * @since 1.8
2151 >     */
2152 >    public long mappingCount() {
2153 >        long n = sumCount();
2154 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2155 >    }
2156 >
2157 >    /**
2158 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2159 >     * from the given type to {@code Boolean.TRUE}.
2160 >     *
2161 >     * @param <K> the element type of the returned set
2162 >     * @return the new set
2163 >     * @since 1.8
2164 >     */
2165 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2166 >        return new KeySetView<K,Boolean>
2167 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2168 >    }
2169 >
2170 >    /**
2171 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2172 >     * from the given type to {@code Boolean.TRUE}.
2173 >     *
2174 >     * @param initialCapacity The implementation performs internal
2175 >     * sizing to accommodate this many elements.
2176 >     * @param <K> the element type of the returned set
2177 >     * @return the new set
2178 >     * @throws IllegalArgumentException if the initial capacity of
2179 >     * elements is negative
2180 >     * @since 1.8
2181 >     */
2182 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2183 >        return new KeySetView<K,Boolean>
2184 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2185 >    }
2186 >
2187 >    /**
2188 >     * Returns a {@link Set} view of the keys in this map, using the
2189 >     * given common mapped value for any additions (i.e., {@link
2190 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2191 >     * This is of course only appropriate if it is acceptable to use
2192 >     * the same value for all additions from this view.
2193 >     *
2194 >     * @param mappedValue the mapped value to use for any additions
2195 >     * @return the set view
2196 >     * @throws NullPointerException if the mappedValue is null
2197 >     */
2198 >    public KeySetView<K,V> keySet(V mappedValue) {
2199 >        if (mappedValue == null)
2200 >            throw new NullPointerException();
2201 >        return new KeySetView<K,V>(this, mappedValue);
2202 >    }
2203 >
2204 >    /* ---------------- Special Nodes -------------- */
2205 >
2206 >    /**
2207 >     * A node inserted at head of bins during transfer operations.
2208 >     */
2209 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2210 >        final Node<K,V>[] nextTable;
2211 >        ForwardingNode(Node<K,V>[] tab) {
2212 >            super(MOVED, null, null);
2213 >            this.nextTable = tab;
2214 >        }
2215 >
2216 >        Node<K,V> find(int h, Object k) {
2217 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2218 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2219 >                Node<K,V> e; int n;
2220 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2221 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2222 >                    return null;
2223 >                for (;;) {
2224 >                    int eh; K ek;
2225 >                    if ((eh = e.hash) == h &&
2226 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2227 >                        return e;
2228 >                    if (eh < 0) {
2229 >                        if (e instanceof ForwardingNode) {
2230 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2231 >                            continue outer;
2232                          }
2233                          else
2234 <                            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 <                        }
2234 >                            return e.find(h, k);
2235                      }
2236 +                    if ((e = e.next) == null)
2237 +                        return null;
2238                  }
2239              }
1704        } finally {
1705            if (delta != 0L)
1706                addCount(delta, 2);
2240          }
1708        if (npe)
1709            throw new NullPointerException();
2241      }
2242  
2243      /**
2244 <     * Implementation for clear. Steps through each bin, removing all
1714 <     * nodes.
2244 >     * A place-holder node used in computeIfAbsent and compute.
2245       */
2246 <    @SuppressWarnings("unchecked") private final void internalClear() {
2247 <        long delta = 0L; // negative number of deletions
2248 <        int i = 0;
2249 <        Node<V>[] tab = table;
2250 <        while (tab != null && i < tab.length) {
2251 <            Node<V> f = tabAt(tab, i);
2252 <            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 <            }
2246 >    static final class ReservationNode<K,V> extends Node<K,V> {
2247 >        ReservationNode() {
2248 >            super(RESERVED, null, null);
2249 >        }
2250 >
2251 >        Node<K,V> find(int h, Object k) {
2252 >            return null;
2253          }
1763        if (delta != 0L)
1764            addCount(delta, -1);
2254      }
2255  
2256      /* ---------------- Table Initialization and Resizing -------------- */
2257  
2258      /**
2259 <     * Returns a power of two table size for the given desired capacity.
2260 <     * See Hackers Delight, sec 3.2
2259 >     * Returns the stamp bits for resizing a table of size n.
2260 >     * Must be negative when shifted left by RESIZE_STAMP_SHIFT.
2261       */
2262 <    private static final int tableSizeFor(int c) {
2263 <        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;
2262 >    static final int resizeStamp(int n) {
2263 >        return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
2264      }
2265  
2266      /**
2267       * Initializes table, using the size recorded in sizeCtl.
2268       */
2269 <    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
2270 <        Node<V>[] tab; int sc;
2271 <        while ((tab = table) == null) {
2269 >    private final Node<K,V>[] initTable() {
2270 >        Node<K,V>[] tab; int sc;
2271 >        while ((tab = table) == null || tab.length == 0) {
2272              if ((sc = sizeCtl) < 0)
2273                  Thread.yield(); // lost initialization race; just spin
2274              else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2275                  try {
2276 <                    if ((tab = table) == null) {
2276 >                    if ((tab = table) == null || tab.length == 0) {
2277                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2278 <                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2279 <                        table = tab = (Node<V>[])tb;
2278 >                        @SuppressWarnings("unchecked")
2279 >                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2280 >                        table = tab = nt;
2281                          sc = n - (n >>> 2);
2282                      }
2283                  } finally {
# Line 1816 | Line 2300 | public class ConcurrentHashMap<K, V>
2300       * @param check if <0, don't check resize, if <= 1 only check if uncontended
2301       */
2302      private final void addCount(long x, int check) {
2303 <        Cell[] as; long b, s;
2303 >        CounterCell[] as; long b, s;
2304          if ((as = counterCells) != null ||
2305              !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2306 <            Cell a; long v; int m;
2306 >            CounterCell a; long v; int m;
2307              boolean uncontended = true;
2308              if (as == null || (m = as.length - 1) < 0 ||
2309                  (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
# Line 1833 | Line 2317 | public class ConcurrentHashMap<K, V>
2317              s = sumCount();
2318          }
2319          if (check >= 0) {
2320 <            Node<V>[] tab, nt; int sc;
2320 >            Node<K,V>[] tab, nt; int n, sc;
2321              while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2322 <                   tab.length < MAXIMUM_CAPACITY) {
2322 >                   (n = tab.length) < MAXIMUM_CAPACITY) {
2323 >                int rs = resizeStamp(n);
2324                  if (sc < 0) {
2325 <                    if (sc == -1 || transferIndex <= transferOrigin ||
2326 <                        (nt = nextTable) == null)
2325 >                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2326 >                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
2327 >                        transferIndex <= 0)
2328                          break;
2329 <                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2329 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
2330                          transfer(tab, nt);
2331                  }
2332 <                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2332 >                else if (U.compareAndSwapInt(this, SIZECTL, sc,
2333 >                                             (rs << RESIZE_STAMP_SHIFT) + 2))
2334                      transfer(tab, null);
2335                  s = sumCount();
2336              }
# Line 1851 | Line 2338 | public class ConcurrentHashMap<K, V>
2338      }
2339  
2340      /**
2341 +     * Helps transfer if a resize is in progress.
2342 +     */
2343 +    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2344 +        Node<K,V>[] nextTab; int sc;
2345 +        if (tab != null && (f instanceof ForwardingNode) &&
2346 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2347 +            int rs = resizeStamp(tab.length);
2348 +            while (nextTab == nextTable && table == tab &&
2349 +                   (sc = sizeCtl) < 0) {
2350 +                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2351 +                    sc == rs + MAX_RESIZERS || transferIndex <= 0)
2352 +                    break;
2353 +                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
2354 +                    transfer(tab, nextTab);
2355 +                    break;
2356 +                }
2357 +            }
2358 +            return nextTab;
2359 +        }
2360 +        return table;
2361 +    }
2362 +
2363 +    /**
2364       * Tries to presize table to accommodate the given number of elements.
2365       *
2366       * @param size number of elements (doesn't need to be perfectly accurate)
2367       */
2368 <    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
2368 >    private final void tryPresize(int size) {
2369          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2370              tableSizeFor(size + (size >>> 1) + 1);
2371          int sc;
2372          while ((sc = sizeCtl) >= 0) {
2373 <            Node<V>[] tab = table; int n;
2373 >            Node<K,V>[] tab = table; int n;
2374              if (tab == null || (n = tab.length) == 0) {
2375                  n = (sc > c) ? sc : c;
2376                  if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2377                      try {
2378                          if (table == tab) {
2379 <                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2380 <                            table = (Node<V>[])tb;
2379 >                            @SuppressWarnings("unchecked")
2380 >                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2381 >                            table = nt;
2382                              sc = n - (n >>> 2);
2383                          }
2384                      } finally {
# Line 1877 | Line 2388 | public class ConcurrentHashMap<K, V>
2388              }
2389              else if (c <= sc || n >= MAXIMUM_CAPACITY)
2390                  break;
2391 <            else if (tab == table &&
2392 <                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2393 <                transfer(tab, null);
2391 >            else if (tab == table) {
2392 >                int rs = resizeStamp(n);
2393 >                if (U.compareAndSwapInt(this, SIZECTL, sc,
2394 >                                        (rs << RESIZE_STAMP_SHIFT) + 2))
2395 >                    transfer(tab, null);
2396 >            }
2397          }
2398      }
2399  
2400 <    /*
2400 >    /**
2401       * Moves and/or copies the nodes in each bin to new table. See
2402       * above for explanation.
2403       */
2404 <    @SuppressWarnings("unchecked") private final void transfer
1891 <        (Node<V>[] tab, Node<V>[] nextTab) {
2404 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2405          int n = tab.length, stride;
2406          if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2407              stride = MIN_TRANSFER_STRIDE; // subdivide range
2408          if (nextTab == null) {            // initiating
2409              try {
2410 <                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
2411 <                nextTab = (Node<V>[])tb;
2410 >                @SuppressWarnings("unchecked")
2411 >                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
2412 >                nextTab = nt;
2413              } catch (Throwable ex) {      // try to cope with OOME
2414                  sizeCtl = Integer.MAX_VALUE;
2415                  return;
2416              }
2417              nextTable = nextTab;
1904            transferOrigin = n;
2418              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            }
2419          }
2420          int nextn = nextTab.length;
2421 <        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2421 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2422          boolean advance = true;
2423 +        boolean finishing = false; // to ensure sweep before committing nextTab
2424          for (int i = 0, bound = 0;;) {
2425 <            int nextIndex, nextBound; Node<V> f; Object fk;
2425 >            Node<K,V> f; int fh;
2426              while (advance) {
2427 <                if (--i >= bound)
2427 >                int nextIndex, nextBound;
2428 >                if (--i >= bound || finishing)
2429                      advance = false;
2430 <                else if ((nextIndex = transferIndex) <= transferOrigin) {
2430 >                else if ((nextIndex = transferIndex) <= 0) {
2431                      i = -1;
2432                      advance = false;
2433                  }
# Line 1935 | Line 2441 | public class ConcurrentHashMap<K, V>
2441                  }
2442              }
2443              if (i < 0 || i >= n || i + n >= nextn) {
2444 <                for (int sc;;) {
2445 <                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2446 <                        if (sc == -1) {
2447 <                            nextTable = null;
2448 <                            table = nextTab;
2449 <                            sizeCtl = (n << 1) - (n >>> 1);
1944 <                        }
1945 <                        return;
1946 <                    }
2444 >                int sc;
2445 >                if (finishing) {
2446 >                    nextTable = null;
2447 >                    table = nextTab;
2448 >                    sizeCtl = (n << 1) - (n >>> 1);
2449 >                    return;
2450                  }
2451 <            }
2452 <            else if ((f = tabAt(tab, i)) == null) {
2453 <                if (casTabAt(tab, i, null, fwd)) {
2454 <                    setTabAt(nextTab, i, null);
2455 <                    setTabAt(nextTab, i + n, null);
1953 <                    advance = true;
2451 >                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
2452 >                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
2453 >                        return;
2454 >                    finishing = advance = true;
2455 >                    i = n; // recheck before commit
2456                  }
2457              }
2458 <            else if (f.hash >= 0) {
2458 >            else if ((f = tabAt(tab, i)) == null)
2459 >                advance = casTabAt(tab, i, null, fwd);
2460 >            else if ((fh = f.hash) == MOVED)
2461 >                advance = true; // already processed
2462 >            else {
2463                  synchronized (f) {
2464                      if (tabAt(tab, i) == f) {
2465 <                        int runBit = f.hash & n;
2466 <                        Node<V> lastRun = f, lo = null, hi = null;
2467 <                        for (Node<V> p = f.next; p != null; p = p.next) {
2468 <                            int b = p.hash & n;
2469 <                            if (b != runBit) {
2470 <                                runBit = b;
2471 <                                lastRun = p;
2465 >                        Node<K,V> ln, hn;
2466 >                        if (fh >= 0) {
2467 >                            int runBit = fh & n;
2468 >                            Node<K,V> lastRun = f;
2469 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2470 >                                int b = p.hash & n;
2471 >                                if (b != runBit) {
2472 >                                    runBit = b;
2473 >                                    lastRun = p;
2474 >                                }
2475                              }
2476 <                        }
2477 <                        if (runBit == 0)
2478 <                            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);
2476 >                            if (runBit == 0) {
2477 >                                ln = lastRun;
2478 >                                hn = null;
2479                              }
2480                              else {
2481 <                                ++hc;
2482 <                                ht.putTreeNode(h, k, v);
2481 >                                hn = lastRun;
2482 >                                ln = null;
2483                              }
2484 +                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2485 +                                int ph = p.hash; K pk = p.key; V pv = p.val;
2486 +                                if ((ph & n) == 0)
2487 +                                    ln = new Node<K,V>(ph, pk, pv, ln);
2488 +                                else
2489 +                                    hn = new Node<K,V>(ph, pk, pv, hn);
2490 +                            }
2491 +                            setTabAt(nextTab, i, ln);
2492 +                            setTabAt(nextTab, i + n, hn);
2493 +                            setTabAt(tab, i, fwd);
2494 +                            advance = true;
2495                          }
2496 <                        Node<V> ln, hn; // throw away trees if too small
2497 <                        if (lc < TREE_THRESHOLD) {
2498 <                            ln = null;
2499 <                            for (Node<V> p = lt.first; p != null; p = p.next)
2500 <                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2501 <                        }
2502 <                        else
2503 <                            ln = new Node<V>(MOVED, lt, null, null);
2504 <                        setTabAt(nextTab, i, ln);
2505 <                        if (hc < TREE_THRESHOLD) {
2506 <                            hn = null;
2507 <                            for (Node<V> p = ht.first; p != null; p = p.next)
2508 <                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2496 >                        else if (f instanceof TreeBin) {
2497 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2498 >                            TreeNode<K,V> lo = null, loTail = null;
2499 >                            TreeNode<K,V> hi = null, hiTail = null;
2500 >                            int lc = 0, hc = 0;
2501 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2502 >                                int h = e.hash;
2503 >                                TreeNode<K,V> p = new TreeNode<K,V>
2504 >                                    (h, e.key, e.val, null, null);
2505 >                                if ((h & n) == 0) {
2506 >                                    if ((p.prev = loTail) == null)
2507 >                                        lo = p;
2508 >                                    else
2509 >                                        loTail.next = p;
2510 >                                    loTail = p;
2511 >                                    ++lc;
2512 >                                }
2513 >                                else {
2514 >                                    if ((p.prev = hiTail) == null)
2515 >                                        hi = p;
2516 >                                    else
2517 >                                        hiTail.next = p;
2518 >                                    hiTail = p;
2519 >                                    ++hc;
2520 >                                }
2521 >                            }
2522 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2523 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2524 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2525 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2526 >                            setTabAt(nextTab, i, ln);
2527 >                            setTabAt(nextTab, i + n, hn);
2528 >                            setTabAt(tab, i, fwd);
2529 >                            advance = true;
2530                          }
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;
2531                      }
2027                } finally {
2028                    t.release(0);
2532                  }
2533              }
2031            else
2032                advance = true; // already processed
2534          }
2535      }
2536  
2537      /* ---------------- Counter support -------------- */
2538  
2539 +    /**
2540 +     * A padded cell for distributing counts.  Adapted from LongAdder
2541 +     * and Striped64.  See their internal docs for explanation.
2542 +     */
2543 +    @jdk.internal.vm.annotation.Contended static final class CounterCell {
2544 +        volatile long value;
2545 +        CounterCell(long x) { value = x; }
2546 +    }
2547 +
2548      final long sumCount() {
2549 <        Cell[] as = counterCells; Cell a;
2549 >        CounterCell[] as = counterCells; CounterCell a;
2550          long sum = baseCount;
2551          if (as != null) {
2552              for (int i = 0; i < as.length; ++i) {
# Line 2057 | Line 2567 | public class ConcurrentHashMap<K, V>
2567          }
2568          boolean collide = false;                // True if last slot nonempty
2569          for (;;) {
2570 <            Cell[] as; Cell a; int n; long v;
2570 >            CounterCell[] as; CounterCell a; int n; long v;
2571              if ((as = counterCells) != null && (n = as.length) > 0) {
2572                  if ((a = as[(n - 1) & h]) == null) {
2573                      if (cellsBusy == 0) {            // Try to attach new Cell
2574 <                        Cell r = new Cell(x); // Optimistic create
2574 >                        CounterCell r = new CounterCell(x); // Optimistic create
2575                          if (cellsBusy == 0 &&
2576                              U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2577                              boolean created = false;
2578                              try {               // Recheck under lock
2579 <                                Cell[] rs; int m, j;
2579 >                                CounterCell[] rs; int m, j;
2580                                  if ((rs = counterCells) != null &&
2581                                      (m = rs.length) > 0 &&
2582                                      rs[j = (m - 1) & h] == null) {
# Line 2095 | Line 2605 | public class ConcurrentHashMap<K, V>
2605                           U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2606                      try {
2607                          if (counterCells == as) {// Expand table unless stale
2608 <                            Cell[] rs = new Cell[n << 1];
2608 >                            CounterCell[] rs = new CounterCell[n << 1];
2609                              for (int i = 0; i < n; ++i)
2610                                  rs[i] = as[i];
2611                              counterCells = rs;
# Line 2113 | Line 2623 | public class ConcurrentHashMap<K, V>
2623                  boolean init = false;
2624                  try {                           // Initialize table
2625                      if (counterCells == as) {
2626 <                        Cell[] rs = new Cell[2];
2627 <                        rs[h & 1] = new Cell(x);
2626 >                        CounterCell[] rs = new CounterCell[2];
2627 >                        rs[h & 1] = new CounterCell(x);
2628                          counterCells = rs;
2629                          init = true;
2630                      }
# Line 2129 | Line 2639 | public class ConcurrentHashMap<K, V>
2639          }
2640      }
2641  
2642 <    /* ----------------Table Traversal -------------- */
2642 >    /* ---------------- Conversion from/to TreeBins -------------- */
2643  
2644      /**
2645 <     * Encapsulates traversal for methods such as containsValue; also
2646 <     * serves as a base class for other iterators and bulk tasks.
2647 <     *
2648 <     * At each step, the iterator snapshots the key ("nextKey") and
2649 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2650 <     * snapshot, has a non-null user value). Because val fields can
2651 <     * change (including to null, indicating deletion), field nextVal
2652 <     * might not be accurate at point of use, but still maintains the
2653 <     * weak consistency property of holding a value that was once
2654 <     * valid. To support iterator.remove, the nextKey field is not
2655 <     * updated (nulled out) when the iterator cannot advance.
2656 <     *
2657 <     * Internal traversals directly access these fields, as in:
2658 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2659 <     *
2660 <     * Exported iterators must track whether the iterator has advanced
2661 <     * (in hasNext vs next) (by setting/checking/nulling field
2662 <     * nextVal), and then extract key, value, or key-value pairs as
2663 <     * return values of next().
2664 <     *
2665 <     * 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 <        Object 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
2645 >     * Replaces all linked nodes in bin at given index unless table is
2646 >     * too small, in which case resizes instead.
2647 >     */
2648 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2649 >        Node<K,V> b; int n;
2650 >        if (tab != null) {
2651 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
2652 >                tryPresize(n << 1);
2653 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2654 >                synchronized (b) {
2655 >                    if (tabAt(tab, index) == b) {
2656 >                        TreeNode<K,V> hd = null, tl = null;
2657 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2658 >                            TreeNode<K,V> p =
2659 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2660 >                                                  null, null);
2661 >                            if ((p.prev = tl) == null)
2662 >                                hd = p;
2663 >                            else
2664 >                                tl.next = p;
2665 >                            tl = p;
2666                          }
2667 <                    }                           // visit upper slots if present
2668 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2667 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2668 >                    }
2669                  }
2670 <                nextKey = 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 <            Object 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;
2670 >            }
2671          }
2672      }
2673  
2343    /* ---------------- Public operations -------------- */
2344
2674      /**
2675 <     * Creates a new, empty map with the default initial table size (16).
2675 >     * Returns a list of non-TreeNodes replacing those in given list.
2676       */
2677 <    public ConcurrentHashMap() {
2678 <    }
2679 <
2680 <    /**
2681 <     * Creates a new, empty map with an initial table size
2682 <     * accommodating the specified number of elements without the need
2683 <     * to dynamically resize.
2684 <     *
2685 <     * @param initialCapacity The implementation performs internal
2686 <     * sizing to accommodate this many elements.
2687 <     * @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;
2677 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2678 >        Node<K,V> hd = null, tl = null;
2679 >        for (Node<K,V> q = b; q != null; q = q.next) {
2680 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val);
2681 >            if (tl == null)
2682 >                hd = p;
2683 >            else
2684 >                tl.next = p;
2685 >            tl = p;
2686 >        }
2687 >        return hd;
2688      }
2689  
2690 <    /**
2371 <     * Creates a new map with the same mappings as the given map.
2372 <     *
2373 <     * @param m the map
2374 <     */
2375 <    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2376 <        this.sizeCtl = DEFAULT_CAPACITY;
2377 <        internalPutAll(m);
2378 <    }
2690 >    /* ---------------- TreeNodes -------------- */
2691  
2692      /**
2693 <     * 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
2693 >     * Nodes for use in TreeBins.
2694       */
2695 <    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
2696 <        this(initialCapacity, loadFactor, 1);
2697 <    }
2698 <
2699 <    /**
2700 <     * 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
2416 <     */
2417 <    public ConcurrentHashMap(int initialCapacity,
2418 <                               float loadFactor, int concurrencyLevel) {
2419 <        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2420 <            throw new IllegalArgumentException();
2421 <        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2422 <            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 <    }
2695 >    static final class TreeNode<K,V> extends Node<K,V> {
2696 >        TreeNode<K,V> parent;  // red-black tree links
2697 >        TreeNode<K,V> left;
2698 >        TreeNode<K,V> right;
2699 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2700 >        boolean red;
2701  
2702 <    /**
2703 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2704 <     * from the given type to {@code Boolean.TRUE}.
2705 <     *
2706 <     * @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 <    }
2702 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2703 >                 TreeNode<K,V> parent) {
2704 >            super(hash, key, val, next);
2705 >            this.parent = parent;
2706 >        }
2707  
2708 <    /**
2709 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2710 <     * 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 <    }
2708 >        Node<K,V> find(int h, Object k) {
2709 >            return findTreeNode(h, k, null);
2710 >        }
2711  
2712 <    /**
2713 <     * {@inheritDoc}
2714 <     */
2715 <    public boolean isEmpty() {
2716 <        return sumCount() <= 0L; // ignore transient negative values
2712 >        /**
2713 >         * Returns the TreeNode (or null if not found) for the given key
2714 >         * starting at given root.
2715 >         */
2716 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2717 >            if (k != null) {
2718 >                TreeNode<K,V> p = this;
2719 >                do {
2720 >                    int ph, dir; K pk; TreeNode<K,V> q;
2721 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2722 >                    if ((ph = p.hash) > h)
2723 >                        p = pl;
2724 >                    else if (ph < h)
2725 >                        p = pr;
2726 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2727 >                        return p;
2728 >                    else if (pl == null)
2729 >                        p = pr;
2730 >                    else if (pr == null)
2731 >                        p = pl;
2732 >                    else if ((kc != null ||
2733 >                              (kc = comparableClassFor(k)) != null) &&
2734 >                             (dir = compareComparables(kc, k, pk)) != 0)
2735 >                        p = (dir < 0) ? pl : pr;
2736 >                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
2737 >                        return q;
2738 >                    else
2739 >                        p = pl;
2740 >                } while (p != null);
2741 >            }
2742 >            return null;
2743 >        }
2744      }
2745  
2746 <    /**
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 <    }
2746 >    /* ---------------- TreeBins -------------- */
2747  
2748      /**
2749 <     * Returns the number of mappings. This method should be used
2750 <     * instead of {@link #size} because a ConcurrentHashMap may
2751 <     * contain more mappings than can be represented as an int. The
2752 <     * value returned is an estimate; the actual count may differ if
2753 <     * there are concurrent insertions or removals.
2754 <     *
2755 <     * @return the number of mappings
2756 <     */
2757 <    public long mappingCount() {
2758 <        long n = sumCount();
2759 <        return (n < 0L) ? 0L : n; // ignore transient negative values
2760 <    }
2749 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2750 >     * keys or values, but instead point to list of TreeNodes and
2751 >     * their root. They also maintain a parasitic read-write lock
2752 >     * forcing writers (who hold bin lock) to wait for readers (who do
2753 >     * not) to complete before tree restructuring operations.
2754 >     */
2755 >    static final class TreeBin<K,V> extends Node<K,V> {
2756 >        TreeNode<K,V> root;
2757 >        volatile TreeNode<K,V> first;
2758 >        volatile Thread waiter;
2759 >        volatile int lockState;
2760 >        // values for lockState
2761 >        static final int WRITER = 1; // set while holding write lock
2762 >        static final int WAITER = 2; // set when waiting for write lock
2763 >        static final int READER = 4; // increment value for setting read lock
2764 >
2765 >        /**
2766 >         * Tie-breaking utility for ordering insertions when equal
2767 >         * hashCodes and non-comparable. We don't require a total
2768 >         * order, just a consistent insertion rule to maintain
2769 >         * equivalence across rebalancings. Tie-breaking further than
2770 >         * necessary simplifies testing a bit.
2771 >         */
2772 >        static int tieBreakOrder(Object a, Object b) {
2773 >            int d;
2774 >            if (a == null || b == null ||
2775 >                (d = a.getClass().getName().
2776 >                 compareTo(b.getClass().getName())) == 0)
2777 >                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2778 >                     -1 : 1);
2779 >            return d;
2780 >        }
2781  
2782 <    /**
2783 <     * Returns the value to which the specified key is mapped,
2784 <     * or {@code null} if this map contains no mapping for the key.
2785 <     *
2786 <     * <p>More formally, if this map contains a mapping from a key
2787 <     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2788 <     * then this method returns {@code v}; otherwise it returns
2789 <     * {@code null}.  (There can be at most one such mapping.)
2790 <     *
2791 <     * @throws NullPointerException if the specified key is null
2792 <     */
2793 <    public V get(Object key) {
2794 <        return internalGet(key);
2795 <    }
2782 >        /**
2783 >         * Creates bin with initial set of nodes headed by b.
2784 >         */
2785 >        TreeBin(TreeNode<K,V> b) {
2786 >            super(TREEBIN, null, null);
2787 >            this.first = b;
2788 >            TreeNode<K,V> r = null;
2789 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2790 >                next = (TreeNode<K,V>)x.next;
2791 >                x.left = x.right = null;
2792 >                if (r == null) {
2793 >                    x.parent = null;
2794 >                    x.red = false;
2795 >                    r = x;
2796 >                }
2797 >                else {
2798 >                    K k = x.key;
2799 >                    int h = x.hash;
2800 >                    Class<?> kc = null;
2801 >                    for (TreeNode<K,V> p = r;;) {
2802 >                        int dir, ph;
2803 >                        K pk = p.key;
2804 >                        if ((ph = p.hash) > h)
2805 >                            dir = -1;
2806 >                        else if (ph < h)
2807 >                            dir = 1;
2808 >                        else if ((kc == null &&
2809 >                                  (kc = comparableClassFor(k)) == null) ||
2810 >                                 (dir = compareComparables(kc, k, pk)) == 0)
2811 >                            dir = tieBreakOrder(k, pk);
2812 >                        TreeNode<K,V> xp = p;
2813 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2814 >                            x.parent = xp;
2815 >                            if (dir <= 0)
2816 >                                xp.left = x;
2817 >                            else
2818 >                                xp.right = x;
2819 >                            r = balanceInsertion(r, x);
2820 >                            break;
2821 >                        }
2822 >                    }
2823 >                }
2824 >            }
2825 >            this.root = r;
2826 >            assert checkInvariants(root);
2827 >        }
2828  
2829 <    /**
2830 <     * Returns the value to which the specified key is mapped,
2831 <     * or the given defaultValue if this map contains no mapping for the key.
2832 <     *
2833 <     * @param key the key
2834 <     * @param defaultValue the value to return if this map contains
2835 <     * 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 <    }
2829 >        /**
2830 >         * Acquires write lock for tree restructuring.
2831 >         */
2832 >        private final void lockRoot() {
2833 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2834 >                contendedLock(); // offload to separate method
2835 >        }
2836  
2837 <    /**
2838 <     * Tests if the specified object is a key in this table.
2839 <     *
2840 <     * @param  key   possible key
2841 <     * @return {@code true} if and only if the specified object
2842 <     *         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 <    }
2837 >        /**
2838 >         * Releases write lock for tree restructuring.
2839 >         */
2840 >        private final void unlockRoot() {
2841 >            lockState = 0;
2842 >        }
2843  
2844 <    /**
2845 <     * Returns {@code true} if this map maps one or more keys to the
2846 <     * specified value. Note: This method may require a full traversal
2847 <     * of the map, and is much slower than method {@code containsKey}.
2848 <     *
2849 <     * @param value value whose presence in this map is to be tested
2850 <     * @return {@code true} if this map maps one or more keys to the
2851 <     *         specified value
2852 <     * @throws NullPointerException if the specified value is null
2853 <     */
2854 <    public boolean containsValue(Object value) {
2855 <        if (value == null)
2856 <            throw new NullPointerException();
2857 <        V v;
2858 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2859 <        while ((v = it.advance()) != null) {
2860 <            if (v == value || value.equals(v))
2861 <                return true;
2844 >        /**
2845 >         * Possibly blocks awaiting root lock.
2846 >         */
2847 >        private final void contendedLock() {
2848 >            boolean waiting = false;
2849 >            for (int s;;) {
2850 >                if (((s = lockState) & ~WAITER) == 0) {
2851 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2852 >                        if (waiting)
2853 >                            waiter = null;
2854 >                        return;
2855 >                    }
2856 >                }
2857 >                else if ((s & WAITER) == 0) {
2858 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2859 >                        waiting = true;
2860 >                        waiter = Thread.currentThread();
2861 >                    }
2862 >                }
2863 >                else if (waiting)
2864 >                    LockSupport.park(this);
2865 >            }
2866          }
2548        return false;
2549    }
2867  
2868 <    /**
2869 <     * Legacy method testing if some key maps into the specified value
2870 <     * in this table.  This method is identical in functionality to
2871 <     * {@link #containsValue}, and exists solely to ensure
2872 <     * full compatibility with class {@link java.util.Hashtable},
2873 <     * which supported this method prior to introduction of the
2874 <     * Java Collections framework.
2875 <     *
2876 <     * @param  value a value to search for
2877 <     * @return {@code true} if and only if some key maps to the
2878 <     *         {@code value} argument in this table as
2879 <     *         determined by the {@code equals} method;
2880 <     *         {@code false} otherwise
2881 <     * @throws NullPointerException if the specified value is null
2882 <     */
2883 <    @Deprecated public boolean contains(Object value) {
2884 <        return containsValue(value);
2885 <    }
2868 >        /**
2869 >         * Returns matching node or null if none. Tries to search
2870 >         * using tree comparisons from root, but continues linear
2871 >         * search when lock not available.
2872 >         */
2873 >        final Node<K,V> find(int h, Object k) {
2874 >            if (k != null) {
2875 >                for (Node<K,V> e = first; e != null; ) {
2876 >                    int s; K ek;
2877 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2878 >                        if (e.hash == h &&
2879 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2880 >                            return e;
2881 >                        e = e.next;
2882 >                    }
2883 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2884 >                                                 s + READER)) {
2885 >                        TreeNode<K,V> r, p;
2886 >                        try {
2887 >                            p = ((r = root) == null ? null :
2888 >                                 r.findTreeNode(h, k, null));
2889 >                        } finally {
2890 >                            Thread w;
2891 >                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2892 >                                (READER|WAITER) && (w = waiter) != null)
2893 >                                LockSupport.unpark(w);
2894 >                        }
2895 >                        return p;
2896 >                    }
2897 >                }
2898 >            }
2899 >            return null;
2900 >        }
2901  
2902 <    /**
2903 <     * Maps the specified key to the specified value in this table.
2904 <     * Neither the key nor the value can be null.
2905 <     *
2906 <     * <p>The value can be retrieved by calling the {@code get} method
2907 <     * with a key that is equal to the original key.
2908 <     *
2909 <     * @param key key with which the specified value is to be associated
2910 <     * @param value value to be associated with the specified key
2911 <     * @return the previous value associated with {@code key}, or
2912 <     *         {@code null} if there was no mapping for {@code key}
2913 <     * @throws NullPointerException if the specified key or value is null
2914 <     */
2915 <    public V put(K key, V value) {
2916 <        return internalPut(key, value, false);
2917 <    }
2902 >        /**
2903 >         * Finds or adds a node.
2904 >         * @return null if added
2905 >         */
2906 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2907 >            Class<?> kc = null;
2908 >            boolean searched = false;
2909 >            for (TreeNode<K,V> p = root;;) {
2910 >                int dir, ph; K pk;
2911 >                if (p == null) {
2912 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2913 >                    break;
2914 >                }
2915 >                else if ((ph = p.hash) > h)
2916 >                    dir = -1;
2917 >                else if (ph < h)
2918 >                    dir = 1;
2919 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2920 >                    return p;
2921 >                else if ((kc == null &&
2922 >                          (kc = comparableClassFor(k)) == null) ||
2923 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2924 >                    if (!searched) {
2925 >                        TreeNode<K,V> q, ch;
2926 >                        searched = true;
2927 >                        if (((ch = p.left) != null &&
2928 >                             (q = ch.findTreeNode(h, k, kc)) != null) ||
2929 >                            ((ch = p.right) != null &&
2930 >                             (q = ch.findTreeNode(h, k, kc)) != null))
2931 >                            return q;
2932 >                    }
2933 >                    dir = tieBreakOrder(k, pk);
2934 >                }
2935 >
2936 >                TreeNode<K,V> xp = p;
2937 >                if ((p = (dir <= 0) ? p.left : p.right) == null) {
2938 >                    TreeNode<K,V> x, f = first;
2939 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2940 >                    if (f != null)
2941 >                        f.prev = x;
2942 >                    if (dir <= 0)
2943 >                        xp.left = x;
2944 >                    else
2945 >                        xp.right = x;
2946 >                    if (!xp.red)
2947 >                        x.red = true;
2948 >                    else {
2949 >                        lockRoot();
2950 >                        try {
2951 >                            root = balanceInsertion(root, x);
2952 >                        } finally {
2953 >                            unlockRoot();
2954 >                        }
2955 >                    }
2956 >                    break;
2957 >                }
2958 >            }
2959 >            assert checkInvariants(root);
2960 >            return null;
2961 >        }
2962  
2963 <    /**
2964 <     * {@inheritDoc}
2965 <     *
2966 <     * @return the previous value associated with the specified key,
2967 <     *         or {@code null} if there was no mapping for the key
2968 <     * @throws NullPointerException if the specified key or value is null
2969 <     */
2970 <    public V putIfAbsent(K key, V value) {
2971 <        return internalPut(key, value, true);
2972 <    }
2963 >        /**
2964 >         * Removes the given node, that must be present before this
2965 >         * call.  This is messier than typical red-black deletion code
2966 >         * because we cannot swap the contents of an interior node
2967 >         * with a leaf successor that is pinned by "next" pointers
2968 >         * that are accessible independently of lock. So instead we
2969 >         * swap the tree linkages.
2970 >         *
2971 >         * @return true if now too small, so should be untreeified
2972 >         */
2973 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2974 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2975 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2976 >            TreeNode<K,V> r, rl;
2977 >            if (pred == null)
2978 >                first = next;
2979 >            else
2980 >                pred.next = next;
2981 >            if (next != null)
2982 >                next.prev = pred;
2983 >            if (first == null) {
2984 >                root = null;
2985 >                return true;
2986 >            }
2987 >            if ((r = root) == null || r.right == null || // too small
2988 >                (rl = r.left) == null || rl.left == null)
2989 >                return true;
2990 >            lockRoot();
2991 >            try {
2992 >                TreeNode<K,V> replacement;
2993 >                TreeNode<K,V> pl = p.left;
2994 >                TreeNode<K,V> pr = p.right;
2995 >                if (pl != null && pr != null) {
2996 >                    TreeNode<K,V> s = pr, sl;
2997 >                    while ((sl = s.left) != null) // find successor
2998 >                        s = sl;
2999 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
3000 >                    TreeNode<K,V> sr = s.right;
3001 >                    TreeNode<K,V> pp = p.parent;
3002 >                    if (s == pr) { // p was s's direct parent
3003 >                        p.parent = s;
3004 >                        s.right = p;
3005 >                    }
3006 >                    else {
3007 >                        TreeNode<K,V> sp = s.parent;
3008 >                        if ((p.parent = sp) != null) {
3009 >                            if (s == sp.left)
3010 >                                sp.left = p;
3011 >                            else
3012 >                                sp.right = p;
3013 >                        }
3014 >                        if ((s.right = pr) != null)
3015 >                            pr.parent = s;
3016 >                    }
3017 >                    p.left = null;
3018 >                    if ((p.right = sr) != null)
3019 >                        sr.parent = p;
3020 >                    if ((s.left = pl) != null)
3021 >                        pl.parent = s;
3022 >                    if ((s.parent = pp) == null)
3023 >                        r = s;
3024 >                    else if (p == pp.left)
3025 >                        pp.left = s;
3026 >                    else
3027 >                        pp.right = s;
3028 >                    if (sr != null)
3029 >                        replacement = sr;
3030 >                    else
3031 >                        replacement = p;
3032 >                }
3033 >                else if (pl != null)
3034 >                    replacement = pl;
3035 >                else if (pr != null)
3036 >                    replacement = pr;
3037 >                else
3038 >                    replacement = p;
3039 >                if (replacement != p) {
3040 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
3041 >                    if (pp == null)
3042 >                        r = replacement;
3043 >                    else if (p == pp.left)
3044 >                        pp.left = replacement;
3045 >                    else
3046 >                        pp.right = replacement;
3047 >                    p.left = p.right = p.parent = null;
3048 >                }
3049  
3050 <    /**
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 <    }
3050 >                root = (p.red) ? r : balanceDeletion(r, replacement);
3051  
3052 <    /**
3053 <     * If the specified key is not already associated with a value (or
3054 <     * is mapped to {@code null}), attempts to compute its value using
3055 <     * the given mapping function and enters it into this map unless
3056 <     * {@code null}. The entire method invocation is performed
3057 <     * atomically, so the function is applied at most once per key.
3058 <     * Some attempted update operations on this map by other threads
3059 <     * may be blocked while computation is in progress, so the
3060 <     * computation should be short and simple, and must not attempt to
3061 <     * update any other mappings of this Map.
3062 <     *
3063 <     * @param key key with which the specified value is to be associated
3064 <     * @param mappingFunction the function to compute a value
3065 <     * @return the current (existing or computed) value associated with
3066 <     *         the specified key, or null if the computed value is null
3067 <     * @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 <    }
3052 >                if (p == replacement) {  // detach pointers
3053 >                    TreeNode<K,V> pp;
3054 >                    if ((pp = p.parent) != null) {
3055 >                        if (p == pp.left)
3056 >                            pp.left = null;
3057 >                        else if (p == pp.right)
3058 >                            pp.right = null;
3059 >                        p.parent = null;
3060 >                    }
3061 >                }
3062 >            } finally {
3063 >                unlockRoot();
3064 >            }
3065 >            assert checkInvariants(root);
3066 >            return false;
3067 >        }
3068  
3069 <    /**
3070 <     * 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 <    }
3069 >        /* ------------------------------------------------------------ */
3070 >        // Red-black tree methods, all adapted from CLR
3071  
3072 <    /**
3073 <     * Attempts to compute a mapping for the specified key and its
3074 <     * current mapped value (or {@code null} if there is no current
3075 <     * mapping). The entire method invocation is performed atomically.
3076 <     * Some attempted update operations on this map by other threads
3077 <     * may be blocked while computation is in progress, so the
3078 <     * computation should be short and simple, and must not attempt to
3079 <     * update any other mappings of this Map.
3080 <     *
3081 <     * @param key key with which the specified value is to be associated
3082 <     * @param remappingFunction the function to compute a value
3083 <     * @return the new value associated with the specified key, or null if none
3084 <     * @throws NullPointerException if the specified key or remappingFunction
3085 <     *         is null
3086 <     * @throws IllegalStateException if the computation detectably
3087 <     *         attempts a recursive update to this map that would
3088 <     *         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 <    }
3072 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
3073 >                                              TreeNode<K,V> p) {
3074 >            TreeNode<K,V> r, pp, rl;
3075 >            if (p != null && (r = p.right) != null) {
3076 >                if ((rl = p.right = r.left) != null)
3077 >                    rl.parent = p;
3078 >                if ((pp = r.parent = p.parent) == null)
3079 >                    (root = r).red = false;
3080 >                else if (pp.left == p)
3081 >                    pp.left = r;
3082 >                else
3083 >                    pp.right = r;
3084 >                r.left = p;
3085 >                p.parent = r;
3086 >            }
3087 >            return root;
3088 >        }
3089  
3090 <    /**
3091 <     * If the specified key is not already associated with a
3092 <     * (non-null) value, associates it with the given value.
3093 <     * Otherwise, replaces the value with the results of the given
3094 <     * remapping function, or removes if {@code null}. The entire
3095 <     * method invocation is performed atomically.  Some attempted
3096 <     * update operations on this map by other threads may be blocked
3097 <     * while computation is in progress, so the computation should be
3098 <     * short and simple, and must not attempt to update any other
3099 <     * mappings of this Map.
3100 <     *
3101 <     * @param key key with which the specified value is to be associated
3102 <     * @param value the value to use if absent
3103 <     * @param remappingFunction the function to recompute a value if present
3104 <     * @return the new value associated with the specified key, or null if none
3105 <     * @throws NullPointerException if the specified key or the
3106 <     *         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 <    }
3090 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
3091 >                                               TreeNode<K,V> p) {
3092 >            TreeNode<K,V> l, pp, lr;
3093 >            if (p != null && (l = p.left) != null) {
3094 >                if ((lr = p.left = l.right) != null)
3095 >                    lr.parent = p;
3096 >                if ((pp = l.parent = p.parent) == null)
3097 >                    (root = l).red = false;
3098 >                else if (pp.right == p)
3099 >                    pp.right = l;
3100 >                else
3101 >                    pp.left = l;
3102 >                l.right = p;
3103 >                p.parent = l;
3104 >            }
3105 >            return root;
3106 >        }
3107  
3108 <    /**
3109 <     * Removes the key (and its corresponding value) from this map.
3110 <     * This method does nothing if the key is not in the map.
3111 <     *
3112 <     * @param  key the key that needs to be removed
3113 <     * @return the previous value associated with {@code key}, or
3114 <     *         {@code null} if there was no mapping for {@code key}
3115 <     * @throws NullPointerException if the specified key is null
3116 <     */
3117 <    public V remove(Object key) {
3118 <        return internalReplace(key, null, null);
3119 <    }
3108 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
3109 >                                                    TreeNode<K,V> x) {
3110 >            x.red = true;
3111 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
3112 >                if ((xp = x.parent) == null) {
3113 >                    x.red = false;
3114 >                    return x;
3115 >                }
3116 >                else if (!xp.red || (xpp = xp.parent) == null)
3117 >                    return root;
3118 >                if (xp == (xppl = xpp.left)) {
3119 >                    if ((xppr = xpp.right) != null && xppr.red) {
3120 >                        xppr.red = false;
3121 >                        xp.red = false;
3122 >                        xpp.red = true;
3123 >                        x = xpp;
3124 >                    }
3125 >                    else {
3126 >                        if (x == xp.right) {
3127 >                            root = rotateLeft(root, x = xp);
3128 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3129 >                        }
3130 >                        if (xp != null) {
3131 >                            xp.red = false;
3132 >                            if (xpp != null) {
3133 >                                xpp.red = true;
3134 >                                root = rotateRight(root, xpp);
3135 >                            }
3136 >                        }
3137 >                    }
3138 >                }
3139 >                else {
3140 >                    if (xppl != null && xppl.red) {
3141 >                        xppl.red = false;
3142 >                        xp.red = false;
3143 >                        xpp.red = true;
3144 >                        x = xpp;
3145 >                    }
3146 >                    else {
3147 >                        if (x == xp.left) {
3148 >                            root = rotateRight(root, x = xp);
3149 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3150 >                        }
3151 >                        if (xp != null) {
3152 >                            xp.red = false;
3153 >                            if (xpp != null) {
3154 >                                xpp.red = true;
3155 >                                root = rotateLeft(root, xpp);
3156 >                            }
3157 >                        }
3158 >                    }
3159 >                }
3160 >            }
3161 >        }
3162  
3163 <    /**
3164 <     * {@inheritDoc}
3165 <     *
3166 <     * @throws NullPointerException if the specified key is null
3167 <     */
3168 <    public boolean remove(Object key, Object value) {
3169 <        if (key == null)
3170 <            throw new NullPointerException();
3171 <        return value != null && internalReplace(key, null, value) != null;
3172 <    }
3163 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3164 >                                                   TreeNode<K,V> x) {
3165 >            for (TreeNode<K,V> xp, xpl, xpr;;) {
3166 >                if (x == null || x == root)
3167 >                    return root;
3168 >                else if ((xp = x.parent) == null) {
3169 >                    x.red = false;
3170 >                    return x;
3171 >                }
3172 >                else if (x.red) {
3173 >                    x.red = false;
3174 >                    return root;
3175 >                }
3176 >                else if ((xpl = xp.left) == x) {
3177 >                    if ((xpr = xp.right) != null && xpr.red) {
3178 >                        xpr.red = false;
3179 >                        xp.red = true;
3180 >                        root = rotateLeft(root, xp);
3181 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3182 >                    }
3183 >                    if (xpr == null)
3184 >                        x = xp;
3185 >                    else {
3186 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3187 >                        if ((sr == null || !sr.red) &&
3188 >                            (sl == null || !sl.red)) {
3189 >                            xpr.red = true;
3190 >                            x = xp;
3191 >                        }
3192 >                        else {
3193 >                            if (sr == null || !sr.red) {
3194 >                                if (sl != null)
3195 >                                    sl.red = false;
3196 >                                xpr.red = true;
3197 >                                root = rotateRight(root, xpr);
3198 >                                xpr = (xp = x.parent) == null ?
3199 >                                    null : xp.right;
3200 >                            }
3201 >                            if (xpr != null) {
3202 >                                xpr.red = (xp == null) ? false : xp.red;
3203 >                                if ((sr = xpr.right) != null)
3204 >                                    sr.red = false;
3205 >                            }
3206 >                            if (xp != null) {
3207 >                                xp.red = false;
3208 >                                root = rotateLeft(root, xp);
3209 >                            }
3210 >                            x = root;
3211 >                        }
3212 >                    }
3213 >                }
3214 >                else { // symmetric
3215 >                    if (xpl != null && xpl.red) {
3216 >                        xpl.red = false;
3217 >                        xp.red = true;
3218 >                        root = rotateRight(root, xp);
3219 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3220 >                    }
3221 >                    if (xpl == null)
3222 >                        x = xp;
3223 >                    else {
3224 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3225 >                        if ((sl == null || !sl.red) &&
3226 >                            (sr == null || !sr.red)) {
3227 >                            xpl.red = true;
3228 >                            x = xp;
3229 >                        }
3230 >                        else {
3231 >                            if (sl == null || !sl.red) {
3232 >                                if (sr != null)
3233 >                                    sr.red = false;
3234 >                                xpl.red = true;
3235 >                                root = rotateLeft(root, xpl);
3236 >                                xpl = (xp = x.parent) == null ?
3237 >                                    null : xp.left;
3238 >                            }
3239 >                            if (xpl != null) {
3240 >                                xpl.red = (xp == null) ? false : xp.red;
3241 >                                if ((sl = xpl.left) != null)
3242 >                                    sl.red = false;
3243 >                            }
3244 >                            if (xp != null) {
3245 >                                xp.red = false;
3246 >                                root = rotateRight(root, xp);
3247 >                            }
3248 >                            x = root;
3249 >                        }
3250 >                    }
3251 >                }
3252 >            }
3253 >        }
3254  
3255 <    /**
3256 <     * {@inheritDoc}
3257 <     *
3258 <     * @throws NullPointerException if any of the arguments are null
3259 <     */
3260 <    public boolean replace(K key, V oldValue, V newValue) {
3261 <        if (key == null || oldValue == null || newValue == null)
3262 <            throw new NullPointerException();
3263 <        return internalReplace(key, newValue, oldValue) != null;
3264 <    }
3255 >        /**
3256 >         * Checks invariants recursively for the tree of Nodes rooted at t.
3257 >         */
3258 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3259 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3260 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3261 >            if (tb != null && tb.next != t)
3262 >                return false;
3263 >            if (tn != null && tn.prev != t)
3264 >                return false;
3265 >            if (tp != null && t != tp.left && t != tp.right)
3266 >                return false;
3267 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3268 >                return false;
3269 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3270 >                return false;
3271 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3272 >                return false;
3273 >            if (tl != null && !checkInvariants(tl))
3274 >                return false;
3275 >            if (tr != null && !checkInvariants(tr))
3276 >                return false;
3277 >            return true;
3278 >        }
3279  
3280 <    /**
3281 <     * {@inheritDoc}
3282 <     *
3283 <     * @return the previous value associated with the specified key,
3284 <     *         or {@code null} if there was no mapping for the key
3285 <     * @throws NullPointerException if the specified key or value is null
3286 <     */
3287 <    public V replace(K key, V value) {
3288 <        if (key == null || value == null)
3289 <            throw new NullPointerException();
2758 <        return internalReplace(key, value, null);
3280 >        private static final Unsafe U = Unsafe.getUnsafe();
3281 >        private static final long LOCKSTATE;
3282 >        static {
3283 >            try {
3284 >                LOCKSTATE = U.objectFieldOffset
3285 >                    (TreeBin.class.getDeclaredField("lockState"));
3286 >            } catch (ReflectiveOperationException e) {
3287 >                throw new Error(e);
3288 >            }
3289 >        }
3290      }
3291  
3292 <    /**
2762 <     * Removes all of the mappings from this map.
2763 <     */
2764 <    public void clear() {
2765 <        internalClear();
2766 <    }
3292 >    /* ----------------Table Traversal -------------- */
3293  
3294      /**
3295 <     * Returns a {@link Set} view of the keys contained in this map.
3296 <     * The set is backed by the map, so changes to the map are
3297 <     * reflected in the set, and vice-versa.
3298 <     *
3299 <     * @return the set view
3300 <     */
3301 <    public KeySetView<K,V> keySet() {
3302 <        KeySetView<K,V> ks = keySet;
3303 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
3295 >     * Records the table, its length, and current traversal index for a
3296 >     * traverser that must process a region of a forwarded table before
3297 >     * proceeding with current table.
3298 >     */
3299 >    static final class TableStack<K,V> {
3300 >        int length;
3301 >        int index;
3302 >        Node<K,V>[] tab;
3303 >        TableStack<K,V> next;
3304      }
3305  
3306      /**
3307 <     * Returns a {@link Set} view of the keys in this map, using the
3308 <     * given common mapped value for any additions (i.e., {@link
2783 <     * Collection#add} and {@link Collection#addAll}). This is of
2784 <     * course only appropriate if it is acceptable to use the same
2785 <     * value for all additions from this view.
3307 >     * Encapsulates traversal for methods such as containsValue; also
3308 >     * serves as a base class for other iterators and spliterators.
3309       *
3310 <     * @param mappedValue the mapped value to use for any
3311 <     * additions.
3312 <     * @return the set view
3313 <     * @throws NullPointerException if the mappedValue is null
3314 <     */
3315 <    public KeySetView<K,V> keySet(V mappedValue) {
3316 <        if (mappedValue == null)
3317 <            throw new NullPointerException();
2795 <        return new KeySetView<K,V>(this, mappedValue);
2796 <    }
2797 <
2798 <    /**
2799 <     * Returns a {@link Collection} view of the values contained in this map.
2800 <     * The collection is backed by the map, so changes to the map are
2801 <     * reflected in the collection, and vice-versa.
2802 <     */
2803 <    public ValuesView<K,V> values() {
2804 <        ValuesView<K,V> vs = values;
2805 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2806 <    }
2807 <
2808 <    /**
2809 <     * Returns a {@link Set} view of the mappings contained in this map.
2810 <     * The set is backed by the map, so changes to the map are
2811 <     * reflected in the set, and vice-versa.  The set supports element
2812 <     * removal, which removes the corresponding mapping from the map,
2813 <     * via the {@code Iterator.remove}, {@code Set.remove},
2814 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
2815 <     * operations.  It does not support the {@code add} or
2816 <     * {@code addAll} operations.
3310 >     * Method advance visits once each still-valid node that was
3311 >     * reachable upon iterator construction. It might miss some that
3312 >     * were added to a bin after the bin was visited, which is OK wrt
3313 >     * consistency guarantees. Maintaining this property in the face
3314 >     * of possible ongoing resizes requires a fair amount of
3315 >     * bookkeeping state that is difficult to optimize away amidst
3316 >     * volatile accesses.  Even so, traversal maintains reasonable
3317 >     * throughput.
3318       *
3319 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
3320 <     * that will never throw {@link ConcurrentModificationException},
3321 <     * and guarantees to traverse elements as they existed upon
3322 <     * construction of the iterator, and may (but is not guaranteed to)
3323 <     * reflect any modifications subsequent to construction.
3319 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3320 >     * However, if the table has been resized, then all future steps
3321 >     * must traverse both the bin at the current index as well as at
3322 >     * (index + baseSize); and so on for further resizings. To
3323 >     * paranoically cope with potential sharing by users of iterators
3324 >     * across threads, iteration terminates if a bounds checks fails
3325 >     * for a table read.
3326       */
3327 <    public Set<Map.Entry<K,V>> entrySet() {
3328 <        EntrySetView<K,V> es = entrySet;
3329 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
3330 <    }
3327 >    static class Traverser<K,V> {
3328 >        Node<K,V>[] tab;        // current table; updated if resized
3329 >        Node<K,V> next;         // the next entry to use
3330 >        TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3331 >        int index;              // index of bin to use next
3332 >        int baseIndex;          // current index of initial table
3333 >        int baseLimit;          // index bound for initial table
3334 >        final int baseSize;     // initial table size
3335 >
3336 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3337 >            this.tab = tab;
3338 >            this.baseSize = size;
3339 >            this.baseIndex = this.index = index;
3340 >            this.baseLimit = limit;
3341 >            this.next = null;
3342 >        }
3343  
3344 <    /**
3345 <     * Returns an enumeration of the keys in this table.
3346 <     *
3347 <     * @return an enumeration of the keys in this table
3348 <     * @see #keySet()
3349 <     */
3350 <    public Enumeration<K> keys() {
3351 <        return new KeyIterator<K,V>(this);
3352 <    }
3344 >        /**
3345 >         * Advances if possible, returning next valid node, or null if none.
3346 >         */
3347 >        final Node<K,V> advance() {
3348 >            Node<K,V> e;
3349 >            if ((e = next) != null)
3350 >                e = e.next;
3351 >            for (;;) {
3352 >                Node<K,V>[] t; int i, n;  // must use locals in checks
3353 >                if (e != null)
3354 >                    return next = e;
3355 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3356 >                    (n = t.length) <= (i = index) || i < 0)
3357 >                    return next = null;
3358 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
3359 >                    if (e instanceof ForwardingNode) {
3360 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3361 >                        e = null;
3362 >                        pushState(t, i, n);
3363 >                        continue;
3364 >                    }
3365 >                    else if (e instanceof TreeBin)
3366 >                        e = ((TreeBin<K,V>)e).first;
3367 >                    else
3368 >                        e = null;
3369 >                }
3370 >                if (stack != null)
3371 >                    recoverState(n);
3372 >                else if ((index = i + baseSize) >= n)
3373 >                    index = ++baseIndex; // visit upper slots if present
3374 >            }
3375 >        }
3376  
3377 <    /**
3378 <     * Returns an enumeration of the values in this table.
3379 <     *
3380 <     * @return an enumeration of the values in this table
3381 <     * @see #values()
3382 <     */
3383 <    public Enumeration<V> elements() {
3384 <        return new ValueIterator<K,V>(this);
3385 <    }
3377 >        /**
3378 >         * Saves traversal state upon encountering a forwarding node.
3379 >         */
3380 >        private void pushState(Node<K,V>[] t, int i, int n) {
3381 >            TableStack<K,V> s = spare;  // reuse if possible
3382 >            if (s != null)
3383 >                spare = s.next;
3384 >            else
3385 >                s = new TableStack<K,V>();
3386 >            s.tab = t;
3387 >            s.length = n;
3388 >            s.index = i;
3389 >            s.next = stack;
3390 >            stack = s;
3391 >        }
3392  
3393 <    /**
3394 <     * Returns the hash code value for this {@link Map}, i.e.,
3395 <     * the sum of, for each key-value pair in the map,
3396 <     * {@code key.hashCode() ^ value.hashCode()}.
3397 <     *
3398 <     * @return the hash code value for this map
3399 <     */
3400 <    public int hashCode() {
3401 <        int h = 0;
3402 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3403 <        V v;
3404 <        while ((v = it.advance()) != null) {
3405 <            h += it.nextKey.hashCode() ^ v.hashCode();
3393 >        /**
3394 >         * Possibly pops traversal state.
3395 >         *
3396 >         * @param n length of current table
3397 >         */
3398 >        private void recoverState(int n) {
3399 >            TableStack<K,V> s; int len;
3400 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
3401 >                n = len;
3402 >                index = s.index;
3403 >                tab = s.tab;
3404 >                s.tab = null;
3405 >                TableStack<K,V> next = s.next;
3406 >                s.next = spare; // save for reuse
3407 >                stack = next;
3408 >                spare = s;
3409 >            }
3410 >            if (s == null && (index += baseSize) >= n)
3411 >                index = ++baseIndex;
3412          }
2863        return h;
3413      }
3414  
3415      /**
3416 <     * Returns a string representation of this map.  The string
3417 <     * representation consists of a list of key-value mappings (in no
3418 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3419 <     * mappings are separated by the characters {@code ", "} (comma
3420 <     * and space).  Each key-value mapping is rendered as the key
3421 <     * followed by an equals sign ("{@code =}") followed by the
3422 <     * associated value.
3423 <     *
3424 <     * @return a string representation of this map
3425 <     */
3426 <    public String toString() {
2878 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2879 <        StringBuilder sb = new StringBuilder();
2880 <        sb.append('{');
2881 <        V v;
2882 <        if ((v = it.advance()) != null) {
2883 <            for (;;) {
2884 <                Object k = it.nextKey;
2885 <                sb.append(k == this ? "(this Map)" : k);
2886 <                sb.append('=');
2887 <                sb.append(v == this ? "(this Map)" : v);
2888 <                if ((v = it.advance()) == null)
2889 <                    break;
2890 <                sb.append(',').append(' ');
2891 <            }
3416 >     * Base of key, value, and entry Iterators. Adds fields to
3417 >     * Traverser to support iterator.remove.
3418 >     */
3419 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3420 >        final ConcurrentHashMap<K,V> map;
3421 >        Node<K,V> lastReturned;
3422 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3423 >                    ConcurrentHashMap<K,V> map) {
3424 >            super(tab, size, index, limit);
3425 >            this.map = map;
3426 >            advance();
3427          }
2893        return sb.append('}').toString();
2894    }
3428  
3429 <    /**
3430 <     * Compares the specified object with this map for equality.
3431 <     * Returns {@code true} if the given object is a map with the same
3432 <     * mappings as this map.  This operation may return misleading
3433 <     * results if either map is concurrently modified during execution
3434 <     * of this method.
3435 <     *
3436 <     * @param o object to be compared for equality with this map
3437 <     * @return {@code true} if the specified object is equal to this map
2905 <     */
2906 <    public boolean equals(Object o) {
2907 <        if (o != this) {
2908 <            if (!(o instanceof Map))
2909 <                return false;
2910 <            Map<?,?> m = (Map<?,?>) o;
2911 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2912 <            V val;
2913 <            while ((val = it.advance()) != null) {
2914 <                Object v = m.get(it.nextKey);
2915 <                if (v == null || (v != val && !v.equals(val)))
2916 <                    return false;
2917 <            }
2918 <            for (Map.Entry<?,?> e : m.entrySet()) {
2919 <                Object mk, mv, v;
2920 <                if ((mk = e.getKey()) == null ||
2921 <                    (mv = e.getValue()) == null ||
2922 <                    (v = internalGet(mk)) == null ||
2923 <                    (mv != v && !mv.equals(v)))
2924 <                    return false;
2925 <            }
3429 >        public final boolean hasNext() { return next != null; }
3430 >        public final boolean hasMoreElements() { return next != null; }
3431 >
3432 >        public final void remove() {
3433 >            Node<K,V> p;
3434 >            if ((p = lastReturned) == null)
3435 >                throw new IllegalStateException();
3436 >            lastReturned = null;
3437 >            map.replaceNode(p.key, null, null);
3438          }
2927        return true;
3439      }
3440  
3441 <    /* ----------------Iterators -------------- */
3442 <
3443 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3444 <        extends Traverser<K,V,Object>
3445 <        implements Spliterator<K>, Iterator<K>, Enumeration<K> {
2935 <        KeyIterator(ConcurrentHashMap<K, V> map) { super(map); }
2936 <        KeyIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
2937 <            super(map, it);
2938 <        }
2939 <        public KeyIterator<K,V> trySplit() {
2940 <            if (tab != null && baseIndex == baseLimit)
2941 <                return null;
2942 <            return new KeyIterator<K,V>(map, this);
3441 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3442 >        implements Iterator<K>, Enumeration<K> {
3443 >        KeyIterator(Node<K,V>[] tab, int size, int index, int limit,
3444 >                    ConcurrentHashMap<K,V> map) {
3445 >            super(tab, size, index, limit, map);
3446          }
3447 <        @SuppressWarnings("unchecked") public final K next() {
3448 <            if (nextVal == null && advance() == null)
3447 >
3448 >        public final K next() {
3449 >            Node<K,V> p;
3450 >            if ((p = next) == null)
3451                  throw new NoSuchElementException();
3452 <            Object k = nextKey;
3453 <            nextVal = null;
3454 <            return (K) k;
3452 >            K k = p.key;
3453 >            lastReturned = p;
3454 >            advance();
3455 >            return k;
3456          }
3457  
3458          public final K nextElement() { return next(); }
2953
2954        public Iterator<K> iterator() { return this; }
2955
2956        public void forEach(Block<? super K> action) {
2957            if (action == null) throw new NullPointerException();
2958            while (advance() != null)
2959                action.accept((K)nextKey);
2960        }
2961
2962        public boolean tryAdvance(Block<? super K> block) {
2963            if (block == null) throw new NullPointerException();
2964            if (advance() == null)
2965                return false;
2966            block.accept((K)nextKey);
2967            return true;
2968        }
3459      }
3460  
3461 <    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3462 <        extends Traverser<K,V,Object>
3463 <        implements Spliterator<V>, Iterator<V>, Enumeration<V> {
3464 <        ValueIterator(ConcurrentHashMap<K, V> map) { super(map); }
3465 <        ValueIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
2976 <            super(map, it);
2977 <        }
2978 <        public ValueIterator<K,V> trySplit() {
2979 <            if (tab != null && baseIndex == baseLimit)
2980 <                return null;
2981 <            return new ValueIterator<K,V>(map, this);
3461 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3462 >        implements Iterator<V>, Enumeration<V> {
3463 >        ValueIterator(Node<K,V>[] tab, int size, int index, int limit,
3464 >                      ConcurrentHashMap<K,V> map) {
3465 >            super(tab, size, index, limit, map);
3466          }
3467  
3468          public final V next() {
3469 <            V v;
3470 <            if ((v = nextVal) == null && (v = advance()) == null)
3469 >            Node<K,V> p;
3470 >            if ((p = next) == null)
3471                  throw new NoSuchElementException();
3472 <            nextVal = null;
3472 >            V v = p.val;
3473 >            lastReturned = p;
3474 >            advance();
3475              return v;
3476          }
3477  
3478          public final V nextElement() { return next(); }
2993
2994        public Iterator<V> iterator() { return this; }
2995
2996        public void forEach(Block<? super V> action) {
2997            if (action == null) throw new NullPointerException();
2998            V v;
2999            while ((v = advance()) != null)
3000                action.accept(v);
3001        }
3002
3003        public boolean tryAdvance(Block<? super V> block) {
3004            V v;
3005            if (block == null) throw new NullPointerException();
3006            if ((v = advance()) == null)
3007                return false;
3008            block.accept(v);
3009            return true;
3010        }
3011
3479      }
3480  
3481 <    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3482 <        extends Traverser<K,V,Object>
3483 <        implements Spliterator<Map.Entry<K,V>>, Iterator<Map.Entry<K,V>> {
3484 <        EntryIterator(ConcurrentHashMap<K, V> map) { super(map); }
3485 <        EntryIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
3019 <            super(map, it);
3020 <        }
3021 <        public EntryIterator<K,V> trySplit() {
3022 <            if (tab != null && baseIndex == baseLimit)
3023 <                return null;
3024 <            return new EntryIterator<K,V>(map, this);
3481 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3482 >        implements Iterator<Map.Entry<K,V>> {
3483 >        EntryIterator(Node<K,V>[] tab, int size, int index, int limit,
3484 >                      ConcurrentHashMap<K,V> map) {
3485 >            super(tab, size, index, limit, map);
3486          }
3487  
3488 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3489 <            V v;
3490 <            if ((v = nextVal) == null && (v = advance()) == null)
3488 >        public final Map.Entry<K,V> next() {
3489 >            Node<K,V> p;
3490 >            if ((p = next) == null)
3491                  throw new NoSuchElementException();
3492 <            Object k = nextKey;
3493 <            nextVal = null;
3494 <            return new MapEntry<K,V>((K)k, v, map);
3495 <        }
3496 <
3036 <        public Iterator<Map.Entry<K,V>> iterator() { return this; }
3037 <
3038 <        public void forEach(Block<? super Map.Entry<K,V>> action) {
3039 <            if (action == null) throw new NullPointerException();
3040 <            V v;
3041 <            while ((v = advance()) != null)
3042 <                action.accept(entryFor((K)nextKey, v));
3492 >            K k = p.key;
3493 >            V v = p.val;
3494 >            lastReturned = p;
3495 >            advance();
3496 >            return new MapEntry<K,V>(k, v, map);
3497          }
3044
3045        public boolean tryAdvance(Block<? super Map.Entry<K,V>> block) {
3046            V v;
3047            if (block == null) throw new NullPointerException();
3048            if ((v = advance()) == null)
3049                return false;
3050            block.accept(entryFor((K)nextKey, v));
3051            return true;
3052        }
3053
3498      }
3499  
3500      /**
3501 <     * Exported Entry for iterators
3501 >     * Exported Entry for EntryIterator.
3502       */
3503 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3503 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3504          final K key; // non-null
3505          V val;       // non-null
3506 <        final ConcurrentHashMap<K, V> map;
3507 <        MapEntry(K key, V val, ConcurrentHashMap<K, V> map) {
3506 >        final ConcurrentHashMap<K,V> map;
3507 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3508              this.key = key;
3509              this.val = val;
3510              this.map = map;
3511          }
3512 <        public final K getKey()       { return key; }
3513 <        public final V getValue()     { return val; }
3514 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3515 <        public final String toString(){ return key + "=" + val; }
3512 >        public K getKey()        { return key; }
3513 >        public V getValue()      { return val; }
3514 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3515 >        public String toString() {
3516 >            return Helpers.mapEntryToString(key, val);
3517 >        }
3518  
3519 <        public final boolean equals(Object o) {
3519 >        public boolean equals(Object o) {
3520              Object k, v; Map.Entry<?,?> e;
3521              return ((o instanceof Map.Entry) &&
3522                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3084 | Line 3530 | public class ConcurrentHashMap<K, V>
3530           * value to return is somewhat arbitrary here. Since we do not
3531           * necessarily track asynchronous changes, the most recent
3532           * "previous" value could be different from what we return (or
3533 <         * could even have been removed in which case the put will
3533 >         * could even have been removed, in which case the put will
3534           * re-establish). We do not and cannot guarantee more.
3535           */
3536 <        public final V setValue(V value) {
3536 >        public V setValue(V value) {
3537              if (value == null) throw new NullPointerException();
3538              V v = val;
3539              val = value;
# Line 3096 | Line 3542 | public class ConcurrentHashMap<K, V>
3542          }
3543      }
3544  
3545 <    /**
3546 <     * Returns exportable snapshot entry for the given key and value
3547 <     * when write-through can't or shouldn't be used.
3548 <     */
3549 <    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3550 <        return new AbstractMap.SimpleEntry<K,V>(k, v);
3551 <    }
3545 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3546 >        implements Spliterator<K> {
3547 >        long est;               // size estimate
3548 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3549 >                       long est) {
3550 >            super(tab, size, index, limit);
3551 >            this.est = est;
3552 >        }
3553 >
3554 >        public KeySpliterator<K,V> trySplit() {
3555 >            int i, f, h;
3556 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3557 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3558 >                                        f, est >>>= 1);
3559 >        }
3560  
3561 <    /* ---------------- Serialization Support -------------- */
3561 >        public void forEachRemaining(Consumer<? super K> action) {
3562 >            if (action == null) throw new NullPointerException();
3563 >            for (Node<K,V> p; (p = advance()) != null;)
3564 >                action.accept(p.key);
3565 >        }
3566  
3567 <    /**
3568 <     * Stripped-down version of helper class used in previous version,
3569 <     * declared for the sake of serialization compatibility
3570 <     */
3571 <    static class Segment<K,V> implements Serializable {
3572 <        private static final long serialVersionUID = 2249069246763182397L;
3573 <        final float loadFactor;
3574 <        Segment(float lf) { this.loadFactor = lf; }
3567 >        public boolean tryAdvance(Consumer<? super K> action) {
3568 >            if (action == null) throw new NullPointerException();
3569 >            Node<K,V> p;
3570 >            if ((p = advance()) == null)
3571 >                return false;
3572 >            action.accept(p.key);
3573 >            return true;
3574 >        }
3575 >
3576 >        public long estimateSize() { return est; }
3577 >
3578 >        public int characteristics() {
3579 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3580 >                Spliterator.NONNULL;
3581 >        }
3582      }
3583  
3584 <    /**
3585 <     * Saves the state of the {@code ConcurrentHashMap} instance to a
3586 <     * stream (i.e., serializes it).
3587 <     * @param s the stream
3588 <     * @serialData
3589 <     * the key (Object) and value (Object)
3590 <     * for each key-value mapping, followed by a null pair.
3126 <     * The key-value mappings are emitted in no particular order.
3127 <     */
3128 <    @SuppressWarnings("unchecked") private void writeObject
3129 <        (java.io.ObjectOutputStream s)
3130 <        throws java.io.IOException {
3131 <        if (segments == null) { // for serialization compatibility
3132 <            segments = (Segment<K,V>[])
3133 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3134 <            for (int i = 0; i < segments.length; ++i)
3135 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3584 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3585 >        implements Spliterator<V> {
3586 >        long est;               // size estimate
3587 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3588 >                         long est) {
3589 >            super(tab, size, index, limit);
3590 >            this.est = est;
3591          }
3592 <        s.defaultWriteObject();
3593 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3594 <        V v;
3595 <        while ((v = it.advance()) != null) {
3596 <            s.writeObject(it.nextKey);
3597 <            s.writeObject(v);
3592 >
3593 >        public ValueSpliterator<K,V> trySplit() {
3594 >            int i, f, h;
3595 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3596 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3597 >                                          f, est >>>= 1);
3598 >        }
3599 >
3600 >        public void forEachRemaining(Consumer<? super V> action) {
3601 >            if (action == null) throw new NullPointerException();
3602 >            for (Node<K,V> p; (p = advance()) != null;)
3603 >                action.accept(p.val);
3604 >        }
3605 >
3606 >        public boolean tryAdvance(Consumer<? super V> action) {
3607 >            if (action == null) throw new NullPointerException();
3608 >            Node<K,V> p;
3609 >            if ((p = advance()) == null)
3610 >                return false;
3611 >            action.accept(p.val);
3612 >            return true;
3613 >        }
3614 >
3615 >        public long estimateSize() { return est; }
3616 >
3617 >        public int characteristics() {
3618 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3619          }
3144        s.writeObject(null);
3145        s.writeObject(null);
3146        segments = null; // throw away
3620      }
3621  
3622 <    /**
3623 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3624 <     * @param s the stream
3625 <     */
3626 <    @SuppressWarnings("unchecked") private void readObject
3627 <        (java.io.ObjectInputStream s)
3628 <        throws java.io.IOException, ClassNotFoundException {
3629 <        s.defaultReadObject();
3630 <        this.segments = null; // unneeded
3622 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3623 >        implements Spliterator<Map.Entry<K,V>> {
3624 >        final ConcurrentHashMap<K,V> map; // To export MapEntry
3625 >        long est;               // size estimate
3626 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3627 >                         long est, ConcurrentHashMap<K,V> map) {
3628 >            super(tab, size, index, limit);
3629 >            this.map = map;
3630 >            this.est = est;
3631 >        }
3632  
3633 <        // Create all nodes, then place in table once size is known
3634 <        long size = 0L;
3635 <        Node<V> p = null;
3636 <        for (;;) {
3637 <            K k = (K) s.readObject();
3164 <            V v = (V) s.readObject();
3165 <            if (k != null && v != null) {
3166 <                int h = spread(k.hashCode());
3167 <                p = new Node<V>(h, k, v, p);
3168 <                ++size;
3169 <            }
3170 <            else
3171 <                break;
3633 >        public EntrySpliterator<K,V> trySplit() {
3634 >            int i, f, h;
3635 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3636 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3637 >                                          f, est >>>= 1, map);
3638          }
3639 <        if (p != null) {
3640 <            boolean init = false;
3641 <            int n;
3642 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3643 <                n = MAXIMUM_CAPACITY;
3644 <            else {
3645 <                int sz = (int)size;
3646 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3647 <            }
3648 <            int sc = sizeCtl;
3649 <            boolean collide = false;
3650 <            if (n > sc &&
3651 <                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3652 <                try {
3653 <                    if (table == null) {
3654 <                        init = true;
3655 <                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3656 <                        Node<V>[] tab = (Node<V>[])rt;
3657 <                        int mask = n - 1;
3658 <                        while (p != null) {
3659 <                            int j = p.hash & mask;
3194 <                            Node<V> next = p.next;
3195 <                            Node<V> q = p.next = tabAt(tab, j);
3196 <                            setTabAt(tab, j, p);
3197 <                            if (!collide && q != null && q.hash == p.hash)
3198 <                                collide = true;
3199 <                            p = next;
3200 <                        }
3201 <                        table = tab;
3202 <                        addCount(size, -1);
3203 <                        sc = n - (n >>> 2);
3204 <                    }
3205 <                } finally {
3206 <                    sizeCtl = sc;
3207 <                }
3208 <                if (collide) { // rescan and convert to TreeBins
3209 <                    Node<V>[] tab = table;
3210 <                    for (int i = 0; i < tab.length; ++i) {
3211 <                        int c = 0;
3212 <                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3213 <                            if (++c > TREE_THRESHOLD &&
3214 <                                (e.key instanceof Comparable)) {
3215 <                                replaceWithTreeBin(tab, i, e.key);
3216 <                                break;
3217 <                            }
3218 <                        }
3219 <                    }
3220 <                }
3221 <            }
3222 <            if (!init) { // Can only happen if unsafely published.
3223 <                while (p != null) {
3224 <                    internalPut((K)p.key, p.val, false);
3225 <                    p = p.next;
3226 <                }
3227 <            }
3639 >
3640 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3641 >            if (action == null) throw new NullPointerException();
3642 >            for (Node<K,V> p; (p = advance()) != null; )
3643 >                action.accept(new MapEntry<K,V>(p.key, p.val, map));
3644 >        }
3645 >
3646 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3647 >            if (action == null) throw new NullPointerException();
3648 >            Node<K,V> p;
3649 >            if ((p = advance()) == null)
3650 >                return false;
3651 >            action.accept(new MapEntry<K,V>(p.key, p.val, map));
3652 >            return true;
3653 >        }
3654 >
3655 >        public long estimateSize() { return est; }
3656 >
3657 >        public int characteristics() {
3658 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3659 >                Spliterator.NONNULL;
3660          }
3661      }
3662  
3663 <    // -------------------------------------------------------
3663 >    // Parallel bulk operations
3664  
3665 <    // Sequential bulk operations
3665 >    /**
3666 >     * Computes initial batch value for bulk tasks. The returned value
3667 >     * is approximately exp2 of the number of times (minus one) to
3668 >     * split task by two before executing leaf action. This value is
3669 >     * faster to compute and more convenient to use as a guide to
3670 >     * splitting than is the depth, since it is used while dividing by
3671 >     * two anyway.
3672 >     */
3673 >    final int batchFor(long b) {
3674 >        long n;
3675 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3676 >            return 0;
3677 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3678 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3679 >    }
3680  
3681      /**
3682       * Performs the given action for each (key, value).
3683       *
3684 +     * @param parallelismThreshold the (estimated) number of elements
3685 +     * needed for this operation to be executed in parallel
3686       * @param action the action
3687 +     * @since 1.8
3688       */
3689 <    @SuppressWarnings("unchecked") public void forEachSequentially
3690 <        (BiBlock<? super K, ? super V> action) {
3689 >    public void forEach(long parallelismThreshold,
3690 >                        BiConsumer<? super K,? super V> action) {
3691          if (action == null) throw new NullPointerException();
3692 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3693 <        V v;
3694 <        while ((v = it.advance()) != null)
3246 <            action.accept((K)it.nextKey, v);
3692 >        new ForEachMappingTask<K,V>
3693 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3694 >             action).invoke();
3695      }
3696  
3697      /**
3698       * Performs the given action for each non-null transformation
3699       * of each (key, value).
3700       *
3701 +     * @param parallelismThreshold the (estimated) number of elements
3702 +     * needed for this operation to be executed in parallel
3703       * @param transformer a function returning the transformation
3704 <     * for an element, or null of there is no transformation (in
3705 <     * which case the action is not applied).
3704 >     * for an element, or null if there is no transformation (in
3705 >     * which case the action is not applied)
3706       * @param action the action
3707 +     * @param <U> the return type of the transformer
3708 +     * @since 1.8
3709       */
3710 <    @SuppressWarnings("unchecked") public <U> void forEachSequentially
3711 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3712 <         Block<? super U> action) {
3710 >    public <U> void forEach(long parallelismThreshold,
3711 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3712 >                            Consumer<? super U> action) {
3713          if (transformer == null || action == null)
3714              throw new NullPointerException();
3715 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3716 <        V v; U u;
3717 <        while ((v = it.advance()) != null) {
3266 <            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3267 <                action.accept(u);
3268 <        }
3715 >        new ForEachTransformedMappingTask<K,V,U>
3716 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3717 >             transformer, action).invoke();
3718      }
3719  
3720      /**
3721       * Returns a non-null result from applying the given search
3722 <     * function on each (key, value), or null if none.
3722 >     * function on each (key, value), or null if none.  Upon
3723 >     * success, further element processing is suppressed and the
3724 >     * results of any other parallel invocations of the search
3725 >     * function are ignored.
3726       *
3727 +     * @param parallelismThreshold the (estimated) number of elements
3728 +     * needed for this operation to be executed in parallel
3729       * @param searchFunction a function returning a non-null
3730       * result on success, else null
3731 +     * @param <U> the return type of the search function
3732       * @return a non-null result from applying the given search
3733       * function on each (key, value), or null if none
3734 +     * @since 1.8
3735       */
3736 <    @SuppressWarnings("unchecked") public <U> U searchSequentially
3737 <        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3736 >    public <U> U search(long parallelismThreshold,
3737 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3738          if (searchFunction == null) throw new NullPointerException();
3739 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3740 <        V v; U u;
3741 <        while ((v = it.advance()) != null) {
3286 <            if ((u = searchFunction.apply((K)it.nextKey, v)) != null)
3287 <                return u;
3288 <        }
3289 <        return null;
3739 >        return new SearchMappingsTask<K,V,U>
3740 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3741 >             searchFunction, new AtomicReference<U>()).invoke();
3742      }
3743  
3744      /**
# Line 3294 | Line 3746 | public class ConcurrentHashMap<K, V>
3746       * of all (key, value) pairs using the given reducer to
3747       * combine values, or null if none.
3748       *
3749 +     * @param parallelismThreshold the (estimated) number of elements
3750 +     * needed for this operation to be executed in parallel
3751       * @param transformer a function returning the transformation
3752 <     * for an element, or null of there is no transformation (in
3753 <     * which case it is not combined).
3752 >     * for an element, or null if there is no transformation (in
3753 >     * which case it is not combined)
3754       * @param reducer a commutative associative combining function
3755 +     * @param <U> the return type of the transformer
3756       * @return the result of accumulating the given transformation
3757       * of all (key, value) pairs
3758 +     * @since 1.8
3759       */
3760 <    @SuppressWarnings("unchecked") public <U> U reduceSequentially
3761 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3762 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
3760 >    public <U> U reduce(long parallelismThreshold,
3761 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3762 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3763          if (transformer == null || reducer == null)
3764              throw new NullPointerException();
3765 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3766 <        U r = null, u; V v;
3767 <        while ((v = it.advance()) != null) {
3312 <            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3313 <                r = (r == null) ? u : reducer.apply(r, u);
3314 <        }
3315 <        return r;
3765 >        return new MapReduceMappingsTask<K,V,U>
3766 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3767 >             null, transformer, reducer).invoke();
3768      }
3769  
3770      /**
# Line 3320 | Line 3772 | public class ConcurrentHashMap<K, V>
3772       * of all (key, value) pairs using the given reducer to
3773       * combine values, and the given basis as an identity value.
3774       *
3775 +     * @param parallelismThreshold the (estimated) number of elements
3776 +     * needed for this operation to be executed in parallel
3777       * @param transformer a function returning the transformation
3778       * for an element
3779       * @param basis the identity (initial default value) for the reduction
3780       * @param reducer a commutative associative combining function
3781       * @return the result of accumulating the given transformation
3782       * of all (key, value) pairs
3783 +     * @since 1.8
3784       */
3785 <    @SuppressWarnings("unchecked") public double reduceToDoubleSequentially
3786 <        (DoubleBiFunction<? super K, ? super V> transformer,
3787 <         double basis,
3788 <         DoubleBinaryOperator reducer) {
3785 >    public double reduceToDouble(long parallelismThreshold,
3786 >                                 ToDoubleBiFunction<? super K, ? super V> transformer,
3787 >                                 double basis,
3788 >                                 DoubleBinaryOperator reducer) {
3789          if (transformer == null || reducer == null)
3790              throw new NullPointerException();
3791 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3792 <        double r = basis; V v;
3793 <        while ((v = it.advance()) != null)
3339 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)it.nextKey, v));
3340 <        return r;
3791 >        return new MapReduceMappingsToDoubleTask<K,V>
3792 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3793 >             null, transformer, basis, reducer).invoke();
3794      }
3795  
3796      /**
# Line 3345 | Line 3798 | public class ConcurrentHashMap<K, V>
3798       * of all (key, value) pairs using the given reducer to
3799       * combine values, and the given basis as an identity value.
3800       *
3801 +     * @param parallelismThreshold the (estimated) number of elements
3802 +     * needed for this operation to be executed in parallel
3803       * @param transformer a function returning the transformation
3804       * for an element
3805       * @param basis the identity (initial default value) for the reduction
3806       * @param reducer a commutative associative combining function
3807       * @return the result of accumulating the given transformation
3808       * of all (key, value) pairs
3809 +     * @since 1.8
3810       */
3811 <    @SuppressWarnings("unchecked") public long reduceToLongSequentially
3812 <        (LongBiFunction<? super K, ? super V> transformer,
3813 <         long basis,
3814 <         LongBinaryOperator reducer) {
3811 >    public long reduceToLong(long parallelismThreshold,
3812 >                             ToLongBiFunction<? super K, ? super V> transformer,
3813 >                             long basis,
3814 >                             LongBinaryOperator reducer) {
3815          if (transformer == null || reducer == null)
3816              throw new NullPointerException();
3817 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3818 <        long r = basis; V v;
3819 <        while ((v = it.advance()) != null)
3364 <            r = reducer.applyAsLong(r, transformer.applyAsLong((K)it.nextKey, v));
3365 <        return r;
3817 >        return new MapReduceMappingsToLongTask<K,V>
3818 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3819 >             null, transformer, basis, reducer).invoke();
3820      }
3821  
3822      /**
# Line 3370 | Line 3824 | public class ConcurrentHashMap<K, V>
3824       * of all (key, value) pairs using the given reducer to
3825       * combine values, and the given basis as an identity value.
3826       *
3827 +     * @param parallelismThreshold the (estimated) number of elements
3828 +     * needed for this operation to be executed in parallel
3829       * @param transformer a function returning the transformation
3830       * for an element
3831       * @param basis the identity (initial default value) for the reduction
3832       * @param reducer a commutative associative combining function
3833       * @return the result of accumulating the given transformation
3834       * of all (key, value) pairs
3835 +     * @since 1.8
3836       */
3837 <    @SuppressWarnings("unchecked") public int reduceToIntSequentially
3838 <        (IntBiFunction<? super K, ? super V> transformer,
3839 <         int basis,
3840 <         IntBinaryOperator reducer) {
3837 >    public int reduceToInt(long parallelismThreshold,
3838 >                           ToIntBiFunction<? super K, ? super V> transformer,
3839 >                           int basis,
3840 >                           IntBinaryOperator reducer) {
3841          if (transformer == null || reducer == null)
3842              throw new NullPointerException();
3843 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3844 <        int r = basis; V v;
3845 <        while ((v = it.advance()) != null)
3389 <            r = reducer.applyAsInt(r, transformer.applyAsInt((K)it.nextKey, v));
3390 <        return r;
3843 >        return new MapReduceMappingsToIntTask<K,V>
3844 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3845 >             null, transformer, basis, reducer).invoke();
3846      }
3847  
3848      /**
3849       * Performs the given action for each key.
3850       *
3851 +     * @param parallelismThreshold the (estimated) number of elements
3852 +     * needed for this operation to be executed in parallel
3853       * @param action the action
3854 +     * @since 1.8
3855       */
3856 <    @SuppressWarnings("unchecked") public void forEachKeySequentially
3857 <        (Block<? super K> action) {
3856 >    public void forEachKey(long parallelismThreshold,
3857 >                           Consumer<? super K> action) {
3858          if (action == null) throw new NullPointerException();
3859 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3860 <        while (it.advance() != null)
3861 <            action.accept((K)it.nextKey);
3859 >        new ForEachKeyTask<K,V>
3860 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3861 >             action).invoke();
3862      }
3863  
3864      /**
3865       * Performs the given action for each non-null transformation
3866       * of each key.
3867       *
3868 +     * @param parallelismThreshold the (estimated) number of elements
3869 +     * needed for this operation to be executed in parallel
3870       * @param transformer a function returning the transformation
3871 <     * for an element, or null of there is no transformation (in
3872 <     * which case the action is not applied).
3871 >     * for an element, or null if there is no transformation (in
3872 >     * which case the action is not applied)
3873       * @param action the action
3874 +     * @param <U> the return type of the transformer
3875 +     * @since 1.8
3876       */
3877 <    @SuppressWarnings("unchecked") public <U> void forEachKeySequentially
3878 <        (Function<? super K, ? extends U> transformer,
3879 <         Block<? super U> action) {
3877 >    public <U> void forEachKey(long parallelismThreshold,
3878 >                               Function<? super K, ? extends U> transformer,
3879 >                               Consumer<? super U> action) {
3880          if (transformer == null || action == null)
3881              throw new NullPointerException();
3882 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3883 <        U u;
3884 <        while (it.advance() != null) {
3423 <            if ((u = transformer.apply((K)it.nextKey)) != null)
3424 <                action.accept(u);
3425 <        }
3426 <        ForkJoinTasks.forEachKey
3427 <            (this, transformer, action).invoke();
3882 >        new ForEachTransformedKeyTask<K,V,U>
3883 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3884 >             transformer, action).invoke();
3885      }
3886  
3887      /**
3888       * Returns a non-null result from applying the given search
3889 <     * function on each key, or null if none.
3889 >     * function on each key, or null if none. Upon success,
3890 >     * further element processing is suppressed and the results of
3891 >     * any other parallel invocations of the search function are
3892 >     * ignored.
3893       *
3894 +     * @param parallelismThreshold the (estimated) number of elements
3895 +     * needed for this operation to be executed in parallel
3896       * @param searchFunction a function returning a non-null
3897       * result on success, else null
3898 +     * @param <U> the return type of the search function
3899       * @return a non-null result from applying the given search
3900       * function on each key, or null if none
3901 +     * @since 1.8
3902       */
3903 <    @SuppressWarnings("unchecked") public <U> U searchKeysSequentially
3904 <        (Function<? super K, ? extends U> searchFunction) {
3905 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3906 <        U u;
3907 <        while (it.advance() != null) {
3908 <            if ((u = searchFunction.apply((K)it.nextKey)) != null)
3445 <                return u;
3446 <        }
3447 <        return null;
3903 >    public <U> U searchKeys(long parallelismThreshold,
3904 >                            Function<? super K, ? extends U> searchFunction) {
3905 >        if (searchFunction == null) throw new NullPointerException();
3906 >        return new SearchKeysTask<K,V,U>
3907 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3908 >             searchFunction, new AtomicReference<U>()).invoke();
3909      }
3910  
3911      /**
3912       * Returns the result of accumulating all keys using the given
3913       * reducer to combine values, or null if none.
3914       *
3915 +     * @param parallelismThreshold the (estimated) number of elements
3916 +     * needed for this operation to be executed in parallel
3917       * @param reducer a commutative associative combining function
3918       * @return the result of accumulating all keys using the given
3919       * reducer to combine values, or null if none
3920 +     * @since 1.8
3921       */
3922 <    @SuppressWarnings("unchecked") public K reduceKeysSequentially
3923 <        (BiFunction<? super K, ? super K, ? extends K> reducer) {
3922 >    public K reduceKeys(long parallelismThreshold,
3923 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3924          if (reducer == null) throw new NullPointerException();
3925 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3926 <        K r = null;
3927 <        while (it.advance() != null) {
3464 <            K u = (K)it.nextKey;
3465 <            r = (r == null) ? u : reducer.apply(r, u);
3466 <        }
3467 <        return r;
3925 >        return new ReduceKeysTask<K,V>
3926 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3927 >             null, reducer).invoke();
3928      }
3929  
3930      /**
# Line 3472 | Line 3932 | public class ConcurrentHashMap<K, V>
3932       * of all keys using the given reducer to combine values, or
3933       * null if none.
3934       *
3935 +     * @param parallelismThreshold the (estimated) number of elements
3936 +     * needed for this operation to be executed in parallel
3937       * @param transformer a function returning the transformation
3938 <     * for an element, or null of there is no transformation (in
3939 <     * which case it is not combined).
3938 >     * for an element, or null if there is no transformation (in
3939 >     * which case it is not combined)
3940       * @param reducer a commutative associative combining function
3941 +     * @param <U> the return type of the transformer
3942       * @return the result of accumulating the given transformation
3943       * of all keys
3944 +     * @since 1.8
3945       */
3946 <    @SuppressWarnings("unchecked") public <U> U reduceKeysSequentially
3947 <        (Function<? super K, ? extends U> transformer,
3946 >    public <U> U reduceKeys(long parallelismThreshold,
3947 >                            Function<? super K, ? extends U> transformer,
3948           BiFunction<? super U, ? super U, ? extends U> reducer) {
3949          if (transformer == null || reducer == null)
3950              throw new NullPointerException();
3951 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3952 <        U r = null, u;
3953 <        while (it.advance() != null) {
3490 <            if ((u = transformer.apply((K)it.nextKey)) != null)
3491 <                r = (r == null) ? u : reducer.apply(r, u);
3492 <        }
3493 <        return r;
3951 >        return new MapReduceKeysTask<K,V,U>
3952 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3953 >             null, transformer, reducer).invoke();
3954      }
3955  
3956      /**
# Line 3498 | Line 3958 | public class ConcurrentHashMap<K, V>
3958       * of all keys using the given reducer to combine values, and
3959       * the given basis as an identity value.
3960       *
3961 +     * @param parallelismThreshold the (estimated) number of elements
3962 +     * needed for this operation to be executed in parallel
3963       * @param transformer a function returning the transformation
3964       * for an element
3965       * @param basis the identity (initial default value) for the reduction
3966       * @param reducer a commutative associative combining function
3967       * @return the result of accumulating the given transformation
3968       * of all keys
3969 +     * @since 1.8
3970       */
3971 <    @SuppressWarnings("unchecked") public double reduceKeysToDoubleSequentially
3972 <        (DoubleFunction<? super K> transformer,
3973 <         double basis,
3974 <         DoubleBinaryOperator reducer) {
3971 >    public double reduceKeysToDouble(long parallelismThreshold,
3972 >                                     ToDoubleFunction<? super K> transformer,
3973 >                                     double basis,
3974 >                                     DoubleBinaryOperator reducer) {
3975          if (transformer == null || reducer == null)
3976              throw new NullPointerException();
3977 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3978 <        double r = basis;
3979 <        while (it.advance() != null)
3517 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)it.nextKey));
3518 <        return r;
3977 >        return new MapReduceKeysToDoubleTask<K,V>
3978 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3979 >             null, transformer, basis, reducer).invoke();
3980      }
3981  
3982      /**
# Line 3523 | Line 3984 | public class ConcurrentHashMap<K, V>
3984       * of all keys using the given reducer to combine values, and
3985       * the given basis as an identity value.
3986       *
3987 +     * @param parallelismThreshold the (estimated) number of elements
3988 +     * needed for this operation to be executed in parallel
3989       * @param transformer a function returning the transformation
3990       * for an element
3991       * @param basis the identity (initial default value) for the reduction
3992       * @param reducer a commutative associative combining function
3993       * @return the result of accumulating the given transformation
3994       * of all keys
3995 +     * @since 1.8
3996       */
3997 <    @SuppressWarnings("unchecked") public long reduceKeysToLongSequentially
3998 <        (LongFunction<? super K> transformer,
3999 <         long basis,
4000 <         LongBinaryOperator reducer) {
3997 >    public long reduceKeysToLong(long parallelismThreshold,
3998 >                                 ToLongFunction<? super K> transformer,
3999 >                                 long basis,
4000 >                                 LongBinaryOperator reducer) {
4001          if (transformer == null || reducer == null)
4002              throw new NullPointerException();
4003 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4004 <        long r = basis;
4005 <        while (it.advance() != null)
3542 <            r = reducer.applyAsLong(r, transformer.applyAsLong((K)it.nextKey));
3543 <        return r;
4003 >        return new MapReduceKeysToLongTask<K,V>
4004 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4005 >             null, transformer, basis, reducer).invoke();
4006      }
4007  
4008      /**
# Line 3548 | Line 4010 | public class ConcurrentHashMap<K, V>
4010       * of all keys using the given reducer to combine values, and
4011       * the given basis as an identity value.
4012       *
4013 +     * @param parallelismThreshold the (estimated) number of elements
4014 +     * needed for this operation to be executed in parallel
4015       * @param transformer a function returning the transformation
4016       * for an element
4017       * @param basis the identity (initial default value) for the reduction
4018       * @param reducer a commutative associative combining function
4019       * @return the result of accumulating the given transformation
4020       * of all keys
4021 +     * @since 1.8
4022       */
4023 <    @SuppressWarnings("unchecked") public int reduceKeysToIntSequentially
4024 <        (IntFunction<? super K> transformer,
4025 <         int basis,
4026 <         IntBinaryOperator reducer) {
4023 >    public int reduceKeysToInt(long parallelismThreshold,
4024 >                               ToIntFunction<? super K> transformer,
4025 >                               int basis,
4026 >                               IntBinaryOperator reducer) {
4027          if (transformer == null || reducer == null)
4028              throw new NullPointerException();
4029 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4030 <        int r = basis;
4031 <        while (it.advance() != null)
3567 <            r = reducer.applyAsInt(r, transformer.applyAsInt((K)it.nextKey));
3568 <        return r;
4029 >        return new MapReduceKeysToIntTask<K,V>
4030 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4031 >             null, transformer, basis, reducer).invoke();
4032      }
4033  
4034      /**
4035       * Performs the given action for each value.
4036       *
4037 +     * @param parallelismThreshold the (estimated) number of elements
4038 +     * needed for this operation to be executed in parallel
4039       * @param action the action
4040 +     * @since 1.8
4041       */
4042 <    public void forEachValueSequentially(Block<? super V> action) {
4043 <        if (action == null) throw new NullPointerException();
4044 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4045 <        V v;
4046 <        while ((v = it.advance()) != null)
4047 <            action.accept(v);
4042 >    public void forEachValue(long parallelismThreshold,
4043 >                             Consumer<? super V> action) {
4044 >        if (action == null)
4045 >            throw new NullPointerException();
4046 >        new ForEachValueTask<K,V>
4047 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4048 >             action).invoke();
4049      }
4050  
4051      /**
4052       * Performs the given action for each non-null transformation
4053       * of each value.
4054       *
4055 +     * @param parallelismThreshold the (estimated) number of elements
4056 +     * needed for this operation to be executed in parallel
4057       * @param transformer a function returning the transformation
4058 <     * for an element, or null of there is no transformation (in
4059 <     * which case the action is not applied).
4058 >     * for an element, or null if there is no transformation (in
4059 >     * which case the action is not applied)
4060 >     * @param action the action
4061 >     * @param <U> the return type of the transformer
4062 >     * @since 1.8
4063       */
4064 <    public <U> void forEachValueSequentially
4065 <        (Function<? super V, ? extends U> transformer,
4066 <         Block<? super U> action) {
4064 >    public <U> void forEachValue(long parallelismThreshold,
4065 >                                 Function<? super V, ? extends U> transformer,
4066 >                                 Consumer<? super U> action) {
4067          if (transformer == null || action == null)
4068              throw new NullPointerException();
4069 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4070 <        V v; U u;
4071 <        while ((v = it.advance()) != null) {
3600 <            if ((u = transformer.apply(v)) != null)
3601 <                action.accept(u);
3602 <        }
4069 >        new ForEachTransformedValueTask<K,V,U>
4070 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4071 >             transformer, action).invoke();
4072      }
4073  
4074      /**
4075       * Returns a non-null result from applying the given search
4076 <     * function on each value, or null if none.
4076 >     * function on each value, or null if none.  Upon success,
4077 >     * further element processing is suppressed and the results of
4078 >     * any other parallel invocations of the search function are
4079 >     * ignored.
4080       *
4081 +     * @param parallelismThreshold the (estimated) number of elements
4082 +     * needed for this operation to be executed in parallel
4083       * @param searchFunction a function returning a non-null
4084       * result on success, else null
4085 +     * @param <U> the return type of the search function
4086       * @return a non-null result from applying the given search
4087       * function on each value, or null if none
4088 +     * @since 1.8
4089       */
4090 <    public <U> U searchValuesSequentially
4091 <        (Function<? super V, ? extends U> searchFunction) {
4090 >    public <U> U searchValues(long parallelismThreshold,
4091 >                              Function<? super V, ? extends U> searchFunction) {
4092          if (searchFunction == null) throw new NullPointerException();
4093 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4094 <        V v; U u;
4095 <        while ((v = it.advance()) != null) {
3620 <            if ((u = searchFunction.apply(v)) != null)
3621 <                return u;
3622 <        }
3623 <        return null;
4093 >        return new SearchValuesTask<K,V,U>
4094 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4095 >             searchFunction, new AtomicReference<U>()).invoke();
4096      }
4097  
4098      /**
4099       * Returns the result of accumulating all values using the
4100       * given reducer to combine values, or null if none.
4101       *
4102 +     * @param parallelismThreshold the (estimated) number of elements
4103 +     * needed for this operation to be executed in parallel
4104       * @param reducer a commutative associative combining function
4105       * @return the result of accumulating all values
4106 +     * @since 1.8
4107       */
4108 <    public V reduceValuesSequentially
4109 <        (BiFunction<? super V, ? super V, ? extends V> reducer) {
4108 >    public V reduceValues(long parallelismThreshold,
4109 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
4110          if (reducer == null) throw new NullPointerException();
4111 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4112 <        V r = null; V v;
4113 <        while ((v = it.advance()) != null)
3639 <            r = (r == null) ? v : reducer.apply(r, v);
3640 <        return r;
4111 >        return new ReduceValuesTask<K,V>
4112 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4113 >             null, reducer).invoke();
4114      }
4115  
4116      /**
# Line 3645 | Line 4118 | public class ConcurrentHashMap<K, V>
4118       * of all values using the given reducer to combine values, or
4119       * null if none.
4120       *
4121 +     * @param parallelismThreshold the (estimated) number of elements
4122 +     * needed for this operation to be executed in parallel
4123       * @param transformer a function returning the transformation
4124 <     * for an element, or null of there is no transformation (in
4125 <     * which case it is not combined).
4124 >     * for an element, or null if there is no transformation (in
4125 >     * which case it is not combined)
4126       * @param reducer a commutative associative combining function
4127 +     * @param <U> the return type of the transformer
4128       * @return the result of accumulating the given transformation
4129       * of all values
4130 +     * @since 1.8
4131       */
4132 <    public <U> U reduceValuesSequentially
4133 <        (Function<? super V, ? extends U> transformer,
4134 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4132 >    public <U> U reduceValues(long parallelismThreshold,
4133 >                              Function<? super V, ? extends U> transformer,
4134 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
4135          if (transformer == null || reducer == null)
4136              throw new NullPointerException();
4137 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4138 <        U r = null, u; V v;
4139 <        while ((v = it.advance()) != null) {
3663 <            if ((u = transformer.apply(v)) != null)
3664 <                r = (r == null) ? u : reducer.apply(r, u);
3665 <        }
3666 <        return r;
4137 >        return new MapReduceValuesTask<K,V,U>
4138 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4139 >             null, transformer, reducer).invoke();
4140      }
4141  
4142      /**
# Line 3671 | Line 4144 | public class ConcurrentHashMap<K, V>
4144       * of all values using the given reducer to combine values,
4145       * and the given basis as an identity value.
4146       *
4147 +     * @param parallelismThreshold the (estimated) number of elements
4148 +     * needed for this operation to be executed in parallel
4149       * @param transformer a function returning the transformation
4150       * for an element
4151       * @param basis the identity (initial default value) for the reduction
4152       * @param reducer a commutative associative combining function
4153       * @return the result of accumulating the given transformation
4154       * of all values
4155 +     * @since 1.8
4156       */
4157 <    public double reduceValuesToDoubleSequentially
4158 <        (DoubleFunction<? super V> transformer,
4159 <         double basis,
4160 <         DoubleBinaryOperator reducer) {
4157 >    public double reduceValuesToDouble(long parallelismThreshold,
4158 >                                       ToDoubleFunction<? super V> transformer,
4159 >                                       double basis,
4160 >                                       DoubleBinaryOperator reducer) {
4161          if (transformer == null || reducer == null)
4162              throw new NullPointerException();
4163 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4164 <        double r = basis; V v;
4165 <        while ((v = it.advance()) != null)
3690 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
3691 <        return r;
4163 >        return new MapReduceValuesToDoubleTask<K,V>
4164 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4165 >             null, transformer, basis, reducer).invoke();
4166      }
4167  
4168      /**
# Line 3696 | Line 4170 | public class ConcurrentHashMap<K, V>
4170       * of all values using the given reducer to combine values,
4171       * and the given basis as an identity value.
4172       *
4173 +     * @param parallelismThreshold the (estimated) number of elements
4174 +     * needed for this operation to be executed in parallel
4175       * @param transformer a function returning the transformation
4176       * for an element
4177       * @param basis the identity (initial default value) for the reduction
4178       * @param reducer a commutative associative combining function
4179       * @return the result of accumulating the given transformation
4180       * of all values
4181 +     * @since 1.8
4182       */
4183 <    public long reduceValuesToLongSequentially
4184 <        (LongFunction<? super V> transformer,
4185 <         long basis,
4186 <         LongBinaryOperator reducer) {
4183 >    public long reduceValuesToLong(long parallelismThreshold,
4184 >                                   ToLongFunction<? super V> transformer,
4185 >                                   long basis,
4186 >                                   LongBinaryOperator reducer) {
4187          if (transformer == null || reducer == null)
4188              throw new NullPointerException();
4189 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4190 <        long r = basis; V v;
4191 <        while ((v = it.advance()) != null)
3715 <            r = reducer.applyAsLong(r, transformer.applyAsLong(v));
3716 <        return r;
4189 >        return new MapReduceValuesToLongTask<K,V>
4190 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4191 >             null, transformer, basis, reducer).invoke();
4192      }
4193  
4194      /**
# Line 3721 | Line 4196 | public class ConcurrentHashMap<K, V>
4196       * of all values using the given reducer to combine values,
4197       * and the given basis as an identity value.
4198       *
4199 +     * @param parallelismThreshold the (estimated) number of elements
4200 +     * needed for this operation to be executed in parallel
4201       * @param transformer a function returning the transformation
4202       * for an element
4203       * @param basis the identity (initial default value) for the reduction
4204       * @param reducer a commutative associative combining function
4205       * @return the result of accumulating the given transformation
4206       * of all values
4207 +     * @since 1.8
4208       */
4209 <    public int reduceValuesToIntSequentially
4210 <        (IntFunction<? super V> transformer,
4211 <         int basis,
4212 <         IntBinaryOperator reducer) {
4209 >    public int reduceValuesToInt(long parallelismThreshold,
4210 >                                 ToIntFunction<? super V> transformer,
4211 >                                 int basis,
4212 >                                 IntBinaryOperator reducer) {
4213          if (transformer == null || reducer == null)
4214              throw new NullPointerException();
4215 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4216 <        int r = basis; V v;
4217 <        while ((v = it.advance()) != null)
3740 <            r = reducer.applyAsInt(r, transformer.applyAsInt(v));
3741 <        return r;
4215 >        return new MapReduceValuesToIntTask<K,V>
4216 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4217 >             null, transformer, basis, reducer).invoke();
4218      }
4219  
4220      /**
4221       * Performs the given action for each entry.
4222       *
4223 +     * @param parallelismThreshold the (estimated) number of elements
4224 +     * needed for this operation to be executed in parallel
4225       * @param action the action
4226 +     * @since 1.8
4227       */
4228 <    @SuppressWarnings("unchecked") public void forEachEntrySequentially
4229 <        (Block<? super Map.Entry<K,V>> action) {
4228 >    public void forEachEntry(long parallelismThreshold,
4229 >                             Consumer<? super Map.Entry<K,V>> action) {
4230          if (action == null) throw new NullPointerException();
4231 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4232 <        V v;
3754 <        while ((v = it.advance()) != null)
3755 <            action.accept(entryFor((K)it.nextKey, v));
4231 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4232 >                                  action).invoke();
4233      }
4234  
4235      /**
4236       * Performs the given action for each non-null transformation
4237       * of each entry.
4238       *
4239 +     * @param parallelismThreshold the (estimated) number of elements
4240 +     * needed for this operation to be executed in parallel
4241       * @param transformer a function returning the transformation
4242 <     * for an element, or null of there is no transformation (in
4243 <     * which case the action is not applied).
4242 >     * for an element, or null if there is no transformation (in
4243 >     * which case the action is not applied)
4244       * @param action the action
4245 +     * @param <U> the return type of the transformer
4246 +     * @since 1.8
4247       */
4248 <    @SuppressWarnings("unchecked") public <U> void forEachEntrySequentially
4249 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4250 <         Block<? super U> action) {
4248 >    public <U> void forEachEntry(long parallelismThreshold,
4249 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
4250 >                                 Consumer<? super U> action) {
4251          if (transformer == null || action == null)
4252              throw new NullPointerException();
4253 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4254 <        V v; U u;
4255 <        while ((v = it.advance()) != null) {
3775 <            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3776 <                action.accept(u);
3777 <        }
4253 >        new ForEachTransformedEntryTask<K,V,U>
4254 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4255 >             transformer, action).invoke();
4256      }
4257  
4258      /**
4259       * Returns a non-null result from applying the given search
4260 <     * function on each entry, or null if none.
4260 >     * function on each entry, or null if none.  Upon success,
4261 >     * further element processing is suppressed and the results of
4262 >     * any other parallel invocations of the search function are
4263 >     * ignored.
4264       *
4265 +     * @param parallelismThreshold the (estimated) number of elements
4266 +     * needed for this operation to be executed in parallel
4267       * @param searchFunction a function returning a non-null
4268       * result on success, else null
4269 +     * @param <U> the return type of the search function
4270       * @return a non-null result from applying the given search
4271       * function on each entry, or null if none
4272 +     * @since 1.8
4273       */
4274 <    @SuppressWarnings("unchecked") public <U> U searchEntriesSequentially
4275 <        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4274 >    public <U> U searchEntries(long parallelismThreshold,
4275 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4276          if (searchFunction == null) throw new NullPointerException();
4277 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4278 <        V v; U u;
4279 <        while ((v = it.advance()) != null) {
3795 <            if ((u = searchFunction.apply(entryFor((K)it.nextKey, v))) != null)
3796 <                return u;
3797 <        }
3798 <        return null;
4277 >        return new SearchEntriesTask<K,V,U>
4278 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4279 >             searchFunction, new AtomicReference<U>()).invoke();
4280      }
4281  
4282      /**
4283       * Returns the result of accumulating all entries using the
4284       * given reducer to combine values, or null if none.
4285       *
4286 +     * @param parallelismThreshold the (estimated) number of elements
4287 +     * needed for this operation to be executed in parallel
4288       * @param reducer a commutative associative combining function
4289       * @return the result of accumulating all entries
4290 +     * @since 1.8
4291       */
4292 <    @SuppressWarnings("unchecked") public Map.Entry<K,V> reduceEntriesSequentially
4293 <        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4292 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4293 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4294          if (reducer == null) throw new NullPointerException();
4295 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4296 <        Map.Entry<K,V> r = null; V v;
4297 <        while ((v = it.advance()) != null) {
3814 <            Map.Entry<K,V> u = entryFor((K)it.nextKey, v);
3815 <            r = (r == null) ? u : reducer.apply(r, u);
3816 <        }
3817 <        return r;
4295 >        return new ReduceEntriesTask<K,V>
4296 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4297 >             null, reducer).invoke();
4298      }
4299  
4300      /**
# Line 3822 | Line 4302 | public class ConcurrentHashMap<K, V>
4302       * of all entries using the given reducer to combine values,
4303       * or null if none.
4304       *
4305 +     * @param parallelismThreshold the (estimated) number of elements
4306 +     * needed for this operation to be executed in parallel
4307       * @param transformer a function returning the transformation
4308 <     * for an element, or null of there is no transformation (in
4309 <     * which case it is not combined).
4308 >     * for an element, or null if there is no transformation (in
4309 >     * which case it is not combined)
4310       * @param reducer a commutative associative combining function
4311 +     * @param <U> the return type of the transformer
4312       * @return the result of accumulating the given transformation
4313       * of all entries
4314 +     * @since 1.8
4315       */
4316 <    @SuppressWarnings("unchecked") public <U> U reduceEntriesSequentially
4317 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4318 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4316 >    public <U> U reduceEntries(long parallelismThreshold,
4317 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
4318 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
4319          if (transformer == null || reducer == null)
4320              throw new NullPointerException();
4321 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4322 <        U r = null, u; V v;
4323 <        while ((v = it.advance()) != null) {
3840 <            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3841 <                r = (r == null) ? u : reducer.apply(r, u);
3842 <        }
3843 <        return r;
4321 >        return new MapReduceEntriesTask<K,V,U>
4322 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4323 >             null, transformer, reducer).invoke();
4324      }
4325  
4326      /**
# Line 3848 | Line 4328 | public class ConcurrentHashMap<K, V>
4328       * of all entries using the given reducer to combine values,
4329       * and the given basis as an identity value.
4330       *
4331 +     * @param parallelismThreshold the (estimated) number of elements
4332 +     * needed for this operation to be executed in parallel
4333       * @param transformer a function returning the transformation
4334       * for an element
4335       * @param basis the identity (initial default value) for the reduction
4336       * @param reducer a commutative associative combining function
4337       * @return the result of accumulating the given transformation
4338       * of all entries
4339 +     * @since 1.8
4340       */
4341 <    @SuppressWarnings("unchecked") public double reduceEntriesToDoubleSequentially
4342 <        (DoubleFunction<Map.Entry<K,V>> transformer,
4343 <         double basis,
4344 <         DoubleBinaryOperator reducer) {
4341 >    public double reduceEntriesToDouble(long parallelismThreshold,
4342 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
4343 >                                        double basis,
4344 >                                        DoubleBinaryOperator reducer) {
4345          if (transformer == null || reducer == null)
4346              throw new NullPointerException();
4347 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4348 <        double r = basis; V v;
4349 <        while ((v = it.advance()) != null)
3867 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor((K)it.nextKey, v)));
3868 <        return r;
4347 >        return new MapReduceEntriesToDoubleTask<K,V>
4348 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4349 >             null, transformer, basis, reducer).invoke();
4350      }
4351  
4352      /**
# Line 3873 | Line 4354 | public class ConcurrentHashMap<K, V>
4354       * of all entries using the given reducer to combine values,
4355       * and the given basis as an identity value.
4356       *
4357 +     * @param parallelismThreshold the (estimated) number of elements
4358 +     * needed for this operation to be executed in parallel
4359       * @param transformer a function returning the transformation
4360       * for an element
4361       * @param basis the identity (initial default value) for the reduction
4362       * @param reducer a commutative associative combining function
4363       * @return the result of accumulating the given transformation
4364       * of all entries
4365 +     * @since 1.8
4366       */
4367 <    @SuppressWarnings("unchecked") public long reduceEntriesToLongSequentially
4368 <        (LongFunction<Map.Entry<K,V>> transformer,
4369 <         long basis,
4370 <         LongBinaryOperator reducer) {
4367 >    public long reduceEntriesToLong(long parallelismThreshold,
4368 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
4369 >                                    long basis,
4370 >                                    LongBinaryOperator reducer) {
4371          if (transformer == null || reducer == null)
4372              throw new NullPointerException();
4373 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4374 <        long r = basis; V v;
4375 <        while ((v = it.advance()) != null)
3892 <            r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor((K)it.nextKey, v)));
3893 <        return r;
4373 >        return new MapReduceEntriesToLongTask<K,V>
4374 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4375 >             null, transformer, basis, reducer).invoke();
4376      }
4377  
4378      /**
# Line 3898 | Line 4380 | public class ConcurrentHashMap<K, V>
4380       * of all entries using the given reducer to combine values,
4381       * and the given basis as an identity value.
4382       *
4383 +     * @param parallelismThreshold the (estimated) number of elements
4384 +     * needed for this operation to be executed in parallel
4385       * @param transformer a function returning the transformation
4386       * for an element
4387       * @param basis the identity (initial default value) for the reduction
4388       * @param reducer a commutative associative combining function
4389       * @return the result of accumulating the given transformation
4390       * of all entries
4391 +     * @since 1.8
4392       */
4393 <    @SuppressWarnings("unchecked") public int reduceEntriesToIntSequentially
4394 <        (IntFunction<Map.Entry<K,V>> transformer,
4395 <         int basis,
4396 <         IntBinaryOperator reducer) {
4393 >    public int reduceEntriesToInt(long parallelismThreshold,
4394 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
4395 >                                  int basis,
4396 >                                  IntBinaryOperator reducer) {
4397          if (transformer == null || reducer == null)
4398              throw new NullPointerException();
4399 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4400 <        int r = basis; V v;
4401 <        while ((v = it.advance()) != null)
3917 <            r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor((K)it.nextKey, v)));
3918 <        return r;
3919 <    }
3920 <
3921 <    // Parallel bulk operations
3922 <
3923 <    /**
3924 <     * Performs the given action for each (key, value).
3925 <     *
3926 <     * @param action the action
3927 <     */
3928 <    public void forEachInParallel(BiBlock<? super K,? super V> action) {
3929 <        ForkJoinTasks.forEach
3930 <            (this, action).invoke();
3931 <    }
3932 <
3933 <    /**
3934 <     * Performs the given action for each non-null transformation
3935 <     * of each (key, value).
3936 <     *
3937 <     * @param transformer a function returning the transformation
3938 <     * for an element, or null of there is no transformation (in
3939 <     * which case the action is not applied).
3940 <     * @param action the action
3941 <     */
3942 <    public <U> void forEachInParallel
3943 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3944 <                            Block<? super U> action) {
3945 <        ForkJoinTasks.forEach
3946 <            (this, transformer, action).invoke();
3947 <    }
3948 <
3949 <    /**
3950 <     * Returns a non-null result from applying the given search
3951 <     * function on each (key, value), or null if none.  Upon
3952 <     * success, further element processing is suppressed and the
3953 <     * results of any other parallel invocations of the search
3954 <     * function are ignored.
3955 <     *
3956 <     * @param searchFunction a function returning a non-null
3957 <     * result on success, else null
3958 <     * @return a non-null result from applying the given search
3959 <     * function on each (key, value), or null if none
3960 <     */
3961 <    public <U> U searchInParallel
3962 <        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3963 <        return ForkJoinTasks.search
3964 <            (this, searchFunction).invoke();
3965 <    }
3966 <
3967 <    /**
3968 <     * Returns the result of accumulating the given transformation
3969 <     * of all (key, value) pairs using the given reducer to
3970 <     * combine values, or null if none.
3971 <     *
3972 <     * @param transformer a function returning the transformation
3973 <     * for an element, or null of there is no transformation (in
3974 <     * which case it is not combined).
3975 <     * @param reducer a commutative associative combining function
3976 <     * @return the result of accumulating the given transformation
3977 <     * of all (key, value) pairs
3978 <     */
3979 <    public <U> U reduceInParallel
3980 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3981 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
3982 <        return ForkJoinTasks.reduce
3983 <            (this, transformer, reducer).invoke();
3984 <    }
3985 <
3986 <    /**
3987 <     * Returns the result of accumulating the given transformation
3988 <     * of all (key, value) pairs using the given reducer to
3989 <     * combine values, and the given basis as an identity value.
3990 <     *
3991 <     * @param transformer a function returning the transformation
3992 <     * for an element
3993 <     * @param basis the identity (initial default value) for the reduction
3994 <     * @param reducer a commutative associative combining function
3995 <     * @return the result of accumulating the given transformation
3996 <     * of all (key, value) pairs
3997 <     */
3998 <    public double reduceToDoubleInParallel
3999 <        (DoubleBiFunction<? super K, ? super V> transformer,
4000 <         double basis,
4001 <         DoubleBinaryOperator reducer) {
4002 <        return ForkJoinTasks.reduceToDouble
4003 <            (this, transformer, basis, reducer).invoke();
4004 <    }
4005 <
4006 <    /**
4007 <     * Returns the result of accumulating the given transformation
4008 <     * of all (key, value) pairs using the given reducer to
4009 <     * combine values, and the given basis as an identity value.
4010 <     *
4011 <     * @param transformer a function returning the transformation
4012 <     * for an element
4013 <     * @param basis the identity (initial default value) for the reduction
4014 <     * @param reducer a commutative associative combining function
4015 <     * @return the result of accumulating the given transformation
4016 <     * of all (key, value) pairs
4017 <     */
4018 <    public long reduceToLongInParallel
4019 <        (LongBiFunction<? super K, ? super V> transformer,
4020 <         long basis,
4021 <         LongBinaryOperator reducer) {
4022 <        return ForkJoinTasks.reduceToLong
4023 <            (this, transformer, basis, reducer).invoke();
4024 <    }
4025 <
4026 <    /**
4027 <     * Returns the result of accumulating the given transformation
4028 <     * of all (key, value) pairs using the given reducer to
4029 <     * combine values, and the given basis as an identity value.
4030 <     *
4031 <     * @param transformer a function returning the transformation
4032 <     * for an element
4033 <     * @param basis the identity (initial default value) for the reduction
4034 <     * @param reducer a commutative associative combining function
4035 <     * @return the result of accumulating the given transformation
4036 <     * of all (key, value) pairs
4037 <     */
4038 <    public int reduceToIntInParallel
4039 <        (IntBiFunction<? super K, ? super V> transformer,
4040 <         int basis,
4041 <         IntBinaryOperator reducer) {
4042 <        return ForkJoinTasks.reduceToInt
4043 <            (this, transformer, basis, reducer).invoke();
4044 <    }
4045 <
4046 <    /**
4047 <     * Performs the given action for each key.
4048 <     *
4049 <     * @param action the action
4050 <     */
4051 <    public void forEachKeyInParallel(Block<? super K> action) {
4052 <        ForkJoinTasks.forEachKey
4053 <            (this, action).invoke();
4054 <    }
4055 <
4056 <    /**
4057 <     * Performs the given action for each non-null transformation
4058 <     * of each key.
4059 <     *
4060 <     * @param transformer a function returning the transformation
4061 <     * for an element, or null of there is no transformation (in
4062 <     * which case the action is not applied).
4063 <     * @param action the action
4064 <     */
4065 <    public <U> void forEachKeyInParallel
4066 <        (Function<? super K, ? extends U> transformer,
4067 <         Block<? super U> action) {
4068 <        ForkJoinTasks.forEachKey
4069 <            (this, transformer, action).invoke();
4070 <    }
4071 <
4072 <    /**
4073 <     * Returns a non-null result from applying the given search
4074 <     * function on each key, or null if none. Upon success,
4075 <     * further element processing is suppressed and the results of
4076 <     * any other parallel invocations of the search function are
4077 <     * ignored.
4078 <     *
4079 <     * @param searchFunction a function returning a non-null
4080 <     * result on success, else null
4081 <     * @return a non-null result from applying the given search
4082 <     * function on each key, or null if none
4083 <     */
4084 <    public <U> U searchKeysInParallel
4085 <        (Function<? super K, ? extends U> searchFunction) {
4086 <        return ForkJoinTasks.searchKeys
4087 <            (this, searchFunction).invoke();
4088 <    }
4089 <
4090 <    /**
4091 <     * Returns the result of accumulating all keys using the given
4092 <     * reducer to combine values, or null if none.
4093 <     *
4094 <     * @param reducer a commutative associative combining function
4095 <     * @return the result of accumulating all keys using the given
4096 <     * reducer to combine values, or null if none
4097 <     */
4098 <    public K reduceKeysInParallel
4099 <        (BiFunction<? super K, ? super K, ? extends K> reducer) {
4100 <        return ForkJoinTasks.reduceKeys
4101 <            (this, reducer).invoke();
4102 <    }
4103 <
4104 <    /**
4105 <     * Returns the result of accumulating the given transformation
4106 <     * of all keys using the given reducer to combine values, or
4107 <     * null if none.
4108 <     *
4109 <     * @param transformer a function returning the transformation
4110 <     * for an element, or null of there is no transformation (in
4111 <     * which case it is not combined).
4112 <     * @param reducer a commutative associative combining function
4113 <     * @return the result of accumulating the given transformation
4114 <     * of all keys
4115 <     */
4116 <    public <U> U reduceKeysInParallel
4117 <        (Function<? super K, ? extends U> transformer,
4118 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4119 <        return ForkJoinTasks.reduceKeys
4120 <            (this, transformer, reducer).invoke();
4121 <    }
4122 <
4123 <    /**
4124 <     * Returns the result of accumulating the given transformation
4125 <     * of all keys using the given reducer to combine values, and
4126 <     * the given basis as an identity value.
4127 <     *
4128 <     * @param transformer a function returning the transformation
4129 <     * for an element
4130 <     * @param basis the identity (initial default value) for the reduction
4131 <     * @param reducer a commutative associative combining function
4132 <     * @return the result of accumulating the given transformation
4133 <     * of all keys
4134 <     */
4135 <    public double reduceKeysToDoubleInParallel
4136 <        (DoubleFunction<? super K> transformer,
4137 <         double basis,
4138 <         DoubleBinaryOperator reducer) {
4139 <        return ForkJoinTasks.reduceKeysToDouble
4140 <            (this, transformer, basis, reducer).invoke();
4141 <    }
4142 <
4143 <    /**
4144 <     * Returns the result of accumulating the given transformation
4145 <     * of all keys using the given reducer to combine values, and
4146 <     * the given basis as an identity value.
4147 <     *
4148 <     * @param transformer a function returning the transformation
4149 <     * for an element
4150 <     * @param basis the identity (initial default value) for the reduction
4151 <     * @param reducer a commutative associative combining function
4152 <     * @return the result of accumulating the given transformation
4153 <     * of all keys
4154 <     */
4155 <    public long reduceKeysToLongInParallel
4156 <        (LongFunction<? super K> transformer,
4157 <         long basis,
4158 <         LongBinaryOperator reducer) {
4159 <        return ForkJoinTasks.reduceKeysToLong
4160 <            (this, transformer, basis, reducer).invoke();
4161 <    }
4162 <
4163 <    /**
4164 <     * Returns the result of accumulating the given transformation
4165 <     * of all keys using the given reducer to combine values, and
4166 <     * the given basis as an identity value.
4167 <     *
4168 <     * @param transformer a function returning the transformation
4169 <     * for an element
4170 <     * @param basis the identity (initial default value) for the reduction
4171 <     * @param reducer a commutative associative combining function
4172 <     * @return the result of accumulating the given transformation
4173 <     * of all keys
4174 <     */
4175 <    public int reduceKeysToIntInParallel
4176 <        (IntFunction<? super K> transformer,
4177 <         int basis,
4178 <         IntBinaryOperator reducer) {
4179 <        return ForkJoinTasks.reduceKeysToInt
4180 <            (this, transformer, basis, reducer).invoke();
4181 <    }
4182 <
4183 <    /**
4184 <     * Performs the given action for each value.
4185 <     *
4186 <     * @param action the action
4187 <     */
4188 <    public void forEachValueInParallel(Block<? super V> action) {
4189 <        ForkJoinTasks.forEachValue
4190 <            (this, action).invoke();
4191 <    }
4192 <
4193 <    /**
4194 <     * Performs the given action for each non-null transformation
4195 <     * of each value.
4196 <     *
4197 <     * @param transformer a function returning the transformation
4198 <     * for an element, or null of there is no transformation (in
4199 <     * which case the action is not applied).
4200 <     */
4201 <    public <U> void forEachValueInParallel
4202 <        (Function<? super V, ? extends U> transformer,
4203 <         Block<? super U> action) {
4204 <        ForkJoinTasks.forEachValue
4205 <            (this, transformer, action).invoke();
4206 <    }
4207 <
4208 <    /**
4209 <     * Returns a non-null result from applying the given search
4210 <     * function on each value, or null if none.  Upon success,
4211 <     * further element processing is suppressed and the results of
4212 <     * any other parallel invocations of the search function are
4213 <     * ignored.
4214 <     *
4215 <     * @param searchFunction a function returning a non-null
4216 <     * result on success, else null
4217 <     * @return a non-null result from applying the given search
4218 <     * function on each value, or null if none
4219 <     */
4220 <    public <U> U searchValuesInParallel
4221 <        (Function<? super V, ? extends U> searchFunction) {
4222 <        return ForkJoinTasks.searchValues
4223 <            (this, searchFunction).invoke();
4224 <    }
4225 <
4226 <    /**
4227 <     * Returns the result of accumulating all values using the
4228 <     * given reducer to combine values, or null if none.
4229 <     *
4230 <     * @param reducer a commutative associative combining function
4231 <     * @return the result of accumulating all values
4232 <     */
4233 <    public V reduceValuesInParallel
4234 <        (BiFunction<? super V, ? super V, ? extends V> reducer) {
4235 <        return ForkJoinTasks.reduceValues
4236 <            (this, reducer).invoke();
4237 <    }
4238 <
4239 <    /**
4240 <     * Returns the result of accumulating the given transformation
4241 <     * of all values using the given reducer to combine values, or
4242 <     * null if none.
4243 <     *
4244 <     * @param transformer a function returning the transformation
4245 <     * for an element, or null of there is no transformation (in
4246 <     * which case it is not combined).
4247 <     * @param reducer a commutative associative combining function
4248 <     * @return the result of accumulating the given transformation
4249 <     * of all values
4250 <     */
4251 <    public <U> U reduceValuesInParallel
4252 <        (Function<? super V, ? extends U> transformer,
4253 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4254 <        return ForkJoinTasks.reduceValues
4255 <            (this, transformer, reducer).invoke();
4256 <    }
4257 <
4258 <    /**
4259 <     * Returns the result of accumulating the given transformation
4260 <     * of all values using the given reducer to combine values,
4261 <     * and the given basis as an identity value.
4262 <     *
4263 <     * @param transformer a function returning the transformation
4264 <     * for an element
4265 <     * @param basis the identity (initial default value) for the reduction
4266 <     * @param reducer a commutative associative combining function
4267 <     * @return the result of accumulating the given transformation
4268 <     * of all values
4269 <     */
4270 <    public double reduceValuesToDoubleInParallel
4271 <        (DoubleFunction<? super V> transformer,
4272 <         double basis,
4273 <         DoubleBinaryOperator reducer) {
4274 <        return ForkJoinTasks.reduceValuesToDouble
4275 <            (this, transformer, basis, reducer).invoke();
4276 <    }
4277 <
4278 <    /**
4279 <     * Returns the result of accumulating the given transformation
4280 <     * of all values using the given reducer to combine values,
4281 <     * and the given basis as an identity value.
4282 <     *
4283 <     * @param transformer a function returning the transformation
4284 <     * for an element
4285 <     * @param basis the identity (initial default value) for the reduction
4286 <     * @param reducer a commutative associative combining function
4287 <     * @return the result of accumulating the given transformation
4288 <     * of all values
4289 <     */
4290 <    public long reduceValuesToLongInParallel
4291 <        (LongFunction<? super V> transformer,
4292 <         long basis,
4293 <         LongBinaryOperator reducer) {
4294 <        return ForkJoinTasks.reduceValuesToLong
4295 <            (this, transformer, basis, reducer).invoke();
4296 <    }
4297 <
4298 <    /**
4299 <     * Returns the result of accumulating the given transformation
4300 <     * of all values using the given reducer to combine values,
4301 <     * and the given basis as an identity value.
4302 <     *
4303 <     * @param transformer a function returning the transformation
4304 <     * for an element
4305 <     * @param basis the identity (initial default value) for the reduction
4306 <     * @param reducer a commutative associative combining function
4307 <     * @return the result of accumulating the given transformation
4308 <     * of all values
4309 <     */
4310 <    public int reduceValuesToIntInParallel
4311 <        (IntFunction<? super V> transformer,
4312 <         int basis,
4313 <         IntBinaryOperator reducer) {
4314 <        return ForkJoinTasks.reduceValuesToInt
4315 <            (this, transformer, basis, reducer).invoke();
4316 <    }
4317 <
4318 <    /**
4319 <     * Performs the given action for each entry.
4320 <     *
4321 <     * @param action the action
4322 <     */
4323 <    public void forEachEntryInParallel(Block<? super Map.Entry<K,V>> action) {
4324 <        ForkJoinTasks.forEachEntry
4325 <            (this, action).invoke();
4326 <    }
4327 <
4328 <    /**
4329 <     * Performs the given action for each non-null transformation
4330 <     * of each entry.
4331 <     *
4332 <     * @param transformer a function returning the transformation
4333 <     * for an element, or null of there is no transformation (in
4334 <     * which case the action is not applied).
4335 <     * @param action the action
4336 <     */
4337 <    public <U> void forEachEntryInParallel
4338 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4339 <         Block<? super U> action) {
4340 <        ForkJoinTasks.forEachEntry
4341 <            (this, transformer, action).invoke();
4342 <    }
4343 <
4344 <    /**
4345 <     * Returns a non-null result from applying the given search
4346 <     * function on each entry, or null if none.  Upon success,
4347 <     * further element processing is suppressed and the results of
4348 <     * any other parallel invocations of the search function are
4349 <     * ignored.
4350 <     *
4351 <     * @param searchFunction a function returning a non-null
4352 <     * result on success, else null
4353 <     * @return a non-null result from applying the given search
4354 <     * function on each entry, or null if none
4355 <     */
4356 <    public <U> U searchEntriesInParallel
4357 <        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4358 <        return ForkJoinTasks.searchEntries
4359 <            (this, searchFunction).invoke();
4360 <    }
4361 <
4362 <    /**
4363 <     * Returns the result of accumulating all entries using the
4364 <     * given reducer to combine values, or null if none.
4365 <     *
4366 <     * @param reducer a commutative associative combining function
4367 <     * @return the result of accumulating all entries
4368 <     */
4369 <    public Map.Entry<K,V> reduceEntriesInParallel
4370 <        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4371 <        return ForkJoinTasks.reduceEntries
4372 <            (this, reducer).invoke();
4373 <    }
4374 <
4375 <    /**
4376 <     * Returns the result of accumulating the given transformation
4377 <     * of all entries using the given reducer to combine values,
4378 <     * or null if none.
4379 <     *
4380 <     * @param transformer a function returning the transformation
4381 <     * for an element, or null of there is no transformation (in
4382 <     * which case it is not combined).
4383 <     * @param reducer a commutative associative combining function
4384 <     * @return the result of accumulating the given transformation
4385 <     * of all entries
4386 <     */
4387 <    public <U> U reduceEntriesInParallel
4388 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4389 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4390 <        return ForkJoinTasks.reduceEntries
4391 <            (this, transformer, reducer).invoke();
4392 <    }
4393 <
4394 <    /**
4395 <     * Returns the result of accumulating the given transformation
4396 <     * of all entries using the given reducer to combine values,
4397 <     * and the given basis as an identity value.
4398 <     *
4399 <     * @param transformer a function returning the transformation
4400 <     * for an element
4401 <     * @param basis the identity (initial default value) for the reduction
4402 <     * @param reducer a commutative associative combining function
4403 <     * @return the result of accumulating the given transformation
4404 <     * of all entries
4405 <     */
4406 <    public double reduceEntriesToDoubleInParallel
4407 <        (DoubleFunction<Map.Entry<K,V>> transformer,
4408 <         double basis,
4409 <         DoubleBinaryOperator reducer) {
4410 <        return ForkJoinTasks.reduceEntriesToDouble
4411 <            (this, transformer, basis, reducer).invoke();
4412 <    }
4413 <
4414 <    /**
4415 <     * Returns the result of accumulating the given transformation
4416 <     * of all entries using the given reducer to combine values,
4417 <     * and the given basis as an identity value.
4418 <     *
4419 <     * @param transformer a function returning the transformation
4420 <     * for an element
4421 <     * @param basis the identity (initial default value) for the reduction
4422 <     * @param reducer a commutative associative combining function
4423 <     * @return the result of accumulating the given transformation
4424 <     * of all entries
4425 <     */
4426 <    public long reduceEntriesToLongInParallel
4427 <        (LongFunction<Map.Entry<K,V>> transformer,
4428 <         long basis,
4429 <         LongBinaryOperator reducer) {
4430 <        return ForkJoinTasks.reduceEntriesToLong
4431 <            (this, transformer, basis, reducer).invoke();
4432 <    }
4433 <
4434 <    /**
4435 <     * Returns the result of accumulating the given transformation
4436 <     * of all entries using the given reducer to combine values,
4437 <     * and the given basis as an identity value.
4438 <     *
4439 <     * @param transformer a function returning the transformation
4440 <     * for an element
4441 <     * @param basis the identity (initial default value) for the reduction
4442 <     * @param reducer a commutative associative combining function
4443 <     * @return the result of accumulating the given transformation
4444 <     * of all entries
4445 <     */
4446 <    public int reduceEntriesToIntInParallel
4447 <        (IntFunction<Map.Entry<K,V>> transformer,
4448 <         int basis,
4449 <         IntBinaryOperator reducer) {
4450 <        return ForkJoinTasks.reduceEntriesToInt
4451 <            (this, transformer, basis, reducer).invoke();
4399 >        return new MapReduceEntriesToIntTask<K,V>
4400 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4401 >             null, transformer, basis, reducer).invoke();
4402      }
4403  
4404  
# Line 4457 | Line 4407 | public class ConcurrentHashMap<K, V>
4407      /**
4408       * Base class for views.
4409       */
4410 <    abstract static class CHMView<K, V> implements java.io.Serializable {
4410 >    abstract static class CollectionView<K,V,E>
4411 >        implements Collection<E>, java.io.Serializable {
4412          private static final long serialVersionUID = 7249069246763182397L;
4413 <        final ConcurrentHashMap<K, V> map;
4414 <        CHMView(ConcurrentHashMap<K, V> map)  { this.map = map; }
4413 >        final ConcurrentHashMap<K,V> map;
4414 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4415  
4416          /**
4417           * Returns the map backing this view.
# Line 4469 | Line 4420 | public class ConcurrentHashMap<K, V>
4420           */
4421          public ConcurrentHashMap<K,V> getMap() { return map; }
4422  
4423 <        public final int size()                 { return map.size(); }
4424 <        public final boolean isEmpty()          { return map.isEmpty(); }
4425 <        public final void clear()               { map.clear(); }
4423 >        /**
4424 >         * Removes all of the elements from this view, by removing all
4425 >         * the mappings from the map backing this view.
4426 >         */
4427 >        public final void clear()      { map.clear(); }
4428 >        public final int size()        { return map.size(); }
4429 >        public final boolean isEmpty() { return map.isEmpty(); }
4430  
4431          // implementations below rely on concrete classes supplying these
4432 <        public abstract Iterator<?> iterator();
4432 >        // abstract methods
4433 >        /**
4434 >         * Returns an iterator over the elements in this collection.
4435 >         *
4436 >         * <p>The returned iterator is
4437 >         * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
4438 >         *
4439 >         * @return an iterator over the elements in this collection
4440 >         */
4441 >        public abstract Iterator<E> iterator();
4442          public abstract boolean contains(Object o);
4443          public abstract boolean remove(Object o);
4444  
4445 <        private static final String oomeMsg = "Required array size too large";
4445 >        private static final String OOME_MSG = "Required array size too large";
4446  
4447          public final Object[] toArray() {
4448              long sz = map.mappingCount();
4449 <            if (sz > (long)(MAX_ARRAY_SIZE))
4450 <                throw new OutOfMemoryError(oomeMsg);
4449 >            if (sz > MAX_ARRAY_SIZE)
4450 >                throw new OutOfMemoryError(OOME_MSG);
4451              int n = (int)sz;
4452              Object[] r = new Object[n];
4453              int i = 0;
4454 <            Iterator<?> it = iterator();
4491 <            while (it.hasNext()) {
4454 >            for (E e : this) {
4455                  if (i == n) {
4456                      if (n >= MAX_ARRAY_SIZE)
4457 <                        throw new OutOfMemoryError(oomeMsg);
4457 >                        throw new OutOfMemoryError(OOME_MSG);
4458                      if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4459                          n = MAX_ARRAY_SIZE;
4460                      else
4461                          n += (n >>> 1) + 1;
4462                      r = Arrays.copyOf(r, n);
4463                  }
4464 <                r[i++] = it.next();
4464 >                r[i++] = e;
4465              }
4466              return (i == n) ? r : Arrays.copyOf(r, i);
4467          }
4468  
4469 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4469 >        @SuppressWarnings("unchecked")
4470 >        public final <T> T[] toArray(T[] a) {
4471              long sz = map.mappingCount();
4472 <            if (sz > (long)(MAX_ARRAY_SIZE))
4473 <                throw new OutOfMemoryError(oomeMsg);
4472 >            if (sz > MAX_ARRAY_SIZE)
4473 >                throw new OutOfMemoryError(OOME_MSG);
4474              int m = (int)sz;
4475              T[] r = (a.length >= m) ? a :
4476                  (T[])java.lang.reflect.Array
4477                  .newInstance(a.getClass().getComponentType(), m);
4478              int n = r.length;
4479              int i = 0;
4480 <            Iterator<?> it = iterator();
4517 <            while (it.hasNext()) {
4480 >            for (E e : this) {
4481                  if (i == n) {
4482                      if (n >= MAX_ARRAY_SIZE)
4483 <                        throw new OutOfMemoryError(oomeMsg);
4483 >                        throw new OutOfMemoryError(OOME_MSG);
4484                      if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4485                          n = MAX_ARRAY_SIZE;
4486                      else
4487                          n += (n >>> 1) + 1;
4488                      r = Arrays.copyOf(r, n);
4489                  }
4490 <                r[i++] = (T)it.next();
4490 >                r[i++] = (T)e;
4491              }
4492              if (a == r && i < n) {
4493                  r[i] = null; // null-terminate
# Line 4533 | Line 4496 | public class ConcurrentHashMap<K, V>
4496              return (i == n) ? r : Arrays.copyOf(r, i);
4497          }
4498  
4499 <        public final int hashCode() {
4500 <            int h = 0;
4501 <            for (Iterator<?> it = iterator(); it.hasNext();)
4502 <                h += it.next().hashCode();
4503 <            return h;
4504 <        }
4505 <
4499 >        /**
4500 >         * Returns a string representation of this collection.
4501 >         * The string representation consists of the string representations
4502 >         * of the collection's elements in the order they are returned by
4503 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4504 >         * Adjacent elements are separated by the characters {@code ", "}
4505 >         * (comma and space).  Elements are converted to strings as by
4506 >         * {@link String#valueOf(Object)}.
4507 >         *
4508 >         * @return a string representation of this collection
4509 >         */
4510          public final String toString() {
4511              StringBuilder sb = new StringBuilder();
4512              sb.append('[');
4513 <            Iterator<?> it = iterator();
4513 >            Iterator<E> it = iterator();
4514              if (it.hasNext()) {
4515                  for (;;) {
4516                      Object e = it.next();
# Line 4558 | Line 4525 | public class ConcurrentHashMap<K, V>
4525  
4526          public final boolean containsAll(Collection<?> c) {
4527              if (c != this) {
4528 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4562 <                    Object e = it.next();
4528 >                for (Object e : c) {
4529                      if (e == null || !contains(e))
4530                          return false;
4531                  }
# Line 4567 | Line 4533 | public class ConcurrentHashMap<K, V>
4533              return true;
4534          }
4535  
4536 <        public final boolean removeAll(Collection<?> c) {
4536 >        public boolean removeAll(Collection<?> c) {
4537 >            if (c == null) throw new NullPointerException();
4538              boolean modified = false;
4539 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4540 <                if (c.contains(it.next())) {
4541 <                    it.remove();
4542 <                    modified = true;
4539 >            // Use (c instanceof Set) as a hint that lookup in c is as
4540 >            // efficient as this view
4541 >            Node<K,V>[] t;
4542 >            if ((t = map.table) == null) {
4543 >                return false;
4544 >            } else if (c instanceof Set<?> && c.size() > t.length) {
4545 >                for (Iterator<?> it = iterator(); it.hasNext(); ) {
4546 >                    if (c.contains(it.next())) {
4547 >                        it.remove();
4548 >                        modified = true;
4549 >                    }
4550                  }
4551 +            } else {
4552 +                for (Object e : c)
4553 +                    modified |= remove(e);
4554              }
4555              return modified;
4556          }
4557  
4558          public final boolean retainAll(Collection<?> c) {
4559 +            if (c == null) throw new NullPointerException();
4560              boolean modified = false;
4561 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4561 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4562                  if (!c.contains(it.next())) {
4563                      it.remove();
4564                      modified = true;
# Line 4594 | Line 4572 | public class ConcurrentHashMap<K, V>
4572      /**
4573       * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4574       * which additions may optionally be enabled by mapping to a
4575 <     * common value.  This class cannot be directly instantiated. See
4576 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4577 <     * {@link #newKeySet(int)}.
4575 >     * common value.  This class cannot be directly instantiated.
4576 >     * See {@link #keySet() keySet()},
4577 >     * {@link #keySet(Object) keySet(V)},
4578 >     * {@link #newKeySet() newKeySet()},
4579 >     * {@link #newKeySet(int) newKeySet(int)}.
4580 >     *
4581 >     * @since 1.8
4582       */
4583 <    public static class KeySetView<K,V> extends CHMView<K,V>
4583 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4584          implements Set<K>, java.io.Serializable {
4585          private static final long serialVersionUID = 7249069246763182397L;
4586          private final V value;
4587 <        KeySetView(ConcurrentHashMap<K, V> map, V value) {  // non-public
4587 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4588              super(map);
4589              this.value = value;
4590          }
# Line 4612 | Line 4594 | public class ConcurrentHashMap<K, V>
4594           * or {@code null} if additions are not supported.
4595           *
4596           * @return the default mapped value for additions, or {@code null}
4597 <         * if not supported.
4597 >         * if not supported
4598           */
4599          public V getMappedValue() { return value; }
4600  
4601 <        // implement Set API
4602 <
4601 >        /**
4602 >         * {@inheritDoc}
4603 >         * @throws NullPointerException if the specified key is null
4604 >         */
4605          public boolean contains(Object o) { return map.containsKey(o); }
4622        public boolean remove(Object o)   { return map.remove(o) != null; }
4606  
4607          /**
4608 <         * Returns a "weakly consistent" iterator that will never
4609 <         * throw {@link ConcurrentModificationException}, and
4610 <         * guarantees to traverse elements as they existed upon
4611 <         * construction of the iterator, and may (but is not
4612 <         * guaranteed to) reflect any modifications subsequent to
4613 <         * construction.
4608 >         * Removes the key from this map view, by removing the key (and its
4609 >         * corresponding value) from the backing map.  This method does
4610 >         * nothing if the key is not in the map.
4611 >         *
4612 >         * @param  o the key to be removed from the backing map
4613 >         * @return {@code true} if the backing map contained the specified key
4614 >         * @throws NullPointerException if the specified key is null
4615 >         */
4616 >        public boolean remove(Object o) { return map.remove(o) != null; }
4617 >
4618 >        /**
4619 >         * @return an iterator over the keys of the backing map
4620 >         */
4621 >        public Iterator<K> iterator() {
4622 >            Node<K,V>[] t;
4623 >            ConcurrentHashMap<K,V> m = map;
4624 >            int f = (t = m.table) == null ? 0 : t.length;
4625 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4626 >        }
4627 >
4628 >        /**
4629 >         * Adds the specified key to this set view by mapping the key to
4630 >         * the default mapped value in the backing map, if defined.
4631           *
4632 <         * @return an iterator over the keys of this map
4632 >         * @param e key to be added
4633 >         * @return {@code true} if this set changed as a result of the call
4634 >         * @throws NullPointerException if the specified key is null
4635 >         * @throws UnsupportedOperationException if no default mapped value
4636 >         * for additions was provided
4637           */
4634        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4638          public boolean add(K e) {
4639              V v;
4640              if ((v = value) == null)
4641                  throw new UnsupportedOperationException();
4642 <            if (e == null)
4640 <                throw new NullPointerException();
4641 <            return map.internalPut(e, v, true) == null;
4642 >            return map.putVal(e, v, true) == null;
4643          }
4644 +
4645 +        /**
4646 +         * Adds all of the elements in the specified collection to this set,
4647 +         * as if by calling {@link #add} on each one.
4648 +         *
4649 +         * @param c the elements to be inserted into this set
4650 +         * @return {@code true} if this set changed as a result of the call
4651 +         * @throws NullPointerException if the collection or any of its
4652 +         * elements are {@code null}
4653 +         * @throws UnsupportedOperationException if no default mapped value
4654 +         * for additions was provided
4655 +         */
4656          public boolean addAll(Collection<? extends K> c) {
4657              boolean added = false;
4658              V v;
4659              if ((v = value) == null)
4660                  throw new UnsupportedOperationException();
4661              for (K e : c) {
4662 <                if (e == null)
4650 <                    throw new NullPointerException();
4651 <                if (map.internalPut(e, v, true) == null)
4662 >                if (map.putVal(e, v, true) == null)
4663                      added = true;
4664              }
4665              return added;
4666          }
4667 +
4668 +        public int hashCode() {
4669 +            int h = 0;
4670 +            for (K e : this)
4671 +                h += e.hashCode();
4672 +            return h;
4673 +        }
4674 +
4675          public boolean equals(Object o) {
4676              Set<?> c;
4677              return ((o instanceof Set) &&
# Line 4660 | Line 4679 | public class ConcurrentHashMap<K, V>
4679                       (containsAll(c) && c.containsAll(this))));
4680          }
4681  
4682 <        public Stream<K> stream() {
4683 <            return Streams.stream(() -> new KeyIterator<K,V>(map), 0);
4682 >        public Spliterator<K> spliterator() {
4683 >            Node<K,V>[] t;
4684 >            ConcurrentHashMap<K,V> m = map;
4685 >            long n = m.sumCount();
4686 >            int f = (t = m.table) == null ? 0 : t.length;
4687 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4688          }
4689 <        public Stream<K> parallelStream() {
4690 <            return Streams.parallelStream(() -> new KeyIterator<K,V>(map, null),
4691 <                                          0);
4689 >
4690 >        public void forEach(Consumer<? super K> action) {
4691 >            if (action == null) throw new NullPointerException();
4692 >            Node<K,V>[] t;
4693 >            if ((t = map.table) != null) {
4694 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4695 >                for (Node<K,V> p; (p = it.advance()) != null; )
4696 >                    action.accept(p.key);
4697 >            }
4698          }
4699      }
4700  
4701      /**
4702       * A view of a ConcurrentHashMap as a {@link Collection} of
4703       * values, in which additions are disabled. This class cannot be
4704 <     * directly instantiated. See {@link #values},
4705 <     *
4706 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4707 <     * that will never throw {@link ConcurrentModificationException},
4708 <     * and guarantees to traverse elements as they existed upon
4709 <     * construction of the iterator, and may (but is not guaranteed to)
4710 <     * reflect any modifications subsequent to construction.
4711 <     */
4712 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4713 <        implements Collection<V> {
4685 <        ValuesView(ConcurrentHashMap<K, V> map)   { super(map); }
4686 <        public final boolean contains(Object o) { return map.containsValue(o); }
4704 >     * directly instantiated. See {@link #values()}.
4705 >     */
4706 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4707 >        implements Collection<V>, java.io.Serializable {
4708 >        private static final long serialVersionUID = 2249069246763182397L;
4709 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4710 >        public final boolean contains(Object o) {
4711 >            return map.containsValue(o);
4712 >        }
4713 >
4714          public final boolean remove(Object o) {
4715              if (o != null) {
4716 <                Iterator<V> it = new ValueIterator<K,V>(map);
4690 <                while (it.hasNext()) {
4716 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4717                      if (o.equals(it.next())) {
4718                          it.remove();
4719                          return true;
# Line 4697 | Line 4723 | public class ConcurrentHashMap<K, V>
4723              return false;
4724          }
4725  
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         */
4726          public final Iterator<V> iterator() {
4727 <            return new ValueIterator<K,V>(map);
4727 >            ConcurrentHashMap<K,V> m = map;
4728 >            Node<K,V>[] t;
4729 >            int f = (t = m.table) == null ? 0 : t.length;
4730 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4731          }
4732 +
4733          public final boolean add(V e) {
4734              throw new UnsupportedOperationException();
4735          }
# Line 4717 | Line 4737 | public class ConcurrentHashMap<K, V>
4737              throw new UnsupportedOperationException();
4738          }
4739  
4740 <        public Stream<V> stream() {
4741 <            return Streams.stream(() -> new ValueIterator<K,V>(map), 0);
4740 >        @Override public boolean removeAll(Collection<?> c) {
4741 >            if (c == null) throw new NullPointerException();
4742 >            boolean modified = false;
4743 >            for (Iterator<V> it = iterator(); it.hasNext();) {
4744 >                if (c.contains(it.next())) {
4745 >                    it.remove();
4746 >                    modified = true;
4747 >                }
4748 >            }
4749 >            return modified;
4750 >        }
4751 >
4752 >        public boolean removeIf(Predicate<? super V> filter) {
4753 >            return map.removeValueIf(filter);
4754          }
4755  
4756 <        public Stream<V> parallelStream() {
4757 <            return Streams.parallelStream(() -> new ValueIterator<K,V>(map, null),
4758 <                                          0);
4756 >        public Spliterator<V> spliterator() {
4757 >            Node<K,V>[] t;
4758 >            ConcurrentHashMap<K,V> m = map;
4759 >            long n = m.sumCount();
4760 >            int f = (t = m.table) == null ? 0 : t.length;
4761 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4762          }
4763  
4764 +        public void forEach(Consumer<? super V> action) {
4765 +            if (action == null) throw new NullPointerException();
4766 +            Node<K,V>[] t;
4767 +            if ((t = map.table) != null) {
4768 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4769 +                for (Node<K,V> p; (p = it.advance()) != null; )
4770 +                    action.accept(p.val);
4771 +            }
4772 +        }
4773      }
4774  
4775      /**
4776       * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4777       * entries.  This class cannot be directly instantiated. See
4778 <     * {@link #entrySet}.
4778 >     * {@link #entrySet()}.
4779       */
4780 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4781 <        implements Set<Map.Entry<K,V>> {
4782 <        EntrySetView(ConcurrentHashMap<K, V> map) { super(map); }
4783 <        public final boolean contains(Object o) {
4780 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4781 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4782 >        private static final long serialVersionUID = 2249069246763182397L;
4783 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4784 >
4785 >        public boolean contains(Object o) {
4786              Object k, v, r; Map.Entry<?,?> e;
4787              return ((o instanceof Map.Entry) &&
4788                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4744 | Line 4790 | public class ConcurrentHashMap<K, V>
4790                      (v = e.getValue()) != null &&
4791                      (v == r || v.equals(r)));
4792          }
4793 <        public final boolean remove(Object o) {
4793 >
4794 >        public boolean remove(Object o) {
4795              Object k, v; Map.Entry<?,?> e;
4796              return ((o instanceof Map.Entry) &&
4797                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4753 | Line 4800 | public class ConcurrentHashMap<K, V>
4800          }
4801  
4802          /**
4803 <         * Returns a "weakly consistent" iterator that will never
4757 <         * throw {@link ConcurrentModificationException}, and
4758 <         * guarantees to traverse elements as they existed upon
4759 <         * construction of the iterator, and may (but is not
4760 <         * guaranteed to) reflect any modifications subsequent to
4761 <         * construction.
4762 <         *
4763 <         * @return an iterator over the entries of this map
4803 >         * @return an iterator over the entries of the backing map
4804           */
4805 <        public final Iterator<Map.Entry<K,V>> iterator() {
4806 <            return new EntryIterator<K,V>(map);
4805 >        public Iterator<Map.Entry<K,V>> iterator() {
4806 >            ConcurrentHashMap<K,V> m = map;
4807 >            Node<K,V>[] t;
4808 >            int f = (t = m.table) == null ? 0 : t.length;
4809 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4810          }
4811  
4812 <        public final boolean add(Entry<K,V> e) {
4813 <            K key = e.getKey();
4771 <            V value = e.getValue();
4772 <            if (key == null || value == null)
4773 <                throw new NullPointerException();
4774 <            return map.internalPut(key, value, false) == null;
4812 >        public boolean add(Entry<K,V> e) {
4813 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4814          }
4815 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4815 >
4816 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4817              boolean added = false;
4818              for (Entry<K,V> e : c) {
4819                  if (add(e))
# Line 4781 | Line 4821 | public class ConcurrentHashMap<K, V>
4821              }
4822              return added;
4823          }
4784        public boolean equals(Object o) {
4785            Set<?> c;
4786            return ((o instanceof Set) &&
4787                    ((c = (Set<?>)o) == this ||
4788                     (containsAll(c) && c.containsAll(this))));
4789        }
4790
4791        public Stream<Map.Entry<K,V>> stream() {
4792            return Streams.stream(() -> new EntryIterator<K,V>(map), 0);
4793        }
4794
4795        public Stream<Map.Entry<K,V>> parallelStream() {
4796            return Streams.parallelStream(() -> new EntryIterator<K,V>(map, null),
4797                                          0);
4798        }
4799    }
4800
4801    // ---------------------------------------------------------------------
4802
4803    /**
4804     * Predefined tasks for performing bulk parallel operations on
4805     * ConcurrentHashMaps. These tasks follow the forms and rules used
4806     * for bulk operations. Each method has the same name, but returns
4807     * a task rather than invoking it. These methods may be useful in
4808     * custom applications such as submitting a task without waiting
4809     * for completion, using a custom pool, or combining with other
4810     * tasks.
4811     */
4812    public static class ForkJoinTasks {
4813        private ForkJoinTasks() {}
4824  
4825 <        /**
4826 <         * Returns a task that when invoked, performs the given
4817 <         * action for each (key, value)
4818 <         *
4819 <         * @param map the map
4820 <         * @param action the action
4821 <         * @return the task
4822 <         */
4823 <        public static <K,V> ForkJoinTask<Void> forEach
4824 <            (ConcurrentHashMap<K,V> map,
4825 <             BiBlock<? super K, ? super V> action) {
4826 <            if (action == null) throw new NullPointerException();
4827 <            return new ForEachMappingTask<K,V>(map, null, -1, action);
4825 >        public boolean removeIf(Predicate<? super Entry<K,V>> filter) {
4826 >            return map.removeEntryIf(filter);
4827          }
4828  
4829 <        /**
4830 <         * Returns a task that when invoked, performs the given
4831 <         * action for each non-null transformation of each (key, value)
4832 <         *
4833 <         * @param map the map
4834 <         * @param transformer a function returning the transformation
4835 <         * for an element, or null if there is no transformation (in
4836 <         * which case the action is not applied)
4837 <         * @param action the action
4838 <         * @return the task
4840 <         */
4841 <        public static <K,V,U> ForkJoinTask<Void> forEach
4842 <            (ConcurrentHashMap<K,V> map,
4843 <             BiFunction<? super K, ? super V, ? extends U> transformer,
4844 <             Block<? super U> action) {
4845 <            if (transformer == null || action == null)
4846 <                throw new NullPointerException();
4847 <            return new ForEachTransformedMappingTask<K,V,U>
4848 <                (map, null, -1, transformer, action);
4849 <        }
4850 <
4851 <        /**
4852 <         * Returns a task that when invoked, returns a non-null result
4853 <         * from applying the given search function on each (key,
4854 <         * value), or null if none. Upon success, further element
4855 <         * processing is suppressed and the results of any other
4856 <         * parallel invocations of the search function are ignored.
4857 <         *
4858 <         * @param map the map
4859 <         * @param searchFunction a function returning a non-null
4860 <         * result on success, else null
4861 <         * @return the task
4862 <         */
4863 <        public static <K,V,U> ForkJoinTask<U> search
4864 <            (ConcurrentHashMap<K,V> map,
4865 <             BiFunction<? super K, ? super V, ? extends U> searchFunction) {
4866 <            if (searchFunction == null) throw new NullPointerException();
4867 <            return new SearchMappingsTask<K,V,U>
4868 <                (map, null, -1, searchFunction,
4869 <                 new AtomicReference<U>());
4870 <        }
4871 <
4872 <        /**
4873 <         * Returns a task that when invoked, returns the result of
4874 <         * accumulating the given transformation of all (key, value) pairs
4875 <         * using the given reducer to combine values, or null if none.
4876 <         *
4877 <         * @param map the map
4878 <         * @param transformer a function returning the transformation
4879 <         * for an element, or null if there is no transformation (in
4880 <         * which case it is not combined).
4881 <         * @param reducer a commutative associative combining function
4882 <         * @return the task
4883 <         */
4884 <        public static <K,V,U> ForkJoinTask<U> reduce
4885 <            (ConcurrentHashMap<K,V> map,
4886 <             BiFunction<? super K, ? super V, ? extends U> transformer,
4887 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
4888 <            if (transformer == null || reducer == null)
4889 <                throw new NullPointerException();
4890 <            return new MapReduceMappingsTask<K,V,U>
4891 <                (map, null, -1, null, transformer, reducer);
4892 <        }
4893 <
4894 <        /**
4895 <         * Returns a task that when invoked, returns the result of
4896 <         * accumulating the given transformation of all (key, value) pairs
4897 <         * using the given reducer to combine values, and the given
4898 <         * basis as an identity value.
4899 <         *
4900 <         * @param map the map
4901 <         * @param transformer a function returning the transformation
4902 <         * for an element
4903 <         * @param basis the identity (initial default value) for the reduction
4904 <         * @param reducer a commutative associative combining function
4905 <         * @return the task
4906 <         */
4907 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4908 <            (ConcurrentHashMap<K,V> map,
4909 <             DoubleBiFunction<? super K, ? super V> transformer,
4910 <             double basis,
4911 <             DoubleBinaryOperator reducer) {
4912 <            if (transformer == null || reducer == null)
4913 <                throw new NullPointerException();
4914 <            return new MapReduceMappingsToDoubleTask<K,V>
4915 <                (map, null, -1, null, transformer, basis, reducer);
4916 <        }
4917 <
4918 <        /**
4919 <         * Returns a task that when invoked, returns the result of
4920 <         * accumulating the given transformation of all (key, value) pairs
4921 <         * using the given reducer to combine values, and the given
4922 <         * basis as an identity value.
4923 <         *
4924 <         * @param map the map
4925 <         * @param transformer a function returning the transformation
4926 <         * for an element
4927 <         * @param basis the identity (initial default value) for the reduction
4928 <         * @param reducer a commutative associative combining function
4929 <         * @return the task
4930 <         */
4931 <        public static <K,V> ForkJoinTask<Long> reduceToLong
4932 <            (ConcurrentHashMap<K,V> map,
4933 <             LongBiFunction<? super K, ? super V> transformer,
4934 <             long basis,
4935 <             LongBinaryOperator reducer) {
4936 <            if (transformer == null || reducer == null)
4937 <                throw new NullPointerException();
4938 <            return new MapReduceMappingsToLongTask<K,V>
4939 <                (map, null, -1, null, transformer, basis, reducer);
4940 <        }
4941 <
4942 <        /**
4943 <         * Returns a task that when invoked, returns the result of
4944 <         * accumulating the given transformation of all (key, value) pairs
4945 <         * using the given reducer to combine values, and the given
4946 <         * basis as an identity value.
4947 <         *
4948 <         * @param transformer a function returning the transformation
4949 <         * for an element
4950 <         * @param basis the identity (initial default value) for the reduction
4951 <         * @param reducer a commutative associative combining function
4952 <         * @return the task
4953 <         */
4954 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
4955 <            (ConcurrentHashMap<K,V> map,
4956 <             IntBiFunction<? super K, ? super V> transformer,
4957 <             int basis,
4958 <             IntBinaryOperator reducer) {
4959 <            if (transformer == null || reducer == null)
4960 <                throw new NullPointerException();
4961 <            return new MapReduceMappingsToIntTask<K,V>
4962 <                (map, null, -1, null, transformer, basis, reducer);
4963 <        }
4964 <
4965 <        /**
4966 <         * Returns a task that when invoked, performs the given action
4967 <         * for each key.
4968 <         *
4969 <         * @param map the map
4970 <         * @param action the action
4971 <         * @return the task
4972 <         */
4973 <        public static <K,V> ForkJoinTask<Void> forEachKey
4974 <            (ConcurrentHashMap<K,V> map,
4975 <             Block<? super K> action) {
4976 <            if (action == null) throw new NullPointerException();
4977 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
4978 <        }
4979 <
4980 <        /**
4981 <         * Returns a task that when invoked, performs the given action
4982 <         * for each non-null transformation of each key.
4983 <         *
4984 <         * @param map the map
4985 <         * @param transformer a function returning the transformation
4986 <         * for an element, or null if there is no transformation (in
4987 <         * which case the action is not applied)
4988 <         * @param action the action
4989 <         * @return the task
4990 <         */
4991 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
4992 <            (ConcurrentHashMap<K,V> map,
4993 <             Function<? super K, ? extends U> transformer,
4994 <             Block<? super U> action) {
4995 <            if (transformer == null || action == null)
4996 <                throw new NullPointerException();
4997 <            return new ForEachTransformedKeyTask<K,V,U>
4998 <                (map, null, -1, transformer, action);
4999 <        }
5000 <
5001 <        /**
5002 <         * Returns a task that when invoked, returns a non-null result
5003 <         * from applying the given search function on each key, or
5004 <         * null if none.  Upon success, further element processing is
5005 <         * suppressed and the results of any other parallel
5006 <         * invocations of the search function are ignored.
5007 <         *
5008 <         * @param map the map
5009 <         * @param searchFunction a function returning a non-null
5010 <         * result on success, else null
5011 <         * @return the task
5012 <         */
5013 <        public static <K,V,U> ForkJoinTask<U> searchKeys
5014 <            (ConcurrentHashMap<K,V> map,
5015 <             Function<? super K, ? extends U> searchFunction) {
5016 <            if (searchFunction == null) throw new NullPointerException();
5017 <            return new SearchKeysTask<K,V,U>
5018 <                (map, null, -1, searchFunction,
5019 <                 new AtomicReference<U>());
5020 <        }
5021 <
5022 <        /**
5023 <         * Returns a task that when invoked, returns the result of
5024 <         * accumulating all keys using the given reducer to combine
5025 <         * values, or null if none.
5026 <         *
5027 <         * @param map the map
5028 <         * @param reducer a commutative associative combining function
5029 <         * @return the task
5030 <         */
5031 <        public static <K,V> ForkJoinTask<K> reduceKeys
5032 <            (ConcurrentHashMap<K,V> map,
5033 <             BiFunction<? super K, ? super K, ? extends K> reducer) {
5034 <            if (reducer == null) throw new NullPointerException();
5035 <            return new ReduceKeysTask<K,V>
5036 <                (map, null, -1, null, reducer);
5037 <        }
5038 <
5039 <        /**
5040 <         * Returns a task that when invoked, returns the result of
5041 <         * accumulating the given transformation of all keys using the given
5042 <         * reducer to combine values, or null if none.
5043 <         *
5044 <         * @param map the map
5045 <         * @param transformer a function returning the transformation
5046 <         * for an element, or null if there is no transformation (in
5047 <         * which case it is not combined).
5048 <         * @param reducer a commutative associative combining function
5049 <         * @return the task
5050 <         */
5051 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
5052 <            (ConcurrentHashMap<K,V> map,
5053 <             Function<? super K, ? extends U> transformer,
5054 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5055 <            if (transformer == null || reducer == null)
5056 <                throw new NullPointerException();
5057 <            return new MapReduceKeysTask<K,V,U>
5058 <                (map, null, -1, null, transformer, reducer);
5059 <        }
5060 <
5061 <        /**
5062 <         * Returns a task that when invoked, returns the result of
5063 <         * accumulating the given transformation of all keys using the given
5064 <         * reducer to combine values, and the given basis as an
5065 <         * identity value.
5066 <         *
5067 <         * @param map the map
5068 <         * @param transformer a function returning the transformation
5069 <         * for an element
5070 <         * @param basis the identity (initial default value) for the reduction
5071 <         * @param reducer a commutative associative combining function
5072 <         * @return the task
5073 <         */
5074 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5075 <            (ConcurrentHashMap<K,V> map,
5076 <             DoubleFunction<? super K> transformer,
5077 <             double basis,
5078 <             DoubleBinaryOperator reducer) {
5079 <            if (transformer == null || reducer == null)
5080 <                throw new NullPointerException();
5081 <            return new MapReduceKeysToDoubleTask<K,V>
5082 <                (map, null, -1, null, transformer, basis, reducer);
5083 <        }
5084 <
5085 <        /**
5086 <         * Returns a task that when invoked, returns the result of
5087 <         * accumulating the given transformation of all keys using the given
5088 <         * reducer to combine values, and the given basis as an
5089 <         * identity value.
5090 <         *
5091 <         * @param map the map
5092 <         * @param transformer a function returning the transformation
5093 <         * for an element
5094 <         * @param basis the identity (initial default value) for the reduction
5095 <         * @param reducer a commutative associative combining function
5096 <         * @return the task
5097 <         */
5098 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5099 <            (ConcurrentHashMap<K,V> map,
5100 <             LongFunction<? super K> transformer,
5101 <             long basis,
5102 <             LongBinaryOperator reducer) {
5103 <            if (transformer == null || reducer == null)
5104 <                throw new NullPointerException();
5105 <            return new MapReduceKeysToLongTask<K,V>
5106 <                (map, null, -1, null, transformer, basis, reducer);
5107 <        }
5108 <
5109 <        /**
5110 <         * Returns a task that when invoked, returns the result of
5111 <         * accumulating the given transformation of all keys using the given
5112 <         * reducer to combine values, and the given basis as an
5113 <         * identity value.
5114 <         *
5115 <         * @param map the map
5116 <         * @param transformer a function returning the transformation
5117 <         * for an element
5118 <         * @param basis the identity (initial default value) for the reduction
5119 <         * @param reducer a commutative associative combining function
5120 <         * @return the task
5121 <         */
5122 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5123 <            (ConcurrentHashMap<K,V> map,
5124 <             IntFunction<? super K> transformer,
5125 <             int basis,
5126 <             IntBinaryOperator reducer) {
5127 <            if (transformer == null || reducer == null)
5128 <                throw new NullPointerException();
5129 <            return new MapReduceKeysToIntTask<K,V>
5130 <                (map, null, -1, null, transformer, basis, reducer);
5131 <        }
5132 <
5133 <        /**
5134 <         * Returns a task that when invoked, performs the given action
5135 <         * for each value.
5136 <         *
5137 <         * @param map the map
5138 <         * @param action the action
5139 <         */
5140 <        public static <K,V> ForkJoinTask<Void> forEachValue
5141 <            (ConcurrentHashMap<K,V> map,
5142 <             Block<? super V> action) {
5143 <            if (action == null) throw new NullPointerException();
5144 <            return new ForEachValueTask<K,V>(map, null, -1, action);
5145 <        }
5146 <
5147 <        /**
5148 <         * Returns a task that when invoked, performs the given action
5149 <         * for each non-null transformation of each value.
5150 <         *
5151 <         * @param map the map
5152 <         * @param transformer a function returning the transformation
5153 <         * for an element, or null if there is no transformation (in
5154 <         * which case the action is not applied)
5155 <         * @param action the action
5156 <         */
5157 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
5158 <            (ConcurrentHashMap<K,V> map,
5159 <             Function<? super V, ? extends U> transformer,
5160 <             Block<? super U> action) {
5161 <            if (transformer == null || action == null)
5162 <                throw new NullPointerException();
5163 <            return new ForEachTransformedValueTask<K,V,U>
5164 <                (map, null, -1, transformer, action);
5165 <        }
5166 <
5167 <        /**
5168 <         * Returns a task that when invoked, returns a non-null result
5169 <         * from applying the given search function on each value, or
5170 <         * null if none.  Upon success, further element processing is
5171 <         * suppressed and the results of any other parallel
5172 <         * invocations of the search function are ignored.
5173 <         *
5174 <         * @param map the map
5175 <         * @param searchFunction a function returning a non-null
5176 <         * result on success, else null
5177 <         * @return the task
5178 <         */
5179 <        public static <K,V,U> ForkJoinTask<U> searchValues
5180 <            (ConcurrentHashMap<K,V> map,
5181 <             Function<? super V, ? extends U> searchFunction) {
5182 <            if (searchFunction == null) throw new NullPointerException();
5183 <            return new SearchValuesTask<K,V,U>
5184 <                (map, null, -1, searchFunction,
5185 <                 new AtomicReference<U>());
5186 <        }
5187 <
5188 <        /**
5189 <         * Returns a task that when invoked, returns the result of
5190 <         * accumulating all values using the given reducer to combine
5191 <         * values, or null if none.
5192 <         *
5193 <         * @param map the map
5194 <         * @param reducer a commutative associative combining function
5195 <         * @return the task
5196 <         */
5197 <        public static <K,V> ForkJoinTask<V> reduceValues
5198 <            (ConcurrentHashMap<K,V> map,
5199 <             BiFunction<? super V, ? super V, ? extends V> reducer) {
5200 <            if (reducer == null) throw new NullPointerException();
5201 <            return new ReduceValuesTask<K,V>
5202 <                (map, null, -1, null, reducer);
5203 <        }
5204 <
5205 <        /**
5206 <         * Returns a task that when invoked, returns the result of
5207 <         * accumulating the given transformation of all values using the
5208 <         * given reducer to combine values, or null if none.
5209 <         *
5210 <         * @param map the map
5211 <         * @param transformer a function returning the transformation
5212 <         * for an element, or null if there is no transformation (in
5213 <         * which case it is not combined).
5214 <         * @param reducer a commutative associative combining function
5215 <         * @return the task
5216 <         */
5217 <        public static <K,V,U> ForkJoinTask<U> reduceValues
5218 <            (ConcurrentHashMap<K,V> map,
5219 <             Function<? super V, ? extends U> transformer,
5220 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5221 <            if (transformer == null || reducer == null)
5222 <                throw new NullPointerException();
5223 <            return new MapReduceValuesTask<K,V,U>
5224 <                (map, null, -1, null, transformer, reducer);
5225 <        }
5226 <
5227 <        /**
5228 <         * Returns a task that when invoked, returns the result of
5229 <         * accumulating the given transformation of all values using the
5230 <         * given reducer to combine values, and the given basis as an
5231 <         * identity value.
5232 <         *
5233 <         * @param map the map
5234 <         * @param transformer a function returning the transformation
5235 <         * for an element
5236 <         * @param basis the identity (initial default value) for the reduction
5237 <         * @param reducer a commutative associative combining function
5238 <         * @return the task
5239 <         */
5240 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5241 <            (ConcurrentHashMap<K,V> map,
5242 <             DoubleFunction<? super V> transformer,
5243 <             double basis,
5244 <             DoubleBinaryOperator reducer) {
5245 <            if (transformer == null || reducer == null)
5246 <                throw new NullPointerException();
5247 <            return new MapReduceValuesToDoubleTask<K,V>
5248 <                (map, null, -1, null, transformer, basis, reducer);
4829 >        public final int hashCode() {
4830 >            int h = 0;
4831 >            Node<K,V>[] t;
4832 >            if ((t = map.table) != null) {
4833 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4834 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4835 >                    h += p.hashCode();
4836 >                }
4837 >            }
4838 >            return h;
4839          }
4840  
4841 <        /**
4842 <         * Returns a task that when invoked, returns the result of
4843 <         * accumulating the given transformation of all values using the
4844 <         * given reducer to combine values, and the given basis as an
4845 <         * identity value.
5256 <         *
5257 <         * @param map the map
5258 <         * @param transformer a function returning the transformation
5259 <         * for an element
5260 <         * @param basis the identity (initial default value) for the reduction
5261 <         * @param reducer a commutative associative combining function
5262 <         * @return the task
5263 <         */
5264 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5265 <            (ConcurrentHashMap<K,V> map,
5266 <             LongFunction<? super V> transformer,
5267 <             long basis,
5268 <             LongBinaryOperator reducer) {
5269 <            if (transformer == null || reducer == null)
5270 <                throw new NullPointerException();
5271 <            return new MapReduceValuesToLongTask<K,V>
5272 <                (map, null, -1, null, transformer, basis, reducer);
4841 >        public final boolean equals(Object o) {
4842 >            Set<?> c;
4843 >            return ((o instanceof Set) &&
4844 >                    ((c = (Set<?>)o) == this ||
4845 >                     (containsAll(c) && c.containsAll(this))));
4846          }
4847  
4848 <        /**
4849 <         * Returns a task that when invoked, returns the result of
4850 <         * accumulating the given transformation of all values using the
4851 <         * given reducer to combine values, and the given basis as an
4852 <         * identity value.
4853 <         *
5281 <         * @param map the map
5282 <         * @param transformer a function returning the transformation
5283 <         * for an element
5284 <         * @param basis the identity (initial default value) for the reduction
5285 <         * @param reducer a commutative associative combining function
5286 <         * @return the task
5287 <         */
5288 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5289 <            (ConcurrentHashMap<K,V> map,
5290 <             IntFunction<? super V> transformer,
5291 <             int basis,
5292 <             IntBinaryOperator reducer) {
5293 <            if (transformer == null || reducer == null)
5294 <                throw new NullPointerException();
5295 <            return new MapReduceValuesToIntTask<K,V>
5296 <                (map, null, -1, null, transformer, basis, reducer);
4848 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4849 >            Node<K,V>[] t;
4850 >            ConcurrentHashMap<K,V> m = map;
4851 >            long n = m.sumCount();
4852 >            int f = (t = m.table) == null ? 0 : t.length;
4853 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4854          }
4855  
4856 <        /**
5300 <         * Returns a task that when invoked, perform the given action
5301 <         * for each entry.
5302 <         *
5303 <         * @param map the map
5304 <         * @param action the action
5305 <         */
5306 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5307 <            (ConcurrentHashMap<K,V> map,
5308 <             Block<? super Map.Entry<K,V>> action) {
4856 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4857              if (action == null) throw new NullPointerException();
4858 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
4859 <        }
4860 <
4861 <        /**
4862 <         * Returns a task that when invoked, perform the given action
4863 <         * for each non-null transformation of each entry.
5316 <         *
5317 <         * @param map the map
5318 <         * @param transformer a function returning the transformation
5319 <         * for an element, or null if there is no transformation (in
5320 <         * which case the action is not applied)
5321 <         * @param action the action
5322 <         */
5323 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5324 <            (ConcurrentHashMap<K,V> map,
5325 <             Function<Map.Entry<K,V>, ? extends U> transformer,
5326 <             Block<? super U> action) {
5327 <            if (transformer == null || action == null)
5328 <                throw new NullPointerException();
5329 <            return new ForEachTransformedEntryTask<K,V,U>
5330 <                (map, null, -1, transformer, action);
5331 <        }
5332 <
5333 <        /**
5334 <         * Returns a task that when invoked, returns a non-null result
5335 <         * from applying the given search function on each entry, or
5336 <         * null if none.  Upon success, further element processing is
5337 <         * suppressed and the results of any other parallel
5338 <         * invocations of the search function are ignored.
5339 <         *
5340 <         * @param map the map
5341 <         * @param searchFunction a function returning a non-null
5342 <         * result on success, else null
5343 <         * @return the task
5344 <         */
5345 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5346 <            (ConcurrentHashMap<K,V> map,
5347 <             Function<Map.Entry<K,V>, ? extends U> searchFunction) {
5348 <            if (searchFunction == null) throw new NullPointerException();
5349 <            return new SearchEntriesTask<K,V,U>
5350 <                (map, null, -1, searchFunction,
5351 <                 new AtomicReference<U>());
4858 >            Node<K,V>[] t;
4859 >            if ((t = map.table) != null) {
4860 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4861 >                for (Node<K,V> p; (p = it.advance()) != null; )
4862 >                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
4863 >            }
4864          }
4865  
4866 <        /**
5355 <         * Returns a task that when invoked, returns the result of
5356 <         * accumulating all entries using the given reducer to combine
5357 <         * values, or null if none.
5358 <         *
5359 <         * @param map the map
5360 <         * @param reducer a commutative associative combining function
5361 <         * @return the task
5362 <         */
5363 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5364 <            (ConcurrentHashMap<K,V> map,
5365 <             BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5366 <            if (reducer == null) throw new NullPointerException();
5367 <            return new ReduceEntriesTask<K,V>
5368 <                (map, null, -1, null, reducer);
5369 <        }
4866 >    }
4867  
4868 <        /**
5372 <         * Returns a task that when invoked, returns the result of
5373 <         * accumulating the given transformation of all entries using the
5374 <         * given reducer to combine values, or null if none.
5375 <         *
5376 <         * @param map the map
5377 <         * @param transformer a function returning the transformation
5378 <         * for an element, or null if there is no transformation (in
5379 <         * which case it is not combined).
5380 <         * @param reducer a commutative associative combining function
5381 <         * @return the task
5382 <         */
5383 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5384 <            (ConcurrentHashMap<K,V> map,
5385 <             Function<Map.Entry<K,V>, ? extends U> transformer,
5386 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5387 <            if (transformer == null || reducer == null)
5388 <                throw new NullPointerException();
5389 <            return new MapReduceEntriesTask<K,V,U>
5390 <                (map, null, -1, null, transformer, reducer);
5391 <        }
4868 >    // -------------------------------------------------------
4869  
4870 <        /**
4871 <         * Returns a task that when invoked, returns the result of
4872 <         * accumulating the given transformation of all entries using the
4873 <         * given reducer to combine values, and the given basis as an
4874 <         * identity value.
4875 <         *
4876 <         * @param map the map
4877 <         * @param transformer a function returning the transformation
4878 <         * for an element
4879 <         * @param basis the identity (initial default value) for the reduction
4880 <         * @param reducer a commutative associative combining function
4881 <         * @return the task
4882 <         */
4883 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
4884 <            (ConcurrentHashMap<K,V> map,
4885 <             DoubleFunction<Map.Entry<K,V>> transformer,
4886 <             double basis,
4887 <             DoubleBinaryOperator reducer) {
4888 <            if (transformer == null || reducer == null)
4889 <                throw new NullPointerException();
4890 <            return new MapReduceEntriesToDoubleTask<K,V>
4891 <                (map, null, -1, null, transformer, basis, reducer);
4870 >    /**
4871 >     * Base class for bulk tasks. Repeats some fields and code from
4872 >     * class Traverser, because we need to subclass CountedCompleter.
4873 >     */
4874 >    @SuppressWarnings("serial")
4875 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4876 >        Node<K,V>[] tab;        // same as Traverser
4877 >        Node<K,V> next;
4878 >        TableStack<K,V> stack, spare;
4879 >        int index;
4880 >        int baseIndex;
4881 >        int baseLimit;
4882 >        final int baseSize;
4883 >        int batch;              // split control
4884 >
4885 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4886 >            super(par);
4887 >            this.batch = b;
4888 >            this.index = this.baseIndex = i;
4889 >            if ((this.tab = t) == null)
4890 >                this.baseSize = this.baseLimit = 0;
4891 >            else if (par == null)
4892 >                this.baseSize = this.baseLimit = t.length;
4893 >            else {
4894 >                this.baseLimit = f;
4895 >                this.baseSize = par.baseSize;
4896 >            }
4897          }
4898  
4899          /**
4900 <         * Returns a task that when invoked, returns the result of
5419 <         * accumulating the given transformation of all entries using the
5420 <         * given reducer to combine values, and the given basis as an
5421 <         * identity value.
5422 <         *
5423 <         * @param map the map
5424 <         * @param transformer a function returning the transformation
5425 <         * for an element
5426 <         * @param basis the identity (initial default value) for the reduction
5427 <         * @param reducer a commutative associative combining function
5428 <         * @return the task
4900 >         * Same as Traverser version.
4901           */
4902 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4903 <            (ConcurrentHashMap<K,V> map,
4904 <             LongFunction<Map.Entry<K,V>> transformer,
4905 <             long basis,
4906 <             LongBinaryOperator reducer) {
4907 <            if (transformer == null || reducer == null)
4908 <                throw new NullPointerException();
4909 <            return new MapReduceEntriesToLongTask<K,V>
4910 <                (map, null, -1, null, transformer, basis, reducer);
4902 >        final Node<K,V> advance() {
4903 >            Node<K,V> e;
4904 >            if ((e = next) != null)
4905 >                e = e.next;
4906 >            for (;;) {
4907 >                Node<K,V>[] t; int i, n;
4908 >                if (e != null)
4909 >                    return next = e;
4910 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4911 >                    (n = t.length) <= (i = index) || i < 0)
4912 >                    return next = null;
4913 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
4914 >                    if (e instanceof ForwardingNode) {
4915 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4916 >                        e = null;
4917 >                        pushState(t, i, n);
4918 >                        continue;
4919 >                    }
4920 >                    else if (e instanceof TreeBin)
4921 >                        e = ((TreeBin<K,V>)e).first;
4922 >                    else
4923 >                        e = null;
4924 >                }
4925 >                if (stack != null)
4926 >                    recoverState(n);
4927 >                else if ((index = i + baseSize) >= n)
4928 >                    index = ++baseIndex;
4929 >            }
4930          }
4931  
4932 <        /**
4933 <         * Returns a task that when invoked, returns the result of
4934 <         * accumulating the given transformation of all entries using the
4935 <         * given reducer to combine values, and the given basis as an
4936 <         * identity value.
4937 <         *
4938 <         * @param map the map
4939 <         * @param transformer a function returning the transformation
4940 <         * for an element
4941 <         * @param basis the identity (initial default value) for the reduction
4942 <         * @param reducer a commutative associative combining function
4943 <         * @return the task
4944 <         */
4945 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4946 <            (ConcurrentHashMap<K,V> map,
4947 <             IntFunction<Map.Entry<K,V>> transformer,
4948 <             int basis,
4949 <             IntBinaryOperator reducer) {
4950 <            if (transformer == null || reducer == null)
4951 <                throw new NullPointerException();
4952 <            return new MapReduceEntriesToIntTask<K,V>
4953 <                (map, null, -1, null, transformer, basis, reducer);
4932 >        private void pushState(Node<K,V>[] t, int i, int n) {
4933 >            TableStack<K,V> s = spare;
4934 >            if (s != null)
4935 >                spare = s.next;
4936 >            else
4937 >                s = new TableStack<K,V>();
4938 >            s.tab = t;
4939 >            s.length = n;
4940 >            s.index = i;
4941 >            s.next = stack;
4942 >            stack = s;
4943 >        }
4944 >
4945 >        private void recoverState(int n) {
4946 >            TableStack<K,V> s; int len;
4947 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
4948 >                n = len;
4949 >                index = s.index;
4950 >                tab = s.tab;
4951 >                s.tab = null;
4952 >                TableStack<K,V> next = s.next;
4953 >                s.next = spare; // save for reuse
4954 >                stack = next;
4955 >                spare = s;
4956 >            }
4957 >            if (s == null && (index += baseSize) >= n)
4958 >                index = ++baseIndex;
4959          }
4960      }
4961  
5466    // -------------------------------------------------------
5467
4962      /*
4963       * Task classes. Coded in a regular but ugly format/style to
4964       * simplify checks that each variant differs in the right way from
# Line 5472 | Line 4966 | public class ConcurrentHashMap<K, V>
4966       * that we've already null-checked task arguments, so we force
4967       * simplest hoisted bypass to help avoid convoluted traps.
4968       */
4969 <
4970 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4971 <        extends Traverser<K,V,Void> {
4972 <        final Block<? super K> action;
4969 >    @SuppressWarnings("serial")
4970 >    static final class ForEachKeyTask<K,V>
4971 >        extends BulkTask<K,V,Void> {
4972 >        final Consumer<? super K> action;
4973          ForEachKeyTask
4974 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4975 <             Block<? super K> action) {
4976 <            super(m, p, b);
4974 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4975 >             Consumer<? super K> action) {
4976 >            super(p, b, i, f, t);
4977              this.action = action;
4978          }
4979 <        @SuppressWarnings("unchecked") public final void compute() {
4980 <            final Block<? super K> action;
4979 >        public final void compute() {
4980 >            final Consumer<? super K> action;
4981              if ((action = this.action) != null) {
4982 <                for (int b; (b = preSplit()) > 0;)
4983 <                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
4984 <                while (advance() != null)
4985 <                    action.accept((K)nextKey);
4982 >                for (int i = baseIndex, f, h; batch > 0 &&
4983 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4984 >                    addToPendingCount(1);
4985 >                    new ForEachKeyTask<K,V>
4986 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4987 >                         action).fork();
4988 >                }
4989 >                for (Node<K,V> p; (p = advance()) != null;)
4990 >                    action.accept(p.key);
4991                  propagateCompletion();
4992              }
4993          }
4994      }
4995  
4996 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4997 <        extends Traverser<K,V,Void> {
4998 <        final Block<? super V> action;
4996 >    @SuppressWarnings("serial")
4997 >    static final class ForEachValueTask<K,V>
4998 >        extends BulkTask<K,V,Void> {
4999 >        final Consumer<? super V> action;
5000          ForEachValueTask
5001 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5002 <             Block<? super V> action) {
5003 <            super(m, p, b);
5001 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5002 >             Consumer<? super V> action) {
5003 >            super(p, b, i, f, t);
5004              this.action = action;
5005          }
5006 <        @SuppressWarnings("unchecked") public final void compute() {
5007 <            final Block<? super V> action;
5006 >        public final void compute() {
5007 >            final Consumer<? super V> action;
5008              if ((action = this.action) != null) {
5009 <                for (int b; (b = preSplit()) > 0;)
5010 <                    new ForEachValueTask<K,V>(map, this, b, action).fork();
5011 <                V v;
5012 <                while ((v = advance()) != null)
5013 <                    action.accept(v);
5009 >                for (int i = baseIndex, f, h; batch > 0 &&
5010 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5011 >                    addToPendingCount(1);
5012 >                    new ForEachValueTask<K,V>
5013 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5014 >                         action).fork();
5015 >                }
5016 >                for (Node<K,V> p; (p = advance()) != null;)
5017 >                    action.accept(p.val);
5018                  propagateCompletion();
5019              }
5020          }
5021      }
5022  
5023 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
5024 <        extends Traverser<K,V,Void> {
5025 <        final Block<? super Entry<K,V>> action;
5023 >    @SuppressWarnings("serial")
5024 >    static final class ForEachEntryTask<K,V>
5025 >        extends BulkTask<K,V,Void> {
5026 >        final Consumer<? super Entry<K,V>> action;
5027          ForEachEntryTask
5028 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5029 <             Block<? super Entry<K,V>> action) {
5030 <            super(m, p, b);
5028 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5029 >             Consumer<? super Entry<K,V>> action) {
5030 >            super(p, b, i, f, t);
5031              this.action = action;
5032          }
5033 <        @SuppressWarnings("unchecked") public final void compute() {
5034 <            final Block<? super Entry<K,V>> action;
5033 >        public final void compute() {
5034 >            final Consumer<? super Entry<K,V>> action;
5035              if ((action = this.action) != null) {
5036 <                for (int b; (b = preSplit()) > 0;)
5037 <                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
5038 <                V v;
5039 <                while ((v = advance()) != null)
5040 <                    action.accept(entryFor((K)nextKey, v));
5036 >                for (int i = baseIndex, f, h; batch > 0 &&
5037 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5038 >                    addToPendingCount(1);
5039 >                    new ForEachEntryTask<K,V>
5040 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5041 >                         action).fork();
5042 >                }
5043 >                for (Node<K,V> p; (p = advance()) != null; )
5044 >                    action.accept(p);
5045                  propagateCompletion();
5046              }
5047          }
5048      }
5049  
5050 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5051 <        extends Traverser<K,V,Void> {
5052 <        final BiBlock<? super K, ? super V> action;
5050 >    @SuppressWarnings("serial")
5051 >    static final class ForEachMappingTask<K,V>
5052 >        extends BulkTask<K,V,Void> {
5053 >        final BiConsumer<? super K, ? super V> action;
5054          ForEachMappingTask
5055 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5056 <             BiBlock<? super K,? super V> action) {
5057 <            super(m, p, b);
5055 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5056 >             BiConsumer<? super K,? super V> action) {
5057 >            super(p, b, i, f, t);
5058              this.action = action;
5059          }
5060 <        @SuppressWarnings("unchecked") public final void compute() {
5061 <            final BiBlock<? super K, ? super V> action;
5060 >        public final void compute() {
5061 >            final BiConsumer<? super K, ? super V> action;
5062              if ((action = this.action) != null) {
5063 <                for (int b; (b = preSplit()) > 0;)
5064 <                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
5065 <                V v;
5066 <                while ((v = advance()) != null)
5067 <                    action.accept((K)nextKey, v);
5063 >                for (int i = baseIndex, f, h; batch > 0 &&
5064 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5065 >                    addToPendingCount(1);
5066 >                    new ForEachMappingTask<K,V>
5067 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5068 >                         action).fork();
5069 >                }
5070 >                for (Node<K,V> p; (p = advance()) != null; )
5071 >                    action.accept(p.key, p.val);
5072                  propagateCompletion();
5073              }
5074          }
5075      }
5076  
5077 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5078 <        extends Traverser<K,V,Void> {
5077 >    @SuppressWarnings("serial")
5078 >    static final class ForEachTransformedKeyTask<K,V,U>
5079 >        extends BulkTask<K,V,Void> {
5080          final Function<? super K, ? extends U> transformer;
5081 <        final Block<? super U> action;
5081 >        final Consumer<? super U> action;
5082          ForEachTransformedKeyTask
5083 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5084 <             Function<? super K, ? extends U> transformer, Block<? super U> action) {
5085 <            super(m, p, b);
5083 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5084 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5085 >            super(p, b, i, f, t);
5086              this.transformer = transformer; this.action = action;
5087          }
5088 <        @SuppressWarnings("unchecked") public final void compute() {
5088 >        public final void compute() {
5089              final Function<? super K, ? extends U> transformer;
5090 <            final Block<? super U> action;
5090 >            final Consumer<? super U> action;
5091              if ((transformer = this.transformer) != null &&
5092                  (action = this.action) != null) {
5093 <                for (int b; (b = preSplit()) > 0;)
5093 >                for (int i = baseIndex, f, h; batch > 0 &&
5094 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5095 >                    addToPendingCount(1);
5096                      new ForEachTransformedKeyTask<K,V,U>
5097 <                        (map, this, b, transformer, action).fork();
5098 <                U u;
5099 <                while (advance() != null) {
5100 <                    if ((u = transformer.apply((K)nextKey)) != null)
5097 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5098 >                         transformer, action).fork();
5099 >                }
5100 >                for (Node<K,V> p; (p = advance()) != null; ) {
5101 >                    U u;
5102 >                    if ((u = transformer.apply(p.key)) != null)
5103                          action.accept(u);
5104                  }
5105                  propagateCompletion();
# Line 5588 | Line 5107 | public class ConcurrentHashMap<K, V>
5107          }
5108      }
5109  
5110 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5111 <        extends Traverser<K,V,Void> {
5110 >    @SuppressWarnings("serial")
5111 >    static final class ForEachTransformedValueTask<K,V,U>
5112 >        extends BulkTask<K,V,Void> {
5113          final Function<? super V, ? extends U> transformer;
5114 <        final Block<? super U> action;
5114 >        final Consumer<? super U> action;
5115          ForEachTransformedValueTask
5116 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5117 <             Function<? super V, ? extends U> transformer, Block<? super U> action) {
5118 <            super(m, p, b);
5116 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5117 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5118 >            super(p, b, i, f, t);
5119              this.transformer = transformer; this.action = action;
5120          }
5121 <        @SuppressWarnings("unchecked") public final void compute() {
5121 >        public final void compute() {
5122              final Function<? super V, ? extends U> transformer;
5123 <            final Block<? super U> action;
5123 >            final Consumer<? super U> action;
5124              if ((transformer = this.transformer) != null &&
5125                  (action = this.action) != null) {
5126 <                for (int b; (b = preSplit()) > 0;)
5126 >                for (int i = baseIndex, f, h; batch > 0 &&
5127 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5128 >                    addToPendingCount(1);
5129                      new ForEachTransformedValueTask<K,V,U>
5130 <                        (map, this, b, transformer, action).fork();
5131 <                V v; U u;
5132 <                while ((v = advance()) != null) {
5133 <                    if ((u = transformer.apply(v)) != null)
5130 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5131 >                         transformer, action).fork();
5132 >                }
5133 >                for (Node<K,V> p; (p = advance()) != null; ) {
5134 >                    U u;
5135 >                    if ((u = transformer.apply(p.val)) != null)
5136                          action.accept(u);
5137                  }
5138                  propagateCompletion();
# Line 5616 | Line 5140 | public class ConcurrentHashMap<K, V>
5140          }
5141      }
5142  
5143 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5144 <        extends Traverser<K,V,Void> {
5143 >    @SuppressWarnings("serial")
5144 >    static final class ForEachTransformedEntryTask<K,V,U>
5145 >        extends BulkTask<K,V,Void> {
5146          final Function<Map.Entry<K,V>, ? extends U> transformer;
5147 <        final Block<? super U> action;
5147 >        final Consumer<? super U> action;
5148          ForEachTransformedEntryTask
5149 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5150 <             Function<Map.Entry<K,V>, ? extends U> transformer, Block<? super U> action) {
5151 <            super(m, p, b);
5149 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5150 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5151 >            super(p, b, i, f, t);
5152              this.transformer = transformer; this.action = action;
5153          }
5154 <        @SuppressWarnings("unchecked") public final void compute() {
5154 >        public final void compute() {
5155              final Function<Map.Entry<K,V>, ? extends U> transformer;
5156 <            final Block<? super U> action;
5156 >            final Consumer<? super U> action;
5157              if ((transformer = this.transformer) != null &&
5158                  (action = this.action) != null) {
5159 <                for (int b; (b = preSplit()) > 0;)
5159 >                for (int i = baseIndex, f, h; batch > 0 &&
5160 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5161 >                    addToPendingCount(1);
5162                      new ForEachTransformedEntryTask<K,V,U>
5163 <                        (map, this, b, transformer, action).fork();
5164 <                V v; U u;
5165 <                while ((v = advance()) != null) {
5166 <                    if ((u = transformer.apply(entryFor((K)nextKey,
5167 <                                                        v))) != null)
5163 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5164 >                         transformer, action).fork();
5165 >                }
5166 >                for (Node<K,V> p; (p = advance()) != null; ) {
5167 >                    U u;
5168 >                    if ((u = transformer.apply(p)) != null)
5169                          action.accept(u);
5170                  }
5171                  propagateCompletion();
# Line 5645 | Line 5173 | public class ConcurrentHashMap<K, V>
5173          }
5174      }
5175  
5176 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5177 <        extends Traverser<K,V,Void> {
5176 >    @SuppressWarnings("serial")
5177 >    static final class ForEachTransformedMappingTask<K,V,U>
5178 >        extends BulkTask<K,V,Void> {
5179          final BiFunction<? super K, ? super V, ? extends U> transformer;
5180 <        final Block<? super U> action;
5180 >        final Consumer<? super U> action;
5181          ForEachTransformedMappingTask
5182 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5182 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5183               BiFunction<? super K, ? super V, ? extends U> transformer,
5184 <             Block<? super U> action) {
5185 <            super(m, p, b);
5184 >             Consumer<? super U> action) {
5185 >            super(p, b, i, f, t);
5186              this.transformer = transformer; this.action = action;
5187          }
5188 <        @SuppressWarnings("unchecked") public final void compute() {
5188 >        public final void compute() {
5189              final BiFunction<? super K, ? super V, ? extends U> transformer;
5190 <            final Block<? super U> action;
5190 >            final Consumer<? super U> action;
5191              if ((transformer = this.transformer) != null &&
5192                  (action = this.action) != null) {
5193 <                for (int b; (b = preSplit()) > 0;)
5193 >                for (int i = baseIndex, f, h; batch > 0 &&
5194 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5195 >                    addToPendingCount(1);
5196                      new ForEachTransformedMappingTask<K,V,U>
5197 <                        (map, this, b, transformer, action).fork();
5198 <                V v; U u;
5199 <                while ((v = advance()) != null) {
5200 <                    if ((u = transformer.apply((K)nextKey, v)) != null)
5197 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5198 >                         transformer, action).fork();
5199 >                }
5200 >                for (Node<K,V> p; (p = advance()) != null; ) {
5201 >                    U u;
5202 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5203                          action.accept(u);
5204                  }
5205                  propagateCompletion();
# Line 5674 | Line 5207 | public class ConcurrentHashMap<K, V>
5207          }
5208      }
5209  
5210 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5211 <        extends Traverser<K,V,U> {
5210 >    @SuppressWarnings("serial")
5211 >    static final class SearchKeysTask<K,V,U>
5212 >        extends BulkTask<K,V,U> {
5213          final Function<? super K, ? extends U> searchFunction;
5214          final AtomicReference<U> result;
5215          SearchKeysTask
5216 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5216 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5217               Function<? super K, ? extends U> searchFunction,
5218               AtomicReference<U> result) {
5219 <            super(m, p, b);
5219 >            super(p, b, i, f, t);
5220              this.searchFunction = searchFunction; this.result = result;
5221          }
5222          public final U getRawResult() { return result.get(); }
5223 <        @SuppressWarnings("unchecked") public final void compute() {
5223 >        public final void compute() {
5224              final Function<? super K, ? extends U> searchFunction;
5225              final AtomicReference<U> result;
5226              if ((searchFunction = this.searchFunction) != null &&
5227                  (result = this.result) != null) {
5228 <                for (int b;;) {
5228 >                for (int i = baseIndex, f, h; batch > 0 &&
5229 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5230                      if (result.get() != null)
5231                          return;
5232 <                    if ((b = preSplit()) <= 0)
5698 <                        break;
5232 >                    addToPendingCount(1);
5233                      new SearchKeysTask<K,V,U>
5234 <                        (map, this, b, searchFunction, result).fork();
5234 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5235 >                         searchFunction, result).fork();
5236                  }
5237                  while (result.get() == null) {
5238                      U u;
5239 <                    if (advance() == null) {
5239 >                    Node<K,V> p;
5240 >                    if ((p = advance()) == null) {
5241                          propagateCompletion();
5242                          break;
5243                      }
5244 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
5244 >                    if ((u = searchFunction.apply(p.key)) != null) {
5245                          if (result.compareAndSet(null, u))
5246                              quietlyCompleteRoot();
5247                          break;
# Line 5715 | Line 5251 | public class ConcurrentHashMap<K, V>
5251          }
5252      }
5253  
5254 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5255 <        extends Traverser<K,V,U> {
5254 >    @SuppressWarnings("serial")
5255 >    static final class SearchValuesTask<K,V,U>
5256 >        extends BulkTask<K,V,U> {
5257          final Function<? super V, ? extends U> searchFunction;
5258          final AtomicReference<U> result;
5259          SearchValuesTask
5260 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5260 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5261               Function<? super V, ? extends U> searchFunction,
5262               AtomicReference<U> result) {
5263 <            super(m, p, b);
5263 >            super(p, b, i, f, t);
5264              this.searchFunction = searchFunction; this.result = result;
5265          }
5266          public final U getRawResult() { return result.get(); }
5267 <        @SuppressWarnings("unchecked") public final void compute() {
5267 >        public final void compute() {
5268              final Function<? super V, ? extends U> searchFunction;
5269              final AtomicReference<U> result;
5270              if ((searchFunction = this.searchFunction) != null &&
5271                  (result = this.result) != null) {
5272 <                for (int b;;) {
5272 >                for (int i = baseIndex, f, h; batch > 0 &&
5273 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5274                      if (result.get() != null)
5275                          return;
5276 <                    if ((b = preSplit()) <= 0)
5739 <                        break;
5276 >                    addToPendingCount(1);
5277                      new SearchValuesTask<K,V,U>
5278 <                        (map, this, b, searchFunction, result).fork();
5278 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5279 >                         searchFunction, result).fork();
5280                  }
5281                  while (result.get() == null) {
5282 <                    V v; U u;
5283 <                    if ((v = advance()) == null) {
5282 >                    U u;
5283 >                    Node<K,V> p;
5284 >                    if ((p = advance()) == null) {
5285                          propagateCompletion();
5286                          break;
5287                      }
5288 <                    if ((u = searchFunction.apply(v)) != null) {
5288 >                    if ((u = searchFunction.apply(p.val)) != null) {
5289                          if (result.compareAndSet(null, u))
5290                              quietlyCompleteRoot();
5291                          break;
# Line 5756 | Line 5295 | public class ConcurrentHashMap<K, V>
5295          }
5296      }
5297  
5298 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5299 <        extends Traverser<K,V,U> {
5298 >    @SuppressWarnings("serial")
5299 >    static final class SearchEntriesTask<K,V,U>
5300 >        extends BulkTask<K,V,U> {
5301          final Function<Entry<K,V>, ? extends U> searchFunction;
5302          final AtomicReference<U> result;
5303          SearchEntriesTask
5304 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5304 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5305               Function<Entry<K,V>, ? extends U> searchFunction,
5306               AtomicReference<U> result) {
5307 <            super(m, p, b);
5307 >            super(p, b, i, f, t);
5308              this.searchFunction = searchFunction; this.result = result;
5309          }
5310          public final U getRawResult() { return result.get(); }
5311 <        @SuppressWarnings("unchecked") public final void compute() {
5311 >        public final void compute() {
5312              final Function<Entry<K,V>, ? extends U> searchFunction;
5313              final AtomicReference<U> result;
5314              if ((searchFunction = this.searchFunction) != null &&
5315                  (result = this.result) != null) {
5316 <                for (int b;;) {
5316 >                for (int i = baseIndex, f, h; batch > 0 &&
5317 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5318                      if (result.get() != null)
5319                          return;
5320 <                    if ((b = preSplit()) <= 0)
5780 <                        break;
5320 >                    addToPendingCount(1);
5321                      new SearchEntriesTask<K,V,U>
5322 <                        (map, this, b, searchFunction, result).fork();
5322 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5323 >                         searchFunction, result).fork();
5324                  }
5325                  while (result.get() == null) {
5326 <                    V v; U u;
5327 <                    if ((v = advance()) == null) {
5326 >                    U u;
5327 >                    Node<K,V> p;
5328 >                    if ((p = advance()) == null) {
5329                          propagateCompletion();
5330                          break;
5331                      }
5332 <                    if ((u = searchFunction.apply(entryFor((K)nextKey,
5791 <                                                           v))) != null) {
5332 >                    if ((u = searchFunction.apply(p)) != null) {
5333                          if (result.compareAndSet(null, u))
5334                              quietlyCompleteRoot();
5335                          return;
# Line 5798 | Line 5339 | public class ConcurrentHashMap<K, V>
5339          }
5340      }
5341  
5342 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5343 <        extends Traverser<K,V,U> {
5342 >    @SuppressWarnings("serial")
5343 >    static final class SearchMappingsTask<K,V,U>
5344 >        extends BulkTask<K,V,U> {
5345          final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5346          final AtomicReference<U> result;
5347          SearchMappingsTask
5348 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5348 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5349               BiFunction<? super K, ? super V, ? extends U> searchFunction,
5350               AtomicReference<U> result) {
5351 <            super(m, p, b);
5351 >            super(p, b, i, f, t);
5352              this.searchFunction = searchFunction; this.result = result;
5353          }
5354          public final U getRawResult() { return result.get(); }
5355 <        @SuppressWarnings("unchecked") public final void compute() {
5355 >        public final void compute() {
5356              final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5357              final AtomicReference<U> result;
5358              if ((searchFunction = this.searchFunction) != null &&
5359                  (result = this.result) != null) {
5360 <                for (int b;;) {
5360 >                for (int i = baseIndex, f, h; batch > 0 &&
5361 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5362                      if (result.get() != null)
5363                          return;
5364 <                    if ((b = preSplit()) <= 0)
5822 <                        break;
5364 >                    addToPendingCount(1);
5365                      new SearchMappingsTask<K,V,U>
5366 <                        (map, this, b, searchFunction, result).fork();
5366 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5367 >                         searchFunction, result).fork();
5368                  }
5369                  while (result.get() == null) {
5370 <                    V v; U u;
5371 <                    if ((v = advance()) == null) {
5370 >                    U u;
5371 >                    Node<K,V> p;
5372 >                    if ((p = advance()) == null) {
5373                          propagateCompletion();
5374                          break;
5375                      }
5376 <                    if ((u = searchFunction.apply((K)nextKey, v)) != null) {
5376 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5377                          if (result.compareAndSet(null, u))
5378                              quietlyCompleteRoot();
5379                          break;
# Line 5839 | Line 5383 | public class ConcurrentHashMap<K, V>
5383          }
5384      }
5385  
5386 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5387 <        extends Traverser<K,V,K> {
5386 >    @SuppressWarnings("serial")
5387 >    static final class ReduceKeysTask<K,V>
5388 >        extends BulkTask<K,V,K> {
5389          final BiFunction<? super K, ? super K, ? extends K> reducer;
5390          K result;
5391          ReduceKeysTask<K,V> rights, nextRight;
5392          ReduceKeysTask
5393 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5393 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5394               ReduceKeysTask<K,V> nextRight,
5395               BiFunction<? super K, ? super K, ? extends K> reducer) {
5396 <            super(m, p, b); this.nextRight = nextRight;
5396 >            super(p, b, i, f, t); this.nextRight = nextRight;
5397              this.reducer = reducer;
5398          }
5399          public final K getRawResult() { return result; }
5400 <        @SuppressWarnings("unchecked") public final void compute() {
5400 >        public final void compute() {
5401              final BiFunction<? super K, ? super K, ? extends K> reducer;
5402              if ((reducer = this.reducer) != null) {
5403 <                for (int b; (b = preSplit()) > 0;)
5403 >                for (int i = baseIndex, f, h; batch > 0 &&
5404 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5405 >                    addToPendingCount(1);
5406                      (rights = new ReduceKeysTask<K,V>
5407 <                     (map, this, b, rights, reducer)).fork();
5407 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5408 >                      rights, reducer)).fork();
5409 >                }
5410                  K r = null;
5411 <                while (advance() != null) {
5412 <                    K u = (K)nextKey;
5411 >                for (Node<K,V> p; (p = advance()) != null; ) {
5412 >                    K u = p.key;
5413                      r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5414                  }
5415                  result = r;
5416                  CountedCompleter<?> c;
5417                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5418 +                    @SuppressWarnings("unchecked")
5419                      ReduceKeysTask<K,V>
5420                          t = (ReduceKeysTask<K,V>)c,
5421                          s = t.rights;
# Line 5881 | Line 5431 | public class ConcurrentHashMap<K, V>
5431          }
5432      }
5433  
5434 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5435 <        extends Traverser<K,V,V> {
5434 >    @SuppressWarnings("serial")
5435 >    static final class ReduceValuesTask<K,V>
5436 >        extends BulkTask<K,V,V> {
5437          final BiFunction<? super V, ? super V, ? extends V> reducer;
5438          V result;
5439          ReduceValuesTask<K,V> rights, nextRight;
5440          ReduceValuesTask
5441 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5441 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5442               ReduceValuesTask<K,V> nextRight,
5443               BiFunction<? super V, ? super V, ? extends V> reducer) {
5444 <            super(m, p, b); this.nextRight = nextRight;
5444 >            super(p, b, i, f, t); this.nextRight = nextRight;
5445              this.reducer = reducer;
5446          }
5447          public final V getRawResult() { return result; }
5448 <        @SuppressWarnings("unchecked") public final void compute() {
5448 >        public final void compute() {
5449              final BiFunction<? super V, ? super V, ? extends V> reducer;
5450              if ((reducer = this.reducer) != null) {
5451 <                for (int b; (b = preSplit()) > 0;)
5451 >                for (int i = baseIndex, f, h; batch > 0 &&
5452 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5453 >                    addToPendingCount(1);
5454                      (rights = new ReduceValuesTask<K,V>
5455 <                     (map, this, b, rights, reducer)).fork();
5456 <                V r = null, v;
5457 <                while ((v = advance()) != null)
5455 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5456 >                      rights, reducer)).fork();
5457 >                }
5458 >                V r = null;
5459 >                for (Node<K,V> p; (p = advance()) != null; ) {
5460 >                    V v = p.val;
5461                      r = (r == null) ? v : reducer.apply(r, v);
5462 +                }
5463                  result = r;
5464                  CountedCompleter<?> c;
5465                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5466 +                    @SuppressWarnings("unchecked")
5467                      ReduceValuesTask<K,V>
5468                          t = (ReduceValuesTask<K,V>)c,
5469                          s = t.rights;
# Line 5921 | Line 5479 | public class ConcurrentHashMap<K, V>
5479          }
5480      }
5481  
5482 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5483 <        extends Traverser<K,V,Map.Entry<K,V>> {
5482 >    @SuppressWarnings("serial")
5483 >    static final class ReduceEntriesTask<K,V>
5484 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5485          final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5486          Map.Entry<K,V> result;
5487          ReduceEntriesTask<K,V> rights, nextRight;
5488          ReduceEntriesTask
5489 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5489 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5490               ReduceEntriesTask<K,V> nextRight,
5491               BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5492 <            super(m, p, b); this.nextRight = nextRight;
5492 >            super(p, b, i, f, t); this.nextRight = nextRight;
5493              this.reducer = reducer;
5494          }
5495          public final Map.Entry<K,V> getRawResult() { return result; }
5496 <        @SuppressWarnings("unchecked") public final void compute() {
5496 >        public final void compute() {
5497              final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5498              if ((reducer = this.reducer) != null) {
5499 <                for (int b; (b = preSplit()) > 0;)
5499 >                for (int i = baseIndex, f, h; batch > 0 &&
5500 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5501 >                    addToPendingCount(1);
5502                      (rights = new ReduceEntriesTask<K,V>
5503 <                     (map, this, b, rights, reducer)).fork();
5504 <                Map.Entry<K,V> r = null;
5944 <                V v;
5945 <                while ((v = advance()) != null) {
5946 <                    Map.Entry<K,V> u = entryFor((K)nextKey, v);
5947 <                    r = (r == null) ? u : reducer.apply(r, u);
5503 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5504 >                      rights, reducer)).fork();
5505                  }
5506 +                Map.Entry<K,V> r = null;
5507 +                for (Node<K,V> p; (p = advance()) != null; )
5508 +                    r = (r == null) ? p : reducer.apply(r, p);
5509                  result = r;
5510                  CountedCompleter<?> c;
5511                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5512 +                    @SuppressWarnings("unchecked")
5513                      ReduceEntriesTask<K,V>
5514                          t = (ReduceEntriesTask<K,V>)c,
5515                          s = t.rights;
# Line 5964 | Line 5525 | public class ConcurrentHashMap<K, V>
5525          }
5526      }
5527  
5528 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5529 <        extends Traverser<K,V,U> {
5528 >    @SuppressWarnings("serial")
5529 >    static final class MapReduceKeysTask<K,V,U>
5530 >        extends BulkTask<K,V,U> {
5531          final Function<? super K, ? extends U> transformer;
5532          final BiFunction<? super U, ? super U, ? extends U> reducer;
5533          U result;
5534          MapReduceKeysTask<K,V,U> rights, nextRight;
5535          MapReduceKeysTask
5536 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5536 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5537               MapReduceKeysTask<K,V,U> nextRight,
5538               Function<? super K, ? extends U> transformer,
5539               BiFunction<? super U, ? super U, ? extends U> reducer) {
5540 <            super(m, p, b); this.nextRight = nextRight;
5540 >            super(p, b, i, f, t); this.nextRight = nextRight;
5541              this.transformer = transformer;
5542              this.reducer = reducer;
5543          }
5544          public final U getRawResult() { return result; }
5545 <        @SuppressWarnings("unchecked") public final void compute() {
5545 >        public final void compute() {
5546              final Function<? super K, ? extends U> transformer;
5547              final BiFunction<? super U, ? super U, ? extends U> reducer;
5548              if ((transformer = this.transformer) != null &&
5549                  (reducer = this.reducer) != null) {
5550 <                for (int b; (b = preSplit()) > 0;)
5550 >                for (int i = baseIndex, f, h; batch > 0 &&
5551 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5552 >                    addToPendingCount(1);
5553                      (rights = new MapReduceKeysTask<K,V,U>
5554 <                     (map, this, b, rights, transformer, reducer)).fork();
5555 <                U r = null, u;
5556 <                while (advance() != null) {
5557 <                    if ((u = transformer.apply((K)nextKey)) != null)
5554 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5555 >                      rights, transformer, reducer)).fork();
5556 >                }
5557 >                U r = null;
5558 >                for (Node<K,V> p; (p = advance()) != null; ) {
5559 >                    U u;
5560 >                    if ((u = transformer.apply(p.key)) != null)
5561                          r = (r == null) ? u : reducer.apply(r, u);
5562                  }
5563                  result = r;
5564                  CountedCompleter<?> c;
5565                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5566 +                    @SuppressWarnings("unchecked")
5567                      MapReduceKeysTask<K,V,U>
5568                          t = (MapReduceKeysTask<K,V,U>)c,
5569                          s = t.rights;
# Line 6011 | Line 5579 | public class ConcurrentHashMap<K, V>
5579          }
5580      }
5581  
5582 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5583 <        extends Traverser<K,V,U> {
5582 >    @SuppressWarnings("serial")
5583 >    static final class MapReduceValuesTask<K,V,U>
5584 >        extends BulkTask<K,V,U> {
5585          final Function<? super V, ? extends U> transformer;
5586          final BiFunction<? super U, ? super U, ? extends U> reducer;
5587          U result;
5588          MapReduceValuesTask<K,V,U> rights, nextRight;
5589          MapReduceValuesTask
5590 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5590 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5591               MapReduceValuesTask<K,V,U> nextRight,
5592               Function<? super V, ? extends U> transformer,
5593               BiFunction<? super U, ? super U, ? extends U> reducer) {
5594 <            super(m, p, b); this.nextRight = nextRight;
5594 >            super(p, b, i, f, t); this.nextRight = nextRight;
5595              this.transformer = transformer;
5596              this.reducer = reducer;
5597          }
5598          public final U getRawResult() { return result; }
5599 <        @SuppressWarnings("unchecked") public final void compute() {
5599 >        public final void compute() {
5600              final Function<? super V, ? extends U> transformer;
5601              final BiFunction<? super U, ? super U, ? extends U> reducer;
5602              if ((transformer = this.transformer) != null &&
5603                  (reducer = this.reducer) != null) {
5604 <                for (int b; (b = preSplit()) > 0;)
5604 >                for (int i = baseIndex, f, h; batch > 0 &&
5605 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5606 >                    addToPendingCount(1);
5607                      (rights = new MapReduceValuesTask<K,V,U>
5608 <                     (map, this, b, rights, transformer, reducer)).fork();
5609 <                U r = null, u;
5610 <                V v;
5611 <                while ((v = advance()) != null) {
5612 <                    if ((u = transformer.apply(v)) != null)
5608 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5609 >                      rights, transformer, reducer)).fork();
5610 >                }
5611 >                U r = null;
5612 >                for (Node<K,V> p; (p = advance()) != null; ) {
5613 >                    U u;
5614 >                    if ((u = transformer.apply(p.val)) != null)
5615                          r = (r == null) ? u : reducer.apply(r, u);
5616                  }
5617                  result = r;
5618                  CountedCompleter<?> c;
5619                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5620 +                    @SuppressWarnings("unchecked")
5621                      MapReduceValuesTask<K,V,U>
5622                          t = (MapReduceValuesTask<K,V,U>)c,
5623                          s = t.rights;
# Line 6059 | Line 5633 | public class ConcurrentHashMap<K, V>
5633          }
5634      }
5635  
5636 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5637 <        extends Traverser<K,V,U> {
5636 >    @SuppressWarnings("serial")
5637 >    static final class MapReduceEntriesTask<K,V,U>
5638 >        extends BulkTask<K,V,U> {
5639          final Function<Map.Entry<K,V>, ? extends U> transformer;
5640          final BiFunction<? super U, ? super U, ? extends U> reducer;
5641          U result;
5642          MapReduceEntriesTask<K,V,U> rights, nextRight;
5643          MapReduceEntriesTask
5644 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5644 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5645               MapReduceEntriesTask<K,V,U> nextRight,
5646               Function<Map.Entry<K,V>, ? extends U> transformer,
5647               BiFunction<? super U, ? super U, ? extends U> reducer) {
5648 <            super(m, p, b); this.nextRight = nextRight;
5648 >            super(p, b, i, f, t); this.nextRight = nextRight;
5649              this.transformer = transformer;
5650              this.reducer = reducer;
5651          }
5652          public final U getRawResult() { return result; }
5653 <        @SuppressWarnings("unchecked") public final void compute() {
5653 >        public final void compute() {
5654              final Function<Map.Entry<K,V>, ? extends U> transformer;
5655              final BiFunction<? super U, ? super U, ? extends U> reducer;
5656              if ((transformer = this.transformer) != null &&
5657                  (reducer = this.reducer) != null) {
5658 <                for (int b; (b = preSplit()) > 0;)
5658 >                for (int i = baseIndex, f, h; batch > 0 &&
5659 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5660 >                    addToPendingCount(1);
5661                      (rights = new MapReduceEntriesTask<K,V,U>
5662 <                     (map, this, b, rights, transformer, reducer)).fork();
5663 <                U r = null, u;
5664 <                V v;
5665 <                while ((v = advance()) != null) {
5666 <                    if ((u = transformer.apply(entryFor((K)nextKey,
5667 <                                                        v))) != null)
5662 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5663 >                      rights, transformer, reducer)).fork();
5664 >                }
5665 >                U r = null;
5666 >                for (Node<K,V> p; (p = advance()) != null; ) {
5667 >                    U u;
5668 >                    if ((u = transformer.apply(p)) != null)
5669                          r = (r == null) ? u : reducer.apply(r, u);
5670                  }
5671                  result = r;
5672                  CountedCompleter<?> c;
5673                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5674 +                    @SuppressWarnings("unchecked")
5675                      MapReduceEntriesTask<K,V,U>
5676                          t = (MapReduceEntriesTask<K,V,U>)c,
5677                          s = t.rights;
# Line 6108 | Line 5687 | public class ConcurrentHashMap<K, V>
5687          }
5688      }
5689  
5690 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5691 <        extends Traverser<K,V,U> {
5690 >    @SuppressWarnings("serial")
5691 >    static final class MapReduceMappingsTask<K,V,U>
5692 >        extends BulkTask<K,V,U> {
5693          final BiFunction<? super K, ? super V, ? extends U> transformer;
5694          final BiFunction<? super U, ? super U, ? extends U> reducer;
5695          U result;
5696          MapReduceMappingsTask<K,V,U> rights, nextRight;
5697          MapReduceMappingsTask
5698 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5698 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5699               MapReduceMappingsTask<K,V,U> nextRight,
5700               BiFunction<? super K, ? super V, ? extends U> transformer,
5701               BiFunction<? super U, ? super U, ? extends U> reducer) {
5702 <            super(m, p, b); this.nextRight = nextRight;
5702 >            super(p, b, i, f, t); this.nextRight = nextRight;
5703              this.transformer = transformer;
5704              this.reducer = reducer;
5705          }
5706          public final U getRawResult() { return result; }
5707 <        @SuppressWarnings("unchecked") public final void compute() {
5707 >        public final void compute() {
5708              final BiFunction<? super K, ? super V, ? extends U> transformer;
5709              final BiFunction<? super U, ? super U, ? extends U> reducer;
5710              if ((transformer = this.transformer) != null &&
5711                  (reducer = this.reducer) != null) {
5712 <                for (int b; (b = preSplit()) > 0;)
5712 >                for (int i = baseIndex, f, h; batch > 0 &&
5713 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5714 >                    addToPendingCount(1);
5715                      (rights = new MapReduceMappingsTask<K,V,U>
5716 <                     (map, this, b, rights, transformer, reducer)).fork();
5717 <                U r = null, u;
5718 <                V v;
5719 <                while ((v = advance()) != null) {
5720 <                    if ((u = transformer.apply((K)nextKey, v)) != null)
5716 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5717 >                      rights, transformer, reducer)).fork();
5718 >                }
5719 >                U r = null;
5720 >                for (Node<K,V> p; (p = advance()) != null; ) {
5721 >                    U u;
5722 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5723                          r = (r == null) ? u : reducer.apply(r, u);
5724                  }
5725                  result = r;
5726                  CountedCompleter<?> c;
5727                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5728 +                    @SuppressWarnings("unchecked")
5729                      MapReduceMappingsTask<K,V,U>
5730                          t = (MapReduceMappingsTask<K,V,U>)c,
5731                          s = t.rights;
# Line 6156 | Line 5741 | public class ConcurrentHashMap<K, V>
5741          }
5742      }
5743  
5744 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5745 <        extends Traverser<K,V,Double> {
5746 <        final DoubleFunction<? super K> transformer;
5744 >    @SuppressWarnings("serial")
5745 >    static final class MapReduceKeysToDoubleTask<K,V>
5746 >        extends BulkTask<K,V,Double> {
5747 >        final ToDoubleFunction<? super K> transformer;
5748          final DoubleBinaryOperator reducer;
5749          final double basis;
5750          double result;
5751          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5752          MapReduceKeysToDoubleTask
5753 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5753 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5754               MapReduceKeysToDoubleTask<K,V> nextRight,
5755 <             DoubleFunction<? super K> transformer,
5755 >             ToDoubleFunction<? super K> transformer,
5756               double basis,
5757               DoubleBinaryOperator reducer) {
5758 <            super(m, p, b); this.nextRight = nextRight;
5758 >            super(p, b, i, f, t); this.nextRight = nextRight;
5759              this.transformer = transformer;
5760              this.basis = basis; this.reducer = reducer;
5761          }
5762          public final Double getRawResult() { return result; }
5763 <        @SuppressWarnings("unchecked") public final void compute() {
5764 <            final DoubleFunction<? super K> transformer;
5763 >        public final void compute() {
5764 >            final ToDoubleFunction<? super K> transformer;
5765              final DoubleBinaryOperator reducer;
5766              if ((transformer = this.transformer) != null &&
5767                  (reducer = this.reducer) != null) {
5768                  double r = this.basis;
5769 <                for (int b; (b = preSplit()) > 0;)
5769 >                for (int i = baseIndex, f, h; batch > 0 &&
5770 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5771 >                    addToPendingCount(1);
5772                      (rights = new MapReduceKeysToDoubleTask<K,V>
5773 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5774 <                while (advance() != null)
5775 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)nextKey));
5773 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5774 >                      rights, transformer, r, reducer)).fork();
5775 >                }
5776 >                for (Node<K,V> p; (p = advance()) != null; )
5777 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5778                  result = r;
5779                  CountedCompleter<?> c;
5780                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5781 +                    @SuppressWarnings("unchecked")
5782                      MapReduceKeysToDoubleTask<K,V>
5783                          t = (MapReduceKeysToDoubleTask<K,V>)c,
5784                          s = t.rights;
# Line 6200 | Line 5791 | public class ConcurrentHashMap<K, V>
5791          }
5792      }
5793  
5794 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5795 <        extends Traverser<K,V,Double> {
5796 <        final DoubleFunction<? super V> transformer;
5794 >    @SuppressWarnings("serial")
5795 >    static final class MapReduceValuesToDoubleTask<K,V>
5796 >        extends BulkTask<K,V,Double> {
5797 >        final ToDoubleFunction<? super V> transformer;
5798          final DoubleBinaryOperator reducer;
5799          final double basis;
5800          double result;
5801          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5802          MapReduceValuesToDoubleTask
5803 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5803 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5804               MapReduceValuesToDoubleTask<K,V> nextRight,
5805 <             DoubleFunction<? super V> transformer,
5805 >             ToDoubleFunction<? super V> transformer,
5806               double basis,
5807               DoubleBinaryOperator reducer) {
5808 <            super(m, p, b); this.nextRight = nextRight;
5808 >            super(p, b, i, f, t); this.nextRight = nextRight;
5809              this.transformer = transformer;
5810              this.basis = basis; this.reducer = reducer;
5811          }
5812          public final Double getRawResult() { return result; }
5813 <        @SuppressWarnings("unchecked") public final void compute() {
5814 <            final DoubleFunction<? super V> transformer;
5813 >        public final void compute() {
5814 >            final ToDoubleFunction<? super V> transformer;
5815              final DoubleBinaryOperator reducer;
5816              if ((transformer = this.transformer) != null &&
5817                  (reducer = this.reducer) != null) {
5818                  double r = this.basis;
5819 <                for (int b; (b = preSplit()) > 0;)
5819 >                for (int i = baseIndex, f, h; batch > 0 &&
5820 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5821 >                    addToPendingCount(1);
5822                      (rights = new MapReduceValuesToDoubleTask<K,V>
5823 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5824 <                V v;
5825 <                while ((v = advance()) != null)
5826 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
5823 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5824 >                      rights, transformer, r, reducer)).fork();
5825 >                }
5826 >                for (Node<K,V> p; (p = advance()) != null; )
5827 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5828                  result = r;
5829                  CountedCompleter<?> c;
5830                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5831 +                    @SuppressWarnings("unchecked")
5832                      MapReduceValuesToDoubleTask<K,V>
5833                          t = (MapReduceValuesToDoubleTask<K,V>)c,
5834                          s = t.rights;
# Line 6245 | Line 5841 | public class ConcurrentHashMap<K, V>
5841          }
5842      }
5843  
5844 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5845 <        extends Traverser<K,V,Double> {
5846 <        final DoubleFunction<Map.Entry<K,V>> transformer;
5844 >    @SuppressWarnings("serial")
5845 >    static final class MapReduceEntriesToDoubleTask<K,V>
5846 >        extends BulkTask<K,V,Double> {
5847 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
5848          final DoubleBinaryOperator reducer;
5849          final double basis;
5850          double result;
5851          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5852          MapReduceEntriesToDoubleTask
5853 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5853 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5854               MapReduceEntriesToDoubleTask<K,V> nextRight,
5855 <             DoubleFunction<Map.Entry<K,V>> transformer,
5855 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5856               double basis,
5857               DoubleBinaryOperator reducer) {
5858 <            super(m, p, b); this.nextRight = nextRight;
5858 >            super(p, b, i, f, t); this.nextRight = nextRight;
5859              this.transformer = transformer;
5860              this.basis = basis; this.reducer = reducer;
5861          }
5862          public final Double getRawResult() { return result; }
5863 <        @SuppressWarnings("unchecked") public final void compute() {
5864 <            final DoubleFunction<Map.Entry<K,V>> transformer;
5863 >        public final void compute() {
5864 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
5865              final DoubleBinaryOperator reducer;
5866              if ((transformer = this.transformer) != null &&
5867                  (reducer = this.reducer) != null) {
5868                  double r = this.basis;
5869 <                for (int b; (b = preSplit()) > 0;)
5869 >                for (int i = baseIndex, f, h; batch > 0 &&
5870 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5871 >                    addToPendingCount(1);
5872                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5873 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5874 <                V v;
5875 <                while ((v = advance()) != null)
5876 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor((K)nextKey,
5877 <                                                                    v)));
5873 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5874 >                      rights, transformer, r, reducer)).fork();
5875 >                }
5876 >                for (Node<K,V> p; (p = advance()) != null; )
5877 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5878                  result = r;
5879                  CountedCompleter<?> c;
5880                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5881 +                    @SuppressWarnings("unchecked")
5882                      MapReduceEntriesToDoubleTask<K,V>
5883                          t = (MapReduceEntriesToDoubleTask<K,V>)c,
5884                          s = t.rights;
# Line 6291 | Line 5891 | public class ConcurrentHashMap<K, V>
5891          }
5892      }
5893  
5894 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5895 <        extends Traverser<K,V,Double> {
5896 <        final DoubleBiFunction<? super K, ? super V> transformer;
5894 >    @SuppressWarnings("serial")
5895 >    static final class MapReduceMappingsToDoubleTask<K,V>
5896 >        extends BulkTask<K,V,Double> {
5897 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
5898          final DoubleBinaryOperator reducer;
5899          final double basis;
5900          double result;
5901          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5902          MapReduceMappingsToDoubleTask
5903 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5903 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5904               MapReduceMappingsToDoubleTask<K,V> nextRight,
5905 <             DoubleBiFunction<? super K, ? super V> transformer,
5905 >             ToDoubleBiFunction<? super K, ? super V> transformer,
5906               double basis,
5907               DoubleBinaryOperator reducer) {
5908 <            super(m, p, b); this.nextRight = nextRight;
5908 >            super(p, b, i, f, t); this.nextRight = nextRight;
5909              this.transformer = transformer;
5910              this.basis = basis; this.reducer = reducer;
5911          }
5912          public final Double getRawResult() { return result; }
5913 <        @SuppressWarnings("unchecked") public final void compute() {
5914 <            final DoubleBiFunction<? super K, ? super V> transformer;
5913 >        public final void compute() {
5914 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
5915              final DoubleBinaryOperator reducer;
5916              if ((transformer = this.transformer) != null &&
5917                  (reducer = this.reducer) != null) {
5918                  double r = this.basis;
5919 <                for (int b; (b = preSplit()) > 0;)
5919 >                for (int i = baseIndex, f, h; batch > 0 &&
5920 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5921 >                    addToPendingCount(1);
5922                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5923 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5924 <                V v;
5925 <                while ((v = advance()) != null)
5926 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)nextKey, v));
5923 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5924 >                      rights, transformer, r, reducer)).fork();
5925 >                }
5926 >                for (Node<K,V> p; (p = advance()) != null; )
5927 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5928                  result = r;
5929                  CountedCompleter<?> c;
5930                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5931 +                    @SuppressWarnings("unchecked")
5932                      MapReduceMappingsToDoubleTask<K,V>
5933                          t = (MapReduceMappingsToDoubleTask<K,V>)c,
5934                          s = t.rights;
# Line 6336 | Line 5941 | public class ConcurrentHashMap<K, V>
5941          }
5942      }
5943  
5944 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5945 <        extends Traverser<K,V,Long> {
5946 <        final LongFunction<? super K> transformer;
5944 >    @SuppressWarnings("serial")
5945 >    static final class MapReduceKeysToLongTask<K,V>
5946 >        extends BulkTask<K,V,Long> {
5947 >        final ToLongFunction<? super K> transformer;
5948          final LongBinaryOperator reducer;
5949          final long basis;
5950          long result;
5951          MapReduceKeysToLongTask<K,V> rights, nextRight;
5952          MapReduceKeysToLongTask
5953 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5953 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5954               MapReduceKeysToLongTask<K,V> nextRight,
5955 <             LongFunction<? super K> transformer,
5955 >             ToLongFunction<? super K> transformer,
5956               long basis,
5957               LongBinaryOperator reducer) {
5958 <            super(m, p, b); this.nextRight = nextRight;
5958 >            super(p, b, i, f, t); this.nextRight = nextRight;
5959              this.transformer = transformer;
5960              this.basis = basis; this.reducer = reducer;
5961          }
5962          public final Long getRawResult() { return result; }
5963 <        @SuppressWarnings("unchecked") public final void compute() {
5964 <            final LongFunction<? super K> transformer;
5963 >        public final void compute() {
5964 >            final ToLongFunction<? super K> transformer;
5965              final LongBinaryOperator reducer;
5966              if ((transformer = this.transformer) != null &&
5967                  (reducer = this.reducer) != null) {
5968                  long r = this.basis;
5969 <                for (int b; (b = preSplit()) > 0;)
5969 >                for (int i = baseIndex, f, h; batch > 0 &&
5970 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5971 >                    addToPendingCount(1);
5972                      (rights = new MapReduceKeysToLongTask<K,V>
5973 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5974 <                while (advance() != null)
5975 <                    r = reducer.applyAsLong(r, transformer.applyAsLong((K)nextKey));
5973 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5974 >                      rights, transformer, r, reducer)).fork();
5975 >                }
5976 >                for (Node<K,V> p; (p = advance()) != null; )
5977 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5978                  result = r;
5979                  CountedCompleter<?> c;
5980                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5981 +                    @SuppressWarnings("unchecked")
5982                      MapReduceKeysToLongTask<K,V>
5983                          t = (MapReduceKeysToLongTask<K,V>)c,
5984                          s = t.rights;
# Line 6380 | Line 5991 | public class ConcurrentHashMap<K, V>
5991          }
5992      }
5993  
5994 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5995 <        extends Traverser<K,V,Long> {
5996 <        final LongFunction<? super V> transformer;
5994 >    @SuppressWarnings("serial")
5995 >    static final class MapReduceValuesToLongTask<K,V>
5996 >        extends BulkTask<K,V,Long> {
5997 >        final ToLongFunction<? super V> transformer;
5998          final LongBinaryOperator reducer;
5999          final long basis;
6000          long result;
6001          MapReduceValuesToLongTask<K,V> rights, nextRight;
6002          MapReduceValuesToLongTask
6003 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6003 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6004               MapReduceValuesToLongTask<K,V> nextRight,
6005 <             LongFunction<? super V> transformer,
6005 >             ToLongFunction<? super V> transformer,
6006               long basis,
6007               LongBinaryOperator reducer) {
6008 <            super(m, p, b); this.nextRight = nextRight;
6008 >            super(p, b, i, f, t); this.nextRight = nextRight;
6009              this.transformer = transformer;
6010              this.basis = basis; this.reducer = reducer;
6011          }
6012          public final Long getRawResult() { return result; }
6013 <        @SuppressWarnings("unchecked") public final void compute() {
6014 <            final LongFunction<? super V> transformer;
6013 >        public final void compute() {
6014 >            final ToLongFunction<? super V> transformer;
6015              final LongBinaryOperator reducer;
6016              if ((transformer = this.transformer) != null &&
6017                  (reducer = this.reducer) != null) {
6018                  long r = this.basis;
6019 <                for (int b; (b = preSplit()) > 0;)
6019 >                for (int i = baseIndex, f, h; batch > 0 &&
6020 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6021 >                    addToPendingCount(1);
6022                      (rights = new MapReduceValuesToLongTask<K,V>
6023 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6024 <                V v;
6025 <                while ((v = advance()) != null)
6026 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(v));
6023 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6024 >                      rights, transformer, r, reducer)).fork();
6025 >                }
6026 >                for (Node<K,V> p; (p = advance()) != null; )
6027 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
6028                  result = r;
6029                  CountedCompleter<?> c;
6030                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6031 +                    @SuppressWarnings("unchecked")
6032                      MapReduceValuesToLongTask<K,V>
6033                          t = (MapReduceValuesToLongTask<K,V>)c,
6034                          s = t.rights;
# Line 6425 | Line 6041 | public class ConcurrentHashMap<K, V>
6041          }
6042      }
6043  
6044 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6045 <        extends Traverser<K,V,Long> {
6046 <        final LongFunction<Map.Entry<K,V>> transformer;
6044 >    @SuppressWarnings("serial")
6045 >    static final class MapReduceEntriesToLongTask<K,V>
6046 >        extends BulkTask<K,V,Long> {
6047 >        final ToLongFunction<Map.Entry<K,V>> transformer;
6048          final LongBinaryOperator reducer;
6049          final long basis;
6050          long result;
6051          MapReduceEntriesToLongTask<K,V> rights, nextRight;
6052          MapReduceEntriesToLongTask
6053 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6053 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6054               MapReduceEntriesToLongTask<K,V> nextRight,
6055 <             LongFunction<Map.Entry<K,V>> transformer,
6055 >             ToLongFunction<Map.Entry<K,V>> transformer,
6056               long basis,
6057               LongBinaryOperator reducer) {
6058 <            super(m, p, b); this.nextRight = nextRight;
6058 >            super(p, b, i, f, t); this.nextRight = nextRight;
6059              this.transformer = transformer;
6060              this.basis = basis; this.reducer = reducer;
6061          }
6062          public final Long getRawResult() { return result; }
6063 <        @SuppressWarnings("unchecked") public final void compute() {
6064 <            final LongFunction<Map.Entry<K,V>> transformer;
6063 >        public final void compute() {
6064 >            final ToLongFunction<Map.Entry<K,V>> transformer;
6065              final LongBinaryOperator reducer;
6066              if ((transformer = this.transformer) != null &&
6067                  (reducer = this.reducer) != null) {
6068                  long r = this.basis;
6069 <                for (int b; (b = preSplit()) > 0;)
6069 >                for (int i = baseIndex, f, h; batch > 0 &&
6070 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6071 >                    addToPendingCount(1);
6072                      (rights = new MapReduceEntriesToLongTask<K,V>
6073 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6074 <                V v;
6075 <                while ((v = advance()) != null)
6076 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor((K)nextKey, v)));
6073 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6074 >                      rights, transformer, r, reducer)).fork();
6075 >                }
6076 >                for (Node<K,V> p; (p = advance()) != null; )
6077 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
6078                  result = r;
6079                  CountedCompleter<?> c;
6080                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6081 +                    @SuppressWarnings("unchecked")
6082                      MapReduceEntriesToLongTask<K,V>
6083                          t = (MapReduceEntriesToLongTask<K,V>)c,
6084                          s = t.rights;
# Line 6470 | Line 6091 | public class ConcurrentHashMap<K, V>
6091          }
6092      }
6093  
6094 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6095 <        extends Traverser<K,V,Long> {
6096 <        final LongBiFunction<? super K, ? super V> transformer;
6094 >    @SuppressWarnings("serial")
6095 >    static final class MapReduceMappingsToLongTask<K,V>
6096 >        extends BulkTask<K,V,Long> {
6097 >        final ToLongBiFunction<? super K, ? super V> transformer;
6098          final LongBinaryOperator reducer;
6099          final long basis;
6100          long result;
6101          MapReduceMappingsToLongTask<K,V> rights, nextRight;
6102          MapReduceMappingsToLongTask
6103 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6103 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6104               MapReduceMappingsToLongTask<K,V> nextRight,
6105 <             LongBiFunction<? super K, ? super V> transformer,
6105 >             ToLongBiFunction<? super K, ? super V> transformer,
6106               long basis,
6107               LongBinaryOperator reducer) {
6108 <            super(m, p, b); this.nextRight = nextRight;
6108 >            super(p, b, i, f, t); this.nextRight = nextRight;
6109              this.transformer = transformer;
6110              this.basis = basis; this.reducer = reducer;
6111          }
6112          public final Long getRawResult() { return result; }
6113 <        @SuppressWarnings("unchecked") public final void compute() {
6114 <            final LongBiFunction<? super K, ? super V> transformer;
6113 >        public final void compute() {
6114 >            final ToLongBiFunction<? super K, ? super V> transformer;
6115              final LongBinaryOperator reducer;
6116              if ((transformer = this.transformer) != null &&
6117                  (reducer = this.reducer) != null) {
6118                  long r = this.basis;
6119 <                for (int b; (b = preSplit()) > 0;)
6119 >                for (int i = baseIndex, f, h; batch > 0 &&
6120 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6121 >                    addToPendingCount(1);
6122                      (rights = new MapReduceMappingsToLongTask<K,V>
6123 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6124 <                V v;
6125 <                while ((v = advance()) != null)
6126 <                    r = reducer.applyAsLong(r, transformer.applyAsLong((K)nextKey, v));
6123 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6124 >                      rights, transformer, r, reducer)).fork();
6125 >                }
6126 >                for (Node<K,V> p; (p = advance()) != null; )
6127 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
6128                  result = r;
6129                  CountedCompleter<?> c;
6130                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6131 +                    @SuppressWarnings("unchecked")
6132                      MapReduceMappingsToLongTask<K,V>
6133                          t = (MapReduceMappingsToLongTask<K,V>)c,
6134                          s = t.rights;
# Line 6515 | Line 6141 | public class ConcurrentHashMap<K, V>
6141          }
6142      }
6143  
6144 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6145 <        extends Traverser<K,V,Integer> {
6146 <        final IntFunction<? super K> transformer;
6144 >    @SuppressWarnings("serial")
6145 >    static final class MapReduceKeysToIntTask<K,V>
6146 >        extends BulkTask<K,V,Integer> {
6147 >        final ToIntFunction<? super K> transformer;
6148          final IntBinaryOperator reducer;
6149          final int basis;
6150          int result;
6151          MapReduceKeysToIntTask<K,V> rights, nextRight;
6152          MapReduceKeysToIntTask
6153 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6153 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6154               MapReduceKeysToIntTask<K,V> nextRight,
6155 <             IntFunction<? super K> transformer,
6155 >             ToIntFunction<? super K> transformer,
6156               int basis,
6157               IntBinaryOperator reducer) {
6158 <            super(m, p, b); this.nextRight = nextRight;
6158 >            super(p, b, i, f, t); this.nextRight = nextRight;
6159              this.transformer = transformer;
6160              this.basis = basis; this.reducer = reducer;
6161          }
6162          public final Integer getRawResult() { return result; }
6163 <        @SuppressWarnings("unchecked") public final void compute() {
6164 <            final IntFunction<? super K> transformer;
6163 >        public final void compute() {
6164 >            final ToIntFunction<? super K> transformer;
6165              final IntBinaryOperator reducer;
6166              if ((transformer = this.transformer) != null &&
6167                  (reducer = this.reducer) != null) {
6168                  int r = this.basis;
6169 <                for (int b; (b = preSplit()) > 0;)
6169 >                for (int i = baseIndex, f, h; batch > 0 &&
6170 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6171 >                    addToPendingCount(1);
6172                      (rights = new MapReduceKeysToIntTask<K,V>
6173 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6174 <                while (advance() != null)
6175 <                    r = reducer.applyAsInt(r, transformer.applyAsInt((K)nextKey));
6173 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6174 >                      rights, transformer, r, reducer)).fork();
6175 >                }
6176 >                for (Node<K,V> p; (p = advance()) != null; )
6177 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
6178                  result = r;
6179                  CountedCompleter<?> c;
6180                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6181 +                    @SuppressWarnings("unchecked")
6182                      MapReduceKeysToIntTask<K,V>
6183                          t = (MapReduceKeysToIntTask<K,V>)c,
6184                          s = t.rights;
# Line 6559 | Line 6191 | public class ConcurrentHashMap<K, V>
6191          }
6192      }
6193  
6194 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6195 <        extends Traverser<K,V,Integer> {
6196 <        final IntFunction<? super V> transformer;
6194 >    @SuppressWarnings("serial")
6195 >    static final class MapReduceValuesToIntTask<K,V>
6196 >        extends BulkTask<K,V,Integer> {
6197 >        final ToIntFunction<? super V> transformer;
6198          final IntBinaryOperator reducer;
6199          final int basis;
6200          int result;
6201          MapReduceValuesToIntTask<K,V> rights, nextRight;
6202          MapReduceValuesToIntTask
6203 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6203 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6204               MapReduceValuesToIntTask<K,V> nextRight,
6205 <             IntFunction<? super V> transformer,
6205 >             ToIntFunction<? super V> transformer,
6206               int basis,
6207               IntBinaryOperator reducer) {
6208 <            super(m, p, b); this.nextRight = nextRight;
6208 >            super(p, b, i, f, t); this.nextRight = nextRight;
6209              this.transformer = transformer;
6210              this.basis = basis; this.reducer = reducer;
6211          }
6212          public final Integer getRawResult() { return result; }
6213 <        @SuppressWarnings("unchecked") public final void compute() {
6214 <            final IntFunction<? super V> transformer;
6213 >        public final void compute() {
6214 >            final ToIntFunction<? super V> transformer;
6215              final IntBinaryOperator reducer;
6216              if ((transformer = this.transformer) != null &&
6217                  (reducer = this.reducer) != null) {
6218                  int r = this.basis;
6219 <                for (int b; (b = preSplit()) > 0;)
6219 >                for (int i = baseIndex, f, h; batch > 0 &&
6220 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6221 >                    addToPendingCount(1);
6222                      (rights = new MapReduceValuesToIntTask<K,V>
6223 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6224 <                V v;
6225 <                while ((v = advance()) != null)
6226 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(v));
6223 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6224 >                      rights, transformer, r, reducer)).fork();
6225 >                }
6226 >                for (Node<K,V> p; (p = advance()) != null; )
6227 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
6228                  result = r;
6229                  CountedCompleter<?> c;
6230                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6231 +                    @SuppressWarnings("unchecked")
6232                      MapReduceValuesToIntTask<K,V>
6233                          t = (MapReduceValuesToIntTask<K,V>)c,
6234                          s = t.rights;
# Line 6604 | Line 6241 | public class ConcurrentHashMap<K, V>
6241          }
6242      }
6243  
6244 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6245 <        extends Traverser<K,V,Integer> {
6246 <        final IntFunction<Map.Entry<K,V>> transformer;
6244 >    @SuppressWarnings("serial")
6245 >    static final class MapReduceEntriesToIntTask<K,V>
6246 >        extends BulkTask<K,V,Integer> {
6247 >        final ToIntFunction<Map.Entry<K,V>> transformer;
6248          final IntBinaryOperator reducer;
6249          final int basis;
6250          int result;
6251          MapReduceEntriesToIntTask<K,V> rights, nextRight;
6252          MapReduceEntriesToIntTask
6253 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6253 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6254               MapReduceEntriesToIntTask<K,V> nextRight,
6255 <             IntFunction<Map.Entry<K,V>> transformer,
6255 >             ToIntFunction<Map.Entry<K,V>> transformer,
6256               int basis,
6257               IntBinaryOperator reducer) {
6258 <            super(m, p, b); this.nextRight = nextRight;
6258 >            super(p, b, i, f, t); this.nextRight = nextRight;
6259              this.transformer = transformer;
6260              this.basis = basis; this.reducer = reducer;
6261          }
6262          public final Integer getRawResult() { return result; }
6263 <        @SuppressWarnings("unchecked") public final void compute() {
6264 <            final IntFunction<Map.Entry<K,V>> transformer;
6263 >        public final void compute() {
6264 >            final ToIntFunction<Map.Entry<K,V>> transformer;
6265              final IntBinaryOperator reducer;
6266              if ((transformer = this.transformer) != null &&
6267                  (reducer = this.reducer) != null) {
6268                  int r = this.basis;
6269 <                for (int b; (b = preSplit()) > 0;)
6269 >                for (int i = baseIndex, f, h; batch > 0 &&
6270 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6271 >                    addToPendingCount(1);
6272                      (rights = new MapReduceEntriesToIntTask<K,V>
6273 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6274 <                V v;
6275 <                while ((v = advance()) != null)
6276 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor((K)nextKey,
6277 <                                                                    v)));
6273 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6274 >                      rights, transformer, r, reducer)).fork();
6275 >                }
6276 >                for (Node<K,V> p; (p = advance()) != null; )
6277 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
6278                  result = r;
6279                  CountedCompleter<?> c;
6280                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6281 +                    @SuppressWarnings("unchecked")
6282                      MapReduceEntriesToIntTask<K,V>
6283                          t = (MapReduceEntriesToIntTask<K,V>)c,
6284                          s = t.rights;
# Line 6650 | Line 6291 | public class ConcurrentHashMap<K, V>
6291          }
6292      }
6293  
6294 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6295 <        extends Traverser<K,V,Integer> {
6296 <        final IntBiFunction<? super K, ? super V> transformer;
6294 >    @SuppressWarnings("serial")
6295 >    static final class MapReduceMappingsToIntTask<K,V>
6296 >        extends BulkTask<K,V,Integer> {
6297 >        final ToIntBiFunction<? super K, ? super V> transformer;
6298          final IntBinaryOperator reducer;
6299          final int basis;
6300          int result;
6301          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6302          MapReduceMappingsToIntTask
6303 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6303 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6304               MapReduceMappingsToIntTask<K,V> nextRight,
6305 <             IntBiFunction<? super K, ? super V> transformer,
6305 >             ToIntBiFunction<? super K, ? super V> transformer,
6306               int basis,
6307               IntBinaryOperator reducer) {
6308 <            super(m, p, b); this.nextRight = nextRight;
6308 >            super(p, b, i, f, t); this.nextRight = nextRight;
6309              this.transformer = transformer;
6310              this.basis = basis; this.reducer = reducer;
6311          }
6312          public final Integer getRawResult() { return result; }
6313 <        @SuppressWarnings("unchecked") public final void compute() {
6314 <            final IntBiFunction<? super K, ? super V> transformer;
6313 >        public final void compute() {
6314 >            final ToIntBiFunction<? super K, ? super V> transformer;
6315              final IntBinaryOperator reducer;
6316              if ((transformer = this.transformer) != null &&
6317                  (reducer = this.reducer) != null) {
6318                  int r = this.basis;
6319 <                for (int b; (b = preSplit()) > 0;)
6319 >                for (int i = baseIndex, f, h; batch > 0 &&
6320 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6321 >                    addToPendingCount(1);
6322                      (rights = new MapReduceMappingsToIntTask<K,V>
6323 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6324 <                V v;
6325 <                while ((v = advance()) != null)
6326 <                    r = reducer.applyAsInt(r, transformer.applyAsInt((K)nextKey, v));
6323 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6324 >                      rights, transformer, r, reducer)).fork();
6325 >                }
6326 >                for (Node<K,V> p; (p = advance()) != null; )
6327 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6328                  result = r;
6329                  CountedCompleter<?> c;
6330                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6331 +                    @SuppressWarnings("unchecked")
6332                      MapReduceMappingsToIntTask<K,V>
6333                          t = (MapReduceMappingsToIntTask<K,V>)c,
6334                          s = t.rights;
# Line 6696 | Line 6342 | public class ConcurrentHashMap<K, V>
6342      }
6343  
6344      // Unsafe mechanics
6345 <    private static final sun.misc.Unsafe U;
6345 >    private static final Unsafe U = Unsafe.getUnsafe();
6346      private static final long SIZECTL;
6347      private static final long TRANSFERINDEX;
6702    private static final long TRANSFERORIGIN;
6348      private static final long BASECOUNT;
6349      private static final long CELLSBUSY;
6350      private static final long CELLVALUE;
6351 <    private static final long ABASE;
6351 >    private static final int ABASE;
6352      private static final int ASHIFT;
6353  
6354      static {
6710        int ss;
6355          try {
6712            U = sun.misc.Unsafe.getUnsafe();
6713            Class<?> k = ConcurrentHashMap.class;
6356              SIZECTL = U.objectFieldOffset
6357 <                (k.getDeclaredField("sizeCtl"));
6357 >                (ConcurrentHashMap.class.getDeclaredField("sizeCtl"));
6358              TRANSFERINDEX = U.objectFieldOffset
6359 <                (k.getDeclaredField("transferIndex"));
6718 <            TRANSFERORIGIN = U.objectFieldOffset
6719 <                (k.getDeclaredField("transferOrigin"));
6359 >                (ConcurrentHashMap.class.getDeclaredField("transferIndex"));
6360              BASECOUNT = U.objectFieldOffset
6361 <                (k.getDeclaredField("baseCount"));
6361 >                (ConcurrentHashMap.class.getDeclaredField("baseCount"));
6362              CELLSBUSY = U.objectFieldOffset
6363 <                (k.getDeclaredField("cellsBusy"));
6364 <            Class<?> ck = Cell.class;
6363 >                (ConcurrentHashMap.class.getDeclaredField("cellsBusy"));
6364 >
6365              CELLVALUE = U.objectFieldOffset
6366 <                (ck.getDeclaredField("value"));
6367 <            Class<?> sc = Node[].class;
6368 <            ABASE = U.arrayBaseOffset(sc);
6369 <            ss = U.arrayIndexScale(sc);
6370 <            ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6371 <        } catch (Exception e) {
6366 >                (CounterCell.class.getDeclaredField("value"));
6367 >
6368 >            ABASE = U.arrayBaseOffset(Node[].class);
6369 >            int scale = U.arrayIndexScale(Node[].class);
6370 >            if ((scale & (scale - 1)) != 0)
6371 >                throw new Error("array index scale not a power of two");
6372 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6373 >        } catch (ReflectiveOperationException e) {
6374              throw new Error(e);
6375          }
6734        if ((ss & (ss-1)) != 0)
6735            throw new Error("data type scale not a power of two");
6736    }
6376  
6377 +        // Reduce the risk of rare disastrous classloading in first call to
6378 +        // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
6379 +        Class<?> ensureLoaded = LockSupport.class;
6380 +    }
6381   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines