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.204 by dl, Thu Apr 11 18:43:33 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.Spliterator;
11 import java.util.stream.Stream;
12 import java.util.stream.Streams;
13 import java.util.function.*;
14 import java.util.function.Consumer;
15 import java.util.function.Function;
16 import java.util.function.BiFunction;
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;
20 import java.util.Map;
21 import java.util.Set;
15   import java.util.Collection;
16 < import java.util.AbstractMap;
24 < import java.util.AbstractSet;
25 < import java.util.AbstractCollection;
26 < 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;
30 < 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;
34 < 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;
26 < import java.lang.reflect.Type;
27 < import java.lang.reflect.ParameterizedType;
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 58 | Line 62 | import java.lang.reflect.ParameterizedTy
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 89 | Line 93 | import java.lang.reflect.ParameterizedTy
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 97 | Line 102 | import java.lang.reflect.ParameterizedTy
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 computeIfAbsent}. For example, to add a count
109   * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
110 < * {@code freqs.computeIfAbsent(k -> new LongAdder()).increment();}
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 111 | Line 116 | import java.lang.reflect.ParameterizedTy
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
130 < * 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   *
161   * </ul>
158 * </li>
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 219 | Line 233 | import java.lang.reflect.ParameterizedTy
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>
236 > public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
237      implements ConcurrentMap<K,V>, Serializable {
238      private static final long serialVersionUID = 7249069246763182397L;
239  
# Line 233 | 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 250 | 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
254 <     * are always accurately traversable under volatile reads, so long
255 <     * as lookups check hash code and non-nullness of value before
256 <     * 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
262 <     * of each normal Node's hash field contain a transformation of
263 <     * 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 277 | 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,
281 <     * operations that only conditionally update may inspect nodes
282 <     * until the point of update. This is a converse of sorts to the
283 <     * 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 313 | 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
322 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
323 <     * (a specialized form of red-black trees), bounding search time
324 <     * 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 334 | 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 362 | 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 387 | 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 448 | 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 <    private static final int TREE_THRESHOLD = 16;
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 >    static final int MIN_TREEIFY_CAPACITY = 64;
533  
534      /**
535       * Minimum number of rebinnings per transfer step. Ranges are
# Line 462 | 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 <    // Adapted from LongAdder and Striped64.
477 <    // See their internal docs for explanation.
587 >    /* ---------------- Nodes -------------- */
588  
589 <    // A padded cell for distributing counts
590 <    static final class Cell {
591 <        volatile long p0, p1, p2, p3, p4, p5, p6;
592 <        volatile long value;
593 <        volatile long q0, q1, q2, q3, q4, q5, q6;
594 <        Cell(long x) { value = x; }
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 >        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 490 | 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 520 | 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.
524 <     */
525 <    private transient volatile int transferOrigin;
526 <
527 <    /**
528 <     * 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  
542    /** For serialization compatibility. Null unless serialized; see below */
543    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
551 <     * on the invariants that tab arrays have non-zero size, and all
552 <     * indices are masked with (tab.length - 1) which is never
553 <     * negative and always less than length. Note that, to be correct
554 <     * wrt arbitrary concurrency errors by users, bounds checks must
555 <     * operate on local variables, which accounts for some odd-looking
556 <     * inline assignments below.
557 <     */
558 <
559 <    @SuppressWarnings("unchecked") static final <V> Node<V> tabAt
560 <        (Node<V>[] tab, int i) { // used by Traverser
561 <        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  
574    /* ---------------- Nodes -------------- */
575
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;
589 <        volatile V val;
590 <        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
610 <        boolean red;
611 <
612 <        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
613 <            super(hash, key, val, next);
614 <            this.parent = parent;
615 <        }
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 +    /**
899 +     * {@inheritDoc}
900 +     */
901 +    public boolean isEmpty() {
902 +        return sumCount() <= 0L; // ignore transient negative values
903 +    }
904  
905      /**
906 <     * Returns a Class for the given object of the form "class C
907 <     * implements Comparable<C>", if one exists, else null.  See below
908 <     * for explanation.
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 >     * <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 >     * @throws NullPointerException if the specified key is null
915       */
916 <    static Class<?> comparableClassFor(Object x) {
917 <        Class<?> c, s, cmpc; Type[] ts, as; Type t; ParameterizedType p;
918 <        if ((c = x.getClass()) == String.class) // bypass checks
919 <            return c;
920 <        if ((cmpc = Comparable.class).isAssignableFrom(c)) {
921 <            while (cmpc.isAssignableFrom(s = c.getSuperclass()))
922 <                c = s; // find topmost comparable class
923 <            if ((ts  = c.getGenericInterfaces()) != null) {
924 <                for (int i = 0; i < ts.length; ++i) {
925 <                    if (((t = ts[i]) instanceof ParameterizedType) &&
926 <                        ((p = (ParameterizedType)t).getRawType() == cmpc) &&
927 <                        (as = p.getActualTypeArguments()) != null &&
928 <                        as.length == 1 && as[0] == c) // type arg is c
929 <                        return c;
930 <                }
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 <     * A specialized form of red-black tree for use in bins
646 <     * whose size exceeds a threshold.
647 <     *
648 <     * TreeBins use a special form of comparison for search and
649 <     * related operations (which is the main reason we cannot use
650 <     * existing collections such as TreeMaps). TreeBins contain
651 <     * Comparable elements, but may contain others, as well as
652 <     * elements that are Comparable but not necessarily Comparable<T>
653 <     * for the same T, so we cannot invoke compareTo among them. To
654 <     * handle this, the tree is ordered primarily by hash value, then
655 <     * by Comparable.compareTo order if applicable, else by class
656 <     * names if both comparable but not to each other.  On lookup at a
657 <     * node, if elements are not comparable or compare as 0 then both
658 <     * left and right children may need to be searched in the case of
659 <     * tied hash values. (This corresponds to the full list search
660 <     * that would be necessary if all elements were non-Comparable and
661 <     * had tied hashes.)  The red-black balancing code is updated from
662 <     * pre-jdk-collections
663 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
664 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
665 <     * Algorithms" (CLR).
937 >     * Tests if the specified object is a key in this table.
938       *
939 <     * TreeBins also maintain a separate locking discipline than
940 <     * regular bins. Because they are forwarded via special MOVED
941 <     * nodes at bin heads (which can never change once established),
942 <     * we cannot use those nodes as locks. Instead, TreeBin
943 <     * extends AbstractQueuedSynchronizer to support a simple form of
672 <     * read-write lock. For update operations and table validation,
673 <     * the exclusive form of lock behaves in the same way as bin-head
674 <     * locks. However, lookups use shared read-lock mechanics to allow
675 <     * multiple readers in the absence of writers.  Additionally,
676 <     * these lookups do not ever block: While the lock is not
677 <     * available, they proceed along the slow traversal path (via
678 <     * next-pointers) until the lock becomes available or the list is
679 <     * exhausted, whichever comes first. (These cases are not fast,
680 <     * but maximize aggregate expected throughput.)  The AQS mechanics
681 <     * for doing this are straightforward.  The lock state is held as
682 <     * AQS getState().  Read counts are negative; the write count (1)
683 <     * is positive.  There are no signalling preferences among readers
684 <     * and writers. Since we don't need to export full Lock API, we
685 <     * just override the minimal AQS methods and use them directly.
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 <    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
946 <        private static final long serialVersionUID = 2249069246763182397L;
947 <        transient TreeNode<V> root;  // root of tree
690 <        transient TreeNode<V> first; // head of next-pointer list
691 <
692 <        /* AQS overrides */
693 <        public final boolean isHeldExclusively() { return getState() > 0; }
694 <        public final boolean tryAcquire(int ignore) {
695 <            if (compareAndSetState(0, 1)) {
696 <                setExclusiveOwnerThread(Thread.currentThread());
697 <                return true;
698 <            }
699 <            return false;
700 <        }
701 <        public final boolean tryRelease(int ignore) {
702 <            setExclusiveOwnerThread(null);
703 <            setState(0);
704 <            return true;
705 <        }
706 <        public final int tryAcquireShared(int ignore) {
707 <            for (int c;;) {
708 <                if ((c = getState()) > 0)
709 <                    return -1;
710 <                if (compareAndSetState(c, c -1))
711 <                    return 1;
712 <            }
713 <        }
714 <        public final boolean tryReleaseShared(int ignore) {
715 <            int c;
716 <            do {} while (!compareAndSetState(c = getState(), c + 1));
717 <            return c == -1;
718 <        }
719 <
720 <        /** From CLR */
721 <        private void rotateLeft(TreeNode<V> p) {
722 <            if (p != null) {
723 <                TreeNode<V> r = p.right, pp, rl;
724 <                if ((rl = p.right = r.left) != null)
725 <                    rl.parent = p;
726 <                if ((pp = r.parent = p.parent) == null)
727 <                    root = r;
728 <                else if (pp.left == p)
729 <                    pp.left = r;
730 <                else
731 <                    pp.right = r;
732 <                r.left = p;
733 <                p.parent = r;
734 <            }
735 <        }
945 >    public boolean containsKey(Object key) {
946 >        return get(key) != null;
947 >    }
948  
949 <        /** From CLR */
950 <        private void rotateRight(TreeNode<V> p) {
951 <            if (p != null) {
952 <                TreeNode<V> l = p.left, pp, lr;
953 <                if ((lr = p.left = l.right) != null)
954 <                    lr.parent = p;
955 <                if ((pp = l.parent = p.parent) == null)
956 <                    root = l;
957 <                else if (pp.right == p)
958 <                    pp.right = l;
959 <                else
960 <                    pp.left = l;
961 <                l.right = p;
962 <                p.parent = l;
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              }
970          }
971 +        return false;
972 +    }
973  
974 <        /**
975 <         * Compares k and x: if k's comparable class (cc) matches x's,
976 <         * uses Comparable.compareTo. Otherwise compares on comparable
977 <         * class name if both exist, else 0.
978 <         */
979 <        @SuppressWarnings("unchecked")
980 <        static int cccompare(Class<?> cc, Object k, Object x) {
981 <            Class<?> cx;
982 <            return ((cc != null && (cx = comparableClassFor(x)) != null) ?
983 <                    ((cx == cc) ? ((Comparable<Object>)k).compareTo(x) :
984 <                     cc.getName().compareTo(cx.getName())) : 0);
985 <        }
986 <
987 <        /**
988 <         * Returns the TreeNode (or null if not found) for the given
989 <         * key.  A front-end for recursive version.
770 <         */
771 <        final TreeNode<V> getTreeNode(int h, Object k) {
772 <            return getTreeNode(h, k, root, comparableClassFor(k));
773 <        }
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 <         * Returns the TreeNode (or null if not found) for the given key
993 <         * starting at given root.
994 <         */
995 <        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
996 <            (int h, Object k, TreeNode<V> p, Class<?> cc) {
997 <            while (p != null) {
998 <                int dir, ph;  Object pk;
999 <                if ((ph = p.hash) != h)
1000 <                    dir = (h < ph) ? -1 : 1;
1001 <                else if ((pk = p.key) == k || k.equals(pk))
1002 <                    return p;
787 <                else if ((dir = cccompare(cc, k, pk)) == 0) {
788 <                    TreeNode<V> r, pl, pr; // check both sides
789 <                    if ((pr = p.right) != null && h >= pr.hash &&
790 <                        (r = getTreeNode(h, k, pr, cc)) != null)
791 <                        return r;
792 <                    else if ((pl = p.left) != null && h <= pl.hash)
793 <                        dir = -1;
794 <                    else // nothing there
795 <                        break;
796 <                }
797 <                p = (dir > 0) ? p.right : p.left;
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 <            return null;
1005 <        }
1006 <
1007 <        /**
1008 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
1009 <         * read-lock to call getTreeNode, but during failure to get
1010 <         * lock, searches along next links.
1011 <         */
1012 <        final V getValue(int h, Object k) {
1013 <            Node<V> r = null;
1014 <            int c = getState(); // Must read lock state first
1015 <            for (Node<V> e = first; e != null; e = e.next) {
1016 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
1017 <                    try {
1018 <                        r = getTreeNode(h, k, root, comparableClassFor(k));
1019 <                    } finally {
1020 <                        releaseShared(0);
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 >                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 >                                Node<K,V> pred = e;
1028 >                                if ((e = e.next) == null) {
1029 >                                    pred.next = new Node<K,V>(hash, key, value);
1030 >                                    break;
1031 >                                }
1032 >                            }
1033 >                        }
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                      }
817                    break;
1047                  }
1048 <                else if (e.hash == h && k.equals(e.key)) {
1049 <                    r = e;
1048 >                if (binCount != 0) {
1049 >                    if (binCount >= TREEIFY_THRESHOLD)
1050 >                        treeifyBin(tab, i);
1051 >                    if (oldVal != null)
1052 >                        return oldVal;
1053                      break;
1054                  }
823                else
824                    c = getState();
1055              }
826            return r == null ? null : r.val;
1056          }
1057 +        addCount(1L, binCount);
1058 +        return null;
1059 +    }
1060  
1061 <        /**
1062 <         * Finds or adds a node.
1063 <         * @return null if added
1064 <         */
1065 <        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
1066 <            (int h, Object k, V v) {
1067 <            Class<?> cc = comparableClassFor(k);
1068 <            TreeNode<V> pp = root, p = null;
1069 <            int dir = 0;
1070 <            while (pp != null) { // find existing node or leaf to insert at
1071 <                int ph;  Object pk;
1072 <                p = pp;
1073 <                if ((ph = p.hash) != h)
1074 <                    dir = (h < ph) ? -1 : 1;
1075 <                else if ((pk = p.key) == k || k.equals(pk))
1076 <                    return p;
1077 <                else if ((dir = cccompare(cc, k, pk)) == 0) {
1078 <                    TreeNode<V> r, pr;
1079 <                    if ((pr = p.right) != null && h >= pr.hash &&
1080 <                        (r = getTreeNode(h, k, pr, cc)) != null)
1081 <                        return r;
1082 <                    else // continue left
1083 <                        dir = -1;
1084 <                }
1085 <                pp = (dir > 0) ? p.right : p.left;
1086 <            }
1087 <
1088 <            TreeNode<V> f = first;
1089 <            TreeNode<V> x = first = new TreeNode<V>(h, k, v, f, p);
1090 <            if (p == null)
1091 <                root = x;
1092 <            else { // attach and rebalance; adapted from CLR
1093 <                TreeNode<V> xp, xpp;
1094 <                if (f != null)
1095 <                    f.prev = x;
1096 <                if (dir <= 0)
1097 <                    p.left = x;
1098 <                else
1099 <                    p.right = x;
1100 <                x.red = true;
1101 <                while (x != null && (xp = x.parent) != null && xp.red &&
1102 <                       (xpp = xp.parent) != null) {
1103 <                    TreeNode<V> xppl = xpp.left;
1104 <                    if (xp == xppl) {
1105 <                        TreeNode<V> y = xpp.right;
1106 <                        if (y != null && y.red) {
1107 <                            y.red = false;
1108 <                            xp.red = false;
1109 <                            xpp.red = true;
1110 <                            x = xpp;
1111 <                        }
1112 <                        else {
1113 <                            if (x == xp.right) {
1114 <                                rotateLeft(x = xp);
1115 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
1116 <                            }
1117 <                            if (xp != null) {
1118 <                                xp.red = false;
1119 <                                if (xpp != null) {
1120 <                                    xpp.red = true;
1121 <                                    rotateRight(xpp);
1061 >    /**
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 >    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 >     * 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 >    public V remove(Object key) {
1084 >        return replaceNode(key, null, null);
1085 >    }
1086 >
1087 >    /**
1088 >     * Implementation for the four public remove/replace methods:
1089 >     * Replaces node value with v, conditional upon match of cv if
1090 >     * non-null.  If resulting value is null, delete.
1091 >     */
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) == 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 >                            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 <                    }
1132 <                    else {
1133 <                        TreeNode<V> y = xppl;
1134 <                        if (y != null && y.red) {
1135 <                            y.red = false;
1136 <                            xp.red = false;
1137 <                            xpp.red = true;
1138 <                            x = xpp;
1139 <                        }
1140 <                        else {
1141 <                            if (x == xp.left) {
1142 <                                rotateRight(x = xp);
1143 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
1144 <                            }
907 <                            if (xp != null) {
908 <                                xp.red = false;
909 <                                if (xpp != null) {
910 <                                    xpp.red = true;
911 <                                    rotateLeft(xpp);
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 ||
1139 >                                    (pv != null && cv.equals(pv))) {
1140 >                                    oldVal = pv;
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 +                        else if (f instanceof ReservationNode)
1149 +                            throw new IllegalStateException("Recursive update");
1150                      }
1151                  }
1152 <                TreeNode<V> r = root;
1153 <                if (r != null && r.red)
1154 <                    r.red = false;
1155 <            }
1156 <            return null;
922 <        }
923 <
924 <        /**
925 <         * Removes the given node, that must be present before this
926 <         * call.  This is messier than typical red-black deletion code
927 <         * because we cannot swap the contents of an interior node
928 <         * with a leaf successor that is pinned by "next" pointers
929 <         * that are accessible independently of lock. So instead we
930 <         * swap the tree linkages.
931 <         */
932 <        final void deleteTreeNode(TreeNode<V> p) {
933 <            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
934 <            TreeNode<V> pred = p.prev;
935 <            if (pred == null)
936 <                first = next;
937 <            else
938 <                pred.next = next;
939 <            if (next != null)
940 <                next.prev = pred;
941 <            TreeNode<V> replacement;
942 <            TreeNode<V> pl = p.left;
943 <            TreeNode<V> pr = p.right;
944 <            if (pl != null && pr != null) {
945 <                TreeNode<V> s = pr, sl;
946 <                while ((sl = s.left) != null) // find successor
947 <                    s = sl;
948 <                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
949 <                TreeNode<V> sr = s.right;
950 <                TreeNode<V> pp = p.parent;
951 <                if (s == pr) { // p was s's direct parent
952 <                    p.parent = s;
953 <                    s.right = p;
954 <                }
955 <                else {
956 <                    TreeNode<V> sp = s.parent;
957 <                    if ((p.parent = sp) != null) {
958 <                        if (s == sp.left)
959 <                            sp.left = p;
960 <                        else
961 <                            sp.right = p;
1152 >                if (validated) {
1153 >                    if (oldVal != null) {
1154 >                        if (value == null)
1155 >                            addCount(-1L, -1);
1156 >                        return oldVal;
1157                      }
1158 <                    if ((s.right = pr) != null)
964 <                        pr.parent = s;
1158 >                    break;
1159                  }
966                p.left = null;
967                if ((p.right = sr) != null)
968                    sr.parent = p;
969                if ((s.left = pl) != null)
970                    pl.parent = s;
971                if ((s.parent = pp) == null)
972                    root = s;
973                else if (p == pp.left)
974                    pp.left = s;
975                else
976                    pp.right = s;
977                replacement = sr;
1160              }
1161 <            else
1162 <                replacement = (pl != null) ? pl : pr;
1163 <            TreeNode<V> pp = p.parent;
1164 <            if (replacement == null) {
1165 <                if (pp == null) {
1166 <                    root = null;
1167 <                    return;
1168 <                }
1169 <                replacement = p;
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 {
1182 <                replacement.parent = pp;
1183 <                if (pp == null)
1184 <                    root = replacement;
1185 <                else if (p == pp.left)
1186 <                    pp.left = replacement;
1187 <                else
1188 <                    pp.right = replacement;
1189 <                p.left = p.right = p.parent = null;
998 <            }
999 <            if (!p.red) { // rebalance, from CLR
1000 <                TreeNode<V> x = replacement;
1001 <                while (x != null) {
1002 <                    TreeNode<V> xp, xpl;
1003 <                    if (x.red || (xp = x.parent) == null) {
1004 <                        x.red = false;
1005 <                        break;
1006 <                    }
1007 <                    if (x == (xpl = xp.left)) {
1008 <                        TreeNode<V> sib = xp.right;
1009 <                        if (sib != null && sib.red) {
1010 <                            sib.red = false;
1011 <                            xp.red = true;
1012 <                            rotateLeft(xp);
1013 <                            sib = (xp = x.parent) == null ? null : xp.right;
1014 <                        }
1015 <                        if (sib == null)
1016 <                            x = xp;
1017 <                        else {
1018 <                            TreeNode<V> sl = sib.left, sr = sib.right;
1019 <                            if ((sr == null || !sr.red) &&
1020 <                                (sl == null || !sl.red)) {
1021 <                                sib.red = true;
1022 <                                x = xp;
1023 <                            }
1024 <                            else {
1025 <                                if (sr == null || !sr.red) {
1026 <                                    if (sl != null)
1027 <                                        sl.red = false;
1028 <                                    sib.red = true;
1029 <                                    rotateRight(sib);
1030 <                                    sib = (xp = x.parent) == null ?
1031 <                                        null : xp.right;
1032 <                                }
1033 <                                if (sib != null) {
1034 <                                    sib.red = (xp == null) ? false : xp.red;
1035 <                                    if ((sr = sib.right) != null)
1036 <                                        sr.red = false;
1037 <                                }
1038 <                                if (xp != null) {
1039 <                                    xp.red = false;
1040 <                                    rotateLeft(xp);
1041 <                                }
1042 <                                x = root;
1043 <                            }
1044 <                        }
1045 <                    }
1046 <                    else { // symmetric
1047 <                        TreeNode<V> sib = xpl;
1048 <                        if (sib != null && sib.red) {
1049 <                            sib.red = false;
1050 <                            xp.red = true;
1051 <                            rotateRight(xp);
1052 <                            sib = (xp = x.parent) == null ? null : xp.left;
1053 <                        }
1054 <                        if (sib == null)
1055 <                            x = xp;
1056 <                        else {
1057 <                            TreeNode<V> sl = sib.left, sr = sib.right;
1058 <                            if ((sl == null || !sl.red) &&
1059 <                                (sr == null || !sr.red)) {
1060 <                                sib.red = true;
1061 <                                x = xp;
1062 <                            }
1063 <                            else {
1064 <                                if (sl == null || !sl.red) {
1065 <                                    if (sr != null)
1066 <                                        sr.red = false;
1067 <                                    sib.red = true;
1068 <                                    rotateLeft(sib);
1069 <                                    sib = (xp = x.parent) == null ?
1070 <                                        null : xp.left;
1071 <                                }
1072 <                                if (sib != null) {
1073 <                                    sib.red = (xp == null) ? false : xp.red;
1074 <                                    if ((sl = sib.left) != null)
1075 <                                        sl.red = false;
1076 <                                }
1077 <                                if (xp != null) {
1078 <                                    xp.red = false;
1079 <                                    rotateRight(xp);
1080 <                                }
1081 <                                x = root;
1082 <                            }
1182 >                synchronized (f) {
1183 >                    if (tabAt(tab, i) == f) {
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              }
1087            if (p == replacement && (pp = p.parent) != null) {
1088                if (p == pp.left) // detach pointers
1089                    pp.left = null;
1090                else if (p == pp.right)
1091                    pp.right = null;
1092                p.parent = null;
1093            }
1195          }
1196 +        if (delta != 0L)
1197 +            addCount(delta, -1);
1198      }
1199  
1200 <    /* ---------------- Collision reduction methods -------------- */
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 <     * Spreads higher bits to lower, and also forces top bit to 0.
1226 <     * Because the table uses power-of-two masking, sets of hashes
1227 <     * that vary only in bits above the current mask will always
1228 <     * collide. (Among known examples are sets of Float keys holding
1229 <     * consecutive whole numbers in small tables.)  To counter this,
1230 <     * we apply a transform that spreads the impact of higher bits
1231 <     * downward. There is a tradeoff between speed, utility, and
1232 <     * quality of bit-spreading. Because many common sets of hashes
1233 <     * are already reasonably distributed across bits (so don't benefit
1234 <     * from spreading), and because we use trees to handle large sets
1235 <     * of collisions in bins, we don't need excessively high quality.
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 <    private static final int spread(int h) {
1243 <        h ^= (h >>> 18) ^ (h >>> 12);
1244 <        return (h ^ (h >>> 10)) & HASH_BITS;
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 <     * Replaces a list bin with a tree bin if key is comparable.  Call
1250 <     * only when locked.
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 <    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1266 <        if (comparableClassFor(key) != null) {
1267 <            TreeBin<V> t = new TreeBin<V>();
1268 <            for (Node<V> e = tabAt(tab, index); e != null; e = e.next)
1269 <                t.putTreeNode(e.hash, e.key, e.val);
1270 <            setTabAt(tab, index, new Node<V>(MOVED, t, null, null));
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 <    /* ---------------- Internal access and update methods -------------- */
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 >                sb.append(',').append(' ');
1317 >            }
1318 >        }
1319 >        return sb.append('}').toString();
1320 >    }
1321  
1322 <    /** Implementation for get and containsKey */
1323 <    @SuppressWarnings("unchecked") private final V internalGet(Object k) {
1324 <        int h = spread(k.hashCode());
1325 <        retry: for (Node<V>[] tab = table; tab != null;) {
1326 <            Node<V> e; Object ek; V ev; int eh; // locals to read fields once
1327 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1328 <                if ((eh = e.hash) < 0) {
1329 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1330 <                        return ((TreeBin<V>)ek).getValue(h, k);
1331 <                    else {                      // restart with new table
1332 <                        tab = (Node<V>[])ek;
1333 <                        continue retry;
1334 <                    }
1335 <                }
1336 <                else if (eh == h && (ev = e.val) != null &&
1337 <                         ((ek = e.key) == k || k.equals(ek)))
1338 <                    return ev;
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              }
1150            break;
1354          }
1355 <        return null;
1355 >        return true;
1356      }
1357  
1358      /**
1359 <     * Implementation for the four public remove/replace methods:
1360 <     * Replaces node value with v, conditional upon match of cv if
1158 <     * non-null.  If resulting value is null, delete.
1359 >     * Stripped-down version of helper class used in previous version,
1360 >     * declared for the sake of serialization compatibility.
1361       */
1362 <    @SuppressWarnings("unchecked") private final V internalReplace
1363 <        (Object k, V v, Object cv) {
1364 <        int h = spread(k.hashCode());
1365 <        V oldVal = null;
1366 <        for (Node<V>[] tab = table;;) {
1367 <            Node<V> f; int i, fh; Object fk;
1368 <            if (tab == null ||
1369 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1370 <                break;
1371 <            else if ((fh = f.hash) < 0) {
1372 <                if ((fk = f.key) instanceof TreeBin) {
1373 <                    TreeBin<V> t = (TreeBin<V>)fk;
1374 <                    boolean validated = false;
1375 <                    boolean deleted = false;
1376 <                    t.acquire(0);
1377 <                    try {
1378 <                        if (tabAt(tab, i) == f) {
1379 <                            validated = true;
1380 <                            TreeNode<V> p = t.getTreeNode(h, k);
1381 <                            if (p != null) {
1382 <                                V pv = p.val;
1383 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1384 <                                    oldVal = pv;
1385 <                                    if ((p.val = v) == null) {
1386 <                                        deleted = true;
1387 <                                        t.deleteTreeNode(p);
1388 <                                    }
1389 <                                }
1390 <                            }
1391 <                        }
1392 <                    } finally {
1393 <                        t.release(0);
1394 <                    }
1395 <                    if (validated) {
1396 <                        if (deleted)
1397 <                            addCount(-1L, -1);
1398 <                        break;
1399 <                    }
1400 <                }
1401 <                else
1402 <                    tab = (Node<V>[])fk;
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 >        }
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 (fh != h && f.next == null) // precheck
1443 <                break;                          // rules out possible existence
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 <                boolean validated = false;
1453 <                boolean deleted = false;
1454 <                synchronized (f) {
1455 <                    if (tabAt(tab, i) == f) {
1456 <                        validated = true;
1457 <                        for (Node<V> e = f, pred = null;;) {
1458 <                            Object ek; V ev;
1459 <                            if (e.hash == h &&
1460 <                                ((ev = e.val) != null) &&
1461 <                                ((ek = e.key) == k || k.equals(ek))) {
1462 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1463 <                                    oldVal = ev;
1464 <                                    if ((e.val = v) == null) {
1465 <                                        deleted = true;
1466 <                                        Node<V> en = e.next;
1467 <                                        if (pred != null)
1468 <                                            pred.next = en;
1469 <                                        else
1470 <                                            setTabAt(tab, i, en);
1471 <                                    }
1472 <                                }
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 <                            pred = e;
1485 <                            if ((e = e.next) == null)
1486 <                                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 (validated) {
1505 <                    if (deleted)
1506 <                        addCount(-1L, -1);
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          }
1241        return oldVal;
1515      }
1516  
1517 <    /*
1518 <     * Internal versions of insertion methods
1519 <     * All have the same basic structure as the first (internalPut):
1520 <     *  1. If table uninitialized, create
1521 <     *  2. If bin empty, try to CAS new node
1522 <     *  3. If bin stale, use new table
1523 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1524 <     *  5. Lock and validate; if valid, scan and add or update
1252 <     *
1253 <     * The putAll method differs mainly in attempting to pre-allocate
1254 <     * enough table space, and also more lazily performs count updates
1255 <     * and checks.
1256 <     *
1257 <     * Most of the function-accepting methods can't be factored nicely
1258 <     * because they require different functional forms, so instead
1259 <     * sprawl out similar mechanics.
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 <    /** Implementation for put and putIfAbsent */
1531 <    @SuppressWarnings("unchecked") private final V internalPut
1532 <        (K k, V v, boolean onlyIfAbsent) {
1533 <        if (k == null || v == null) throw new NullPointerException();
1534 <        int h = spread(k.hashCode());
1535 <        int len = 0;
1536 <        for (Node<V>[] tab = table;;) {
1537 <            int i, fh; Node<V> f; Object fk; V fv;
1538 <            if (tab == null)
1539 <                tab = initTable();
1540 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1541 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1542 <                    break;                   // no lock when adding to empty bin
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 <            else if ((fh = f.hash) < 0) {
1592 <                if ((fk = f.key) instanceof TreeBin) {
1593 <                    TreeBin<V> t = (TreeBin<V>)fk;
1594 <                    V oldVal = null;
1595 <                    t.acquire(0);
1596 <                    try {
1597 <                        if (tabAt(tab, i) == f) {
1598 <                            len = 2;
1599 <                            TreeNode<V> p = t.putTreeNode(h, k, v);
1600 <                            if (p != null) {
1601 <                                oldVal = p.val;
1602 <                                if (!onlyIfAbsent)
1603 <                                    p.val = v;
1604 <                            }
1605 <                        }
1606 <                    } finally {
1292 <                        t.release(0);
1293 <                    }
1294 <                    if (len != 0) {
1295 <                        if (oldVal != null)
1296 <                            return oldVal;
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;
1298                    }
1608                  }
1300                else
1301                    tab = (Node<V>[])fk;
1609              }
1610 <            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1611 <                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1612 <                return fv;
1613 <            else {
1614 <                V oldVal = null;
1615 <                synchronized (f) {
1616 <                    if (tabAt(tab, i) == f) {
1617 <                        len = 1;
1618 <                        for (Node<V> e = f;; ++len) {
1619 <                            Object ek; V ev;
1620 <                            if (e.hash == h &&
1621 <                                (ev = e.val) != null &&
1622 <                                ((ek = e.key) == k || k.equals(ek))) {
1623 <                                oldVal = ev;
1624 <                                if (!onlyIfAbsent)
1625 <                                    e.val = v;
1626 <                                break;
1627 <                            }
1321 <                            Node<V> last = e;
1322 <                            if ((e = e.next) == null) {
1323 <                                last.next = new Node<V>(h, k, v, null);
1324 <                                if (len >= TREE_THRESHOLD)
1325 <                                    replaceWithTreeBin(tab, i, k);
1326 <                                break;
1327 <                            }
1328 <                        }
1329 <                    }
1330 <                }
1331 <                if (len != 0) {
1332 <                    if (oldVal != null)
1333 <                        return oldVal;
1334 <                    break;
1335 <                }
1610 >        }
1611 >    }
1612 >
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 <        addCount(1L, len);
1631 <        return null;
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 <    /** Implementation for computeIfAbsent */
1653 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1654 <        (K k, Function<? super K, ? extends V> mf) {
1655 <        if (k == null || mf == null)
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)
1364 <                                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);
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;
1385 <                                t.putTreeNode(h, k, val);
1742 >                                t.putTreeVal(h, key, val);
1743                              }
1744                          }
1745 <                    } finally {
1746 <                        t.release(0);
1390 <                    }
1391 <                    if (len != 0) {
1392 <                        if (!added)
1393 <                            return val;
1394 <                        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 {
1401                for (Node<V> e = f; e != null; e = e.next) { // prescan
1402                    Object ek; V ev;
1403                    if (e.hash == h && (ev = e.val) != null &&
1404                        ((ek = e.key) == k || k.equals(ek)))
1405                        return ev;
1406                }
1407                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                                  }
1427                                break;
1840                              }
1841                          }
1842 +                        else if (f instanceof ReservationNode)
1843 +                            throw new IllegalStateException("Recursive update");
1844                      }
1845                  }
1846 <                if (len != 0) {
1433 <                    if (!added)
1434 <                        return val;
1846 >                if (binCount != 0)
1847                      break;
1436                }
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;
1466 <                            if ((val = mf.apply(k, null)) != null) {
1467 <                                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)
1472 <                                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);
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 {
1494                                    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);
1964 >                                if (t.removeTreeNode(p))
1965 >                                    setTabAt(tab, i, untreeify(t.first));
1966                              }
1967                          }
1968 <                    } finally {
1969 <                        t.release(0);
1968 >                        else if (f instanceof ReservationNode)
1969 >                            throw new IllegalStateException("Recursive update");
1970                      }
1507                    if (len != 0)
1508                        break;
1971                  }
1972 <                else
1973 <                    tab = (Node<V>[])fk;
1974 <            }
1513 <            else {
1514 <                synchronized (f) {
1515 <                    if (tabAt(tab, i) == f) {
1516 <                        len = 1;
1517 <                        for (Node<V> e = f, pred = null;; ++len) {
1518 <                            Object ek; V ev;
1519 <                            if (e.hash == h &&
1520 <                                (ev = e.val) != null &&
1521 <                                ((ek = e.key) == k || k.equals(ek))) {
1522 <                                val = mf.apply(k, ev);
1523 <                                if (val != null)
1524 <                                    e.val = val;
1525 <                                else {
1526 <                                    delta = -1;
1527 <                                    Node<V> en = e.next;
1528 <                                    if (pred != null)
1529 <                                        pred.next = en;
1530 <                                    else
1531 <                                        setTabAt(tab, i, en);
1532 <                                }
1533 <                                break;
1534 <                            }
1535 <                            pred = e;
1536 <                            if ((e = e.next) == null) {
1537 <                                if (!onlyIfPresent &&
1538 <                                    (val = mf.apply(k, null)) != null) {
1539 <                                    pred.next = new Node<V>(h, k, val, null);
1540 <                                    delta = 1;
1541 <                                    if (len >= TREE_THRESHOLD)
1542 <                                        replaceWithTreeBin(tab, i, k);
1543 <                                }
1544 <                                break;
1545 <                            }
1546 <                        }
1547 <                    }
1548 <                }
1549 <                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);
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 {
1591                                    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                      }
1604                    if (len != 0)
1605                        break;
2081                  }
2082 <                else
2083 <                    tab = (Node<V>[])fk;
2084 <            }
1610 <            else {
1611 <                synchronized (f) {
1612 <                    if (tabAt(tab, i) == f) {
1613 <                        len = 1;
1614 <                        for (Node<V> e = f, pred = null;; ++len) {
1615 <                            Object ek; V ev;
1616 <                            if (e.hash == h &&
1617 <                                (ev = e.val) != null &&
1618 <                                ((ek = e.key) == k || k.equals(ek))) {
1619 <                                val = mf.apply(ev, v);
1620 <                                if (val != null)
1621 <                                    e.val = val;
1622 <                                else {
1623 <                                    delta = -1;
1624 <                                    Node<V> en = e.next;
1625 <                                    if (pred != null)
1626 <                                        pred.next = en;
1627 <                                    else
1628 <                                        setTabAt(tab, i, en);
1629 <                                }
1630 <                                break;
1631 <                            }
1632 <                            pred = e;
1633 <                            if ((e = e.next) == null) {
1634 <                                val = v;
1635 <                                pred.next = new Node<V>(h, k, val, null);
1636 <                                delta = 1;
1637 <                                if (len >= TREE_THRESHOLD)
1638 <                                    replaceWithTreeBin(tab, i, k);
1639 <                                break;
1640 <                            }
1641 <                        }
1642 <                    }
1643 <                }
1644 <                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);
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;
1702 <                    }
1703 <                    else {
1704 <                        int len = 0;
1705 <                        synchronized (f) {
1706 <                            if (tabAt(tab, i) == f) {
1707 <                                len = 1;
1708 <                                for (Node<V> e = f;; ++len) {
1709 <                                    Object ek; V ev;
1710 <                                    if (e.hash == h &&
1711 <                                        (ev = e.val) != null &&
1712 <                                        ((ek = e.key) == k || k.equals(ek))) {
1713 <                                        e.val = v;
1714 <                                        break;
1715 <                                    }
1716 <                                    Node<V> last = e;
1717 <                                    if ((e = e.next) == null) {
1718 <                                        ++delta;
1719 <                                        last.next = new Node<V>(h, k, v, null);
1720 <                                        if (len >= TREE_THRESHOLD)
1721 <                                            replaceWithTreeBin(tab, i, k);
1722 <                                        break;
1723 <                                    }
1724 <                                }
1725 <                            }
1726 <                        }
1727 <                        if (len != 0) {
1728 <                            if (len > 1) {
1729 <                                addCount(delta, len);
1730 <                                delta = 0L;
1731 <                            }
1732 <                            break;
1733 <                        }
2234 >                            return e.find(h, k);
2235                      }
2236 +                    if ((e = e.next) == null)
2237 +                        return null;
2238                  }
2239              }
1737        } finally {
1738            if (delta != 0L)
1739                addCount(delta, 2);
2240          }
1741        if (npe)
1742            throw new NullPointerException();
2241      }
2242  
2243      /**
2244 <     * Implementation for clear. Steps through each bin, removing all
1747 <     * 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)
1756 <                ++i;
1757 <            else if (f.hash < 0) {
1758 <                Object fk;
1759 <                if ((fk = f.key) instanceof TreeBin) {
1760 <                    TreeBin<V> t = (TreeBin<V>)fk;
1761 <                    t.acquire(0);
1762 <                    try {
1763 <                        if (tabAt(tab, i) == f) {
1764 <                            for (Node<V> p = t.first; p != null; p = p.next) {
1765 <                                if (p.val != null) { // (currently always true)
1766 <                                    p.val = null;
1767 <                                    --delta;
1768 <                                }
1769 <                            }
1770 <                            t.first = null;
1771 <                            t.root = null;
1772 <                            ++i;
1773 <                        }
1774 <                    } finally {
1775 <                        t.release(0);
1776 <                    }
1777 <                }
1778 <                else
1779 <                    tab = (Node<V>[])fk;
1780 <            }
1781 <            else {
1782 <                synchronized (f) {
1783 <                    if (tabAt(tab, i) == f) {
1784 <                        for (Node<V> e = f; e != null; e = e.next) {
1785 <                            if (e.val != null) {  // (currently always true)
1786 <                                e.val = null;
1787 <                                --delta;
1788 <                            }
1789 <                        }
1790 <                        setTabAt(tab, i, null);
1791 <                        ++i;
1792 <                    }
1793 <                }
1794 <            }
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          }
1796        if (delta != 0L)
1797            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;
1808 <        n |= n >>> 1;
1809 <        n |= n >>> 2;
1810 <        n |= n >>> 4;
1811 <        n |= n >>> 8;
1812 <        n |= n >>> 16;
1813 <        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 1849 | 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 1866 | 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 1884 | 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 1910 | 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  
# Line 1920 | Line 2401 | public class ConcurrentHashMap<K,V>
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
1924 <        (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;
1937            transferOrigin = n;
2418              transferIndex = n;
1939            Node<V> rev = new Node<V>(MOVED, tab, null, null);
1940            for (int k = n; k > 0;) {    // progressively reveal ready slots
1941                int nextk = (k > stride) ? k - stride : 0;
1942                for (int m = nextk; m < k; ++m)
1943                    nextTab[m] = rev;
1944                for (int m = n + nextk; m < n + k; ++m)
1945                    nextTab[m] = rev;
1946                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
1947            }
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 1968 | 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);
1977 <                        }
1978 <                        return;
1979 <                    }
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);
1986 <                    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;
2003 <                        else
2004 <                            hi = lastRun;
2005 <                        for (Node<V> p = f; p != lastRun; p = p.next) {
2006 <                            int ph = p.hash;
2007 <                            Object pk = p.key; V pv = p.val;
2008 <                            if ((ph & n) == 0)
2009 <                                lo = new Node<V>(ph, pk, pv, lo);
2010 <                            else
2011 <                                hi = new Node<V>(ph, pk, pv, hi);
2012 <                        }
2013 <                        setTabAt(nextTab, i, lo);
2014 <                        setTabAt(nextTab, i + n, hi);
2015 <                        setTabAt(tab, i, fwd);
2016 <                        advance = true;
2017 <                    }
2018 <                }
2019 <            }
2020 <            else if ((fk = f.key) instanceof TreeBin) {
2021 <                TreeBin<V> t = (TreeBin<V>)fk;
2022 <                t.acquire(0);
2023 <                try {
2024 <                    if (tabAt(tab, i) == f) {
2025 <                        TreeBin<V> lt = new TreeBin<V>();
2026 <                        TreeBin<V> ht = new TreeBin<V>();
2027 <                        int lc = 0, hc = 0;
2028 <                        for (Node<V> e = t.first; e != null; e = e.next) {
2029 <                            int h = e.hash;
2030 <                            Object k = e.key; V v = e.val;
2031 <                            if ((h & n) == 0) {
2032 <                                ++lc;
2033 <                                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 +                        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                          }
2040                        Node<V> ln, hn; // throw away trees if too small
2041                        if (lc < TREE_THRESHOLD) {
2042                            ln = null;
2043                            for (Node<V> p = lt.first; p != null; p = p.next)
2044                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2045                        }
2046                        else
2047                            ln = new Node<V>(MOVED, lt, null, null);
2048                        setTabAt(nextTab, i, ln);
2049                        if (hc < TREE_THRESHOLD) {
2050                            hn = null;
2051                            for (Node<V> p = ht.first; p != null; p = p.next)
2052                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2053                        }
2054                        else
2055                            hn = new Node<V>(MOVED, ht, null, null);
2056                        setTabAt(nextTab, i + n, hn);
2057                        setTabAt(tab, i, fwd);
2058                        advance = true;
2531                      }
2060                } finally {
2061                    t.release(0);
2532                  }
2533              }
2064            else
2065                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 2090 | 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 2128 | 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 2146 | 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 2162 | 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.
2170 <     *
2171 <     * At each step, the iterator snapshots the key ("nextKey") and
2172 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2173 <     * snapshot, has a non-null user value). Because val fields can
2174 <     * change (including to null, indicating deletion), field nextVal
2175 <     * might not be accurate at point of use, but still maintains the
2176 <     * weak consistency property of holding a value that was once
2177 <     * valid. To support iterator.remove, the nextKey field is not
2178 <     * updated (nulled out) when the iterator cannot advance.
2179 <     *
2180 <     * Exported iterators must track whether the iterator has advanced
2181 <     * (in hasNext vs next) (by setting/checking/nulling field
2182 <     * nextVal), and then extract key, value, or key-value pairs as
2183 <     * return values of next().
2184 <     *
2185 <     * Method advance visits once each still-valid node that was
2186 <     * reachable upon iterator construction. It might miss some that
2187 <     * were added to a bin after the bin was visited, which is OK wrt
2188 <     * consistency guarantees. Maintaining this property in the face
2189 <     * of possible ongoing resizes requires a fair amount of
2190 <     * bookkeeping state that is difficult to optimize away amidst
2191 <     * volatile accesses.  Even so, traversal maintains reasonable
2192 <     * throughput.
2193 <     *
2194 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2195 <     * However, if the table has been resized, then all future steps
2196 <     * must traverse both the bin at the current index as well as at
2197 <     * (index + baseSize); and so on for further resizings. To
2198 <     * paranoically cope with potential sharing by users of iterators
2199 <     * across threads, iteration terminates if a bounds checks fails
2200 <     * for a table read.
2201 <     *
2202 <     * Methods advanceKey and advanceValue are specializations of the
2203 <     * common cases of advance, relaying to the full version
2204 <     * otherwise. The forEachKey and forEachValue methods further
2205 <     * specialize, bypassing all incremental field updates in most cases.
2206 <     *
2207 <     * This class supports both Spliterator-based traversal and
2208 <     * CountedCompleter-based bulk tasks. The same "batch" field is
2209 <     * used, but in slightly different ways, in the two cases.  For
2210 <     * Spliterators, it is a saturating (at Integer.MAX_VALUE)
2211 <     * estimate of element coverage. For CHM tasks, it is a pre-scaled
2212 <     * size that halves down to zero for leaf tasks, that is only
2213 <     * computed upon execution of the task. (Tasks can be submitted to
2214 <     * any pool, of any size, so we don't know scale factors until
2215 <     * running.)
2216 <     *
2217 <     * This class extends CountedCompleter to streamline parallel
2218 <     * iteration in bulk operations. This adds only a few fields of
2219 <     * space overhead, which is small enough in cases where it is not
2220 <     * needed to not worry about it.  Because CountedCompleter is
2221 <     * Serializable, but iterators need not be, we need to add warning
2222 <     * suppressions.
2645 >     * Replaces all linked nodes in bin at given index unless table is
2646 >     * too small, in which case resizes instead.
2647       */
2648 <    @SuppressWarnings("serial") static class Traverser<K,V,R>
2649 <        extends CountedCompleter<R> {
2650 <        final ConcurrentHashMap<K,V> map;
2651 <        Node<V> next;        // the next entry to use
2652 <        K nextKey;           // cached key field of next
2653 <        V nextVal;           // cached val field of next
2654 <        Node<V>[] tab;       // current table; updated if resized
2655 <        int index;           // index of bin to use next
2656 <        int baseIndex;       // current index of initial table
2657 <        int baseLimit;       // index bound for initial table
2658 <        final int baseSize;  // initial table size
2659 <        int batch;           // split control
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 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2668 >                    }
2669 >                }
2670 >            }
2671 >        }
2672 >    }
2673  
2674 <        /** Creates iterator for all entries in the table. */
2675 <        Traverser(ConcurrentHashMap<K,V> map) {
2676 <            this.map = map;
2677 <            Node<V>[] t = this.tab = map.table;
2678 <            baseLimit = baseSize = (t == null) ? 0 : t.length;
2674 >    /**
2675 >     * Returns a list of non-TreeNodes replacing those in given list.
2676 >     */
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 <        /** Task constructor */
2691 <        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it, int batch) {
2692 <            super(it);
2693 <            this.map = map;
2694 <            this.batch = batch; // -1 if unknown
2695 <            if (it == null) {
2696 <                Node<V>[] t = this.tab = map.table;
2697 <                baseLimit = baseSize = (t == null) ? 0 : t.length;
2698 <            }
2699 <            else { // split parent
2700 <                this.tab = it.tab;
2701 <                this.baseSize = it.baseSize;
2702 <                int hi = this.baseLimit = it.baseLimit;
2703 <                it.baseLimit = this.index = this.baseIndex =
2704 <                    (hi + it.baseIndex) >>> 1;
2705 <            }
2690 >    /* ---------------- TreeNodes -------------- */
2691 >
2692 >    /**
2693 >     * Nodes for use in TreeBins.
2694 >     */
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 >        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 <        /** Spliterator constructor */
2709 <        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it) {
2264 <            super(it);
2265 <            this.map = map;
2266 <            if (it == null) {
2267 <                Node<V>[] t = this.tab = map.table;
2268 <                baseLimit = baseSize = (t == null) ? 0 : t.length;
2269 <                long n = map.sumCount();
2270 <                batch = ((n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2271 <                         (int)n);
2272 <            }
2273 <            else {
2274 <                this.tab = it.tab;
2275 <                this.baseSize = it.baseSize;
2276 <                int hi = this.baseLimit = it.baseLimit;
2277 <                it.baseLimit = this.index = this.baseIndex =
2278 <                    (hi + it.baseIndex) >>> 1;
2279 <                this.batch = it.batch >>>= 1;
2280 <            }
2708 >        Node<K,V> find(int h, Object k) {
2709 >            return findTreeNode(h, k, null);
2710          }
2711  
2712          /**
2713 <         * Advances if possible, returning next valid value, or null if none.
2713 >         * Returns the TreeNode (or null if not found) for the given key
2714 >         * starting at given root.
2715           */
2716 <        @SuppressWarnings("unchecked") final V advance() {
2717 <            for (Node<V> e = next;;) {
2718 <                if (e != null)                  // advance past used/skipped node
2719 <                    e = next = e.next;
2720 <                while (e == null) {             // get to next non-null bin
2721 <                    Node<V>[] t; int i, n;      // must use locals in checks
2722 <                    if (baseIndex >= baseLimit || (t = tab) == null ||
2723 <                        (n = t.length) <= (i = index) || i < 0)
2724 <                        return nextVal = null;
2725 <                    if ((e = next = tabAt(t, index)) != null && e.hash < 0) {
2726 <                        Object ek;
2727 <                        if ((ek = e.key) instanceof TreeBin)
2728 <                            e = ((TreeBin<V>)ek).first;
2729 <                        else {
2730 <                            tab = (Node<V>[])ek;
2731 <                            continue;           // restarts due to null val
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 >    /* ---------------- TreeBins -------------- */
2747 >
2748 >    /**
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 >         * 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                      }
2304                    if ((index += baseSize) >= n)
2305                        index = ++baseIndex;    // visit upper slots if present
2823                  }
2307                nextKey = (K)e.key;
2308                if ((nextVal = e.val) != null) // skip deleted or special nodes
2309                    return nextVal;
2824              }
2825 +            this.root = r;
2826 +            assert checkInvariants(root);
2827          }
2828  
2829          /**
2830 <         * Common case version for value traversal
2830 >         * Acquires write lock for tree restructuring.
2831           */
2832 <        @SuppressWarnings("unchecked") final V advanceValue() {
2833 <            outer: for (Node<V> e = next;;) {
2834 <                if (e == null || (e = e.next) == null) {
2835 <                    Node<V>[] t; int i, len, n; Object ek;
2836 <                    if ((t = tab) == null ||
2837 <                        baseSize != (len = t.length) ||
2838 <                        len < (n = baseLimit) ||
2839 <                        baseIndex != (i = index))
2840 <                        break;
2841 <                    do {
2842 <                        if (i < 0 || i >= n) {
2843 <                            index = baseIndex = n;
2844 <                            next = null;
2845 <                            return nextVal = null;
2846 <                        }
2847 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2848 <                            if ((ek = e.key) instanceof TreeBin)
2849 <                                e = ((TreeBin<V>)ek).first;
2850 <                            else {
2851 <                                index = baseIndex = i;
2852 <                                next = null;
2853 <                                tab = (Node<V>[])ek;
2854 <                                break outer;
2855 <                            }
2340 <                        }
2341 <                        ++i;
2342 <                    } while (e == null);
2343 <                    index = baseIndex = i;
2832 >        private final void lockRoot() {
2833 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2834 >                contendedLock(); // offload to separate method
2835 >        }
2836 >
2837 >        /**
2838 >         * Releases write lock for tree restructuring.
2839 >         */
2840 >        private final void unlockRoot() {
2841 >            lockState = 0;
2842 >        }
2843 >
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 <                V v;
2858 <                K k = (K)e.key;
2859 <                if ((v = e.val) != null) {
2860 <                    nextVal = v;
2861 <                    nextKey = k;
2350 <                    next = e;
2351 <                    return v;
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              }
2354            return advance();
2866          }
2867  
2868          /**
2869 <         * Common case version for key traversal
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 <        @SuppressWarnings("unchecked") final K advanceKey() {
2874 <            outer: for (Node<V> e = next;;) {
2875 <                if (e == null || (e = e.next) == null) {
2876 <                    Node<V>[] t; int i, len, n; Object ek;
2877 <                    if ((t = tab) == null ||
2878 <                        baseSize != (len = t.length) ||
2879 <                        len < (n = baseLimit) ||
2880 <                        baseIndex != (i = index))
2881 <                        break;
2882 <                    do {
2883 <                        if (i < 0 || i >= n) {
2884 <                            index = baseIndex = n;
2885 <                            next = null;
2886 <                            nextVal = null;
2887 <                            return null;
2888 <                        }
2889 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2890 <                            if ((ek = e.key) instanceof TreeBin)
2891 <                                e = ((TreeBin<V>)ek).first;
2892 <                            else {
2893 <                                index = baseIndex = i;
2381 <                                next = null;
2382 <                                tab = (Node<V>[])ek;
2383 <                                break outer;
2384 <                            }
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 <                        ++i;
2896 <                    } while (e == null);
2388 <                    index = baseIndex = i;
2389 <                }
2390 <                V v;
2391 <                K k = (K)e.key;
2392 <                if ((v = e.val) != null) {
2393 <                    nextVal = v;
2394 <                    nextKey = k;
2395 <                    next = e;
2396 <                    return k;
2895 >                        return p;
2896 >                    }
2897                  }
2898              }
2899 <            return (advance() == null) ? null : nextKey;
2899 >            return null;
2900          }
2901  
2902 <        @SuppressWarnings("unchecked") final void forEachValue(Consumer<? super V> action) {
2903 <            if (action == null) throw new NullPointerException();
2904 <            Node<V>[] t; int i, len, n;
2905 <            if ((t = tab) != null && baseSize == (len = t.length) &&
2906 <                len >= (n = baseLimit) && baseIndex == (i = index)) {
2907 <                index = baseIndex = n;
2908 <                nextVal = null;
2909 <                Node<V> e = next;
2910 <                next = null;
2911 <                if (e != null)
2912 <                    e = e.next;
2913 <                outer: for (;; e = e.next) {
2914 <                    V v; Object ek;
2915 <                    for (; e == null; ++i) {
2916 <                        if (i < 0 || i >= n)
2917 <                            return;
2918 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2919 <                            if ((ek = e.key) instanceof TreeBin)
2920 <                                e = ((TreeBin<V>)ek).first;
2921 <                            else {
2922 <                                index = baseIndex = i;
2923 <                                tab = (Node<V>[])ek;
2924 <                                break outer;
2925 <                            }
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 <                    if ((v = e.val) != null)
2429 <                        action.accept(v);
2956 >                    break;
2957                  }
2958              }
2959 <            V v;
2960 <            while ((v = advance()) != null)
2434 <                action.accept(v);
2959 >            assert checkInvariants(root);
2960 >            return null;
2961          }
2962  
2963 <        @SuppressWarnings("unchecked") final void forEachKey(Consumer<? super K> action) {
2964 <            if (action == null) throw new NullPointerException();
2965 <            Node<V>[] t; int i, len, n;
2966 <            if ((t = tab) != null && baseSize == (len = t.length) &&
2967 <                len >= (n = baseLimit) && baseIndex == (i = index)) {
2968 <                index = baseIndex = n;
2969 <                nextVal = null;
2970 <                Node<V> e = next;
2971 <                next = null;
2972 <                if (e != null)
2973 <                    e = e.next;
2974 <                outer: for (;; e = e.next) {
2975 <                    for (; e == null; ++i) {
2976 <                        if (i < 0 || i >= n)
2977 <                            return;
2978 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2979 <                            Object ek;
2980 <                            if ((ek = e.key) instanceof TreeBin)
2981 <                                e = ((TreeBin<V>)ek).first;
2982 <                            else {
2983 <                                index = baseIndex = i;
2984 <                                tab = (Node<V>[])ek;
2985 <                                break outer;
2986 <                            }
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 <                    Object k = e.key;
3018 <                    if (e.val != null)
3019 <                        action.accept((K)k);
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 +                root = (p.red) ? r : balanceDeletion(r, replacement);
3051 +
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 <            while (advance() != null)
3066 <                action.accept(nextKey);
3065 >            assert checkInvariants(root);
3066 >            return false;
3067          }
3068  
3069 <        public final void remove() {
3070 <            K k = nextKey;
2474 <            if (k == null && (advanceValue() == null || (k = nextKey) == null))
2475 <                throw new IllegalStateException();
2476 <            map.internalReplace(k, null, null);
2477 <        }
3069 >        /* ------------------------------------------------------------ */
3070 >        // Red-black tree methods, all adapted from CLR
3071  
3072 <        public final boolean hasNext() {
3073 <            return nextVal != null || advanceValue() != null;
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 <        public final boolean hasMoreElements() { return hasNext(); }
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 <        public void compute() { } // default no-op CountedCompleter body
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 <        public long estimateSize() { return batch; }
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 <         * Returns a batch value > 0 if this task should (and must) be
2491 <         * split, if so, adding to pending count, and in any case
2492 <         * updating batch value. The initial batch value is approx
2493 <         * exp2 of the number of times (minus one) to split task by
2494 <         * two before executing leaf action. This value is faster to
2495 <         * compute and more convenient to use as a guide to splitting
2496 <         * than is the depth, since it is used while dividing by two
2497 <         * anyway.
3256 >         * Checks invariants recursively for the tree of Nodes rooted at t.
3257           */
3258 <        final int preSplit() {
3259 <            int b;  ForkJoinPool pool;
3260 <            if ((b = batch) < 0) { // force initialization
3261 <                int sp = (((pool = getPool()) == null) ?
3262 <                          ForkJoinPool.getCommonPoolParallelism() :
3263 <                          pool.getParallelism()) << 3; // slack of 8
3264 <                long n = map.sumCount();
3265 <                b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
3266 <            }
3267 <            b = (b <= 1 || baseIndex >= baseLimit) ? 0 : (b >>> 1);
3268 <            if ((batch = b) > 0)
3269 <                addToPendingCount(1);
3270 <            return b;
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          }
2513    }
2514
2515    /* ---------------- Public operations -------------- */
2516
2517    /**
2518     * Creates a new, empty map with the default initial table size (16).
2519     */
2520    public ConcurrentHashMap() {
2521    }
2522
2523    /**
2524     * Creates a new, empty map with an initial table size
2525     * accommodating the specified number of elements without the need
2526     * to dynamically resize.
2527     *
2528     * @param initialCapacity The implementation performs internal
2529     * sizing to accommodate this many elements.
2530     * @throws IllegalArgumentException if the initial capacity of
2531     * elements is negative
2532     */
2533    public ConcurrentHashMap(int initialCapacity) {
2534        if (initialCapacity < 0)
2535            throw new IllegalArgumentException();
2536        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2537                   MAXIMUM_CAPACITY :
2538                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2539        this.sizeCtl = cap;
2540    }
2541
2542    /**
2543     * Creates a new map with the same mappings as the given map.
2544     *
2545     * @param m the map
2546     */
2547    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2548        this.sizeCtl = DEFAULT_CAPACITY;
2549        internalPutAll(m);
2550    }
2551
2552    /**
2553     * Creates a new, empty map with an initial table size based on
2554     * the given number of elements ({@code initialCapacity}) and
2555     * initial table density ({@code loadFactor}).
2556     *
2557     * @param initialCapacity the initial capacity. The implementation
2558     * performs internal sizing to accommodate this many elements,
2559     * given the specified load factor.
2560     * @param loadFactor the load factor (table density) for
2561     * establishing the initial table size
2562     * @throws IllegalArgumentException if the initial capacity of
2563     * elements is negative or the load factor is nonpositive
2564     *
2565     * @since 1.6
2566     */
2567    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
2568        this(initialCapacity, loadFactor, 1);
2569    }
2570
2571    /**
2572     * Creates a new, empty map with an initial table size based on
2573     * the given number of elements ({@code initialCapacity}), table
2574     * density ({@code loadFactor}), and number of concurrently
2575     * updating threads ({@code concurrencyLevel}).
2576     *
2577     * @param initialCapacity the initial capacity. The implementation
2578     * performs internal sizing to accommodate this many elements,
2579     * given the specified load factor.
2580     * @param loadFactor the load factor (table density) for
2581     * establishing the initial table size
2582     * @param concurrencyLevel the estimated number of concurrently
2583     * updating threads. The implementation may use this value as
2584     * a sizing hint.
2585     * @throws IllegalArgumentException if the initial capacity is
2586     * negative or the load factor or concurrencyLevel are
2587     * nonpositive
2588     */
2589    public ConcurrentHashMap(int initialCapacity,
2590                               float loadFactor, int concurrencyLevel) {
2591        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2592            throw new IllegalArgumentException();
2593        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2594            initialCapacity = concurrencyLevel;   // as estimated threads
2595        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2596        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2597            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2598        this.sizeCtl = cap;
2599    }
2600
2601    /**
2602     * Creates a new {@link Set} backed by a ConcurrentHashMap
2603     * from the given type to {@code Boolean.TRUE}.
2604     *
2605     * @return the new set
2606     */
2607    public static <K> KeySetView<K,Boolean> newKeySet() {
2608        return new KeySetView<K,Boolean>
2609            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2610    }
2611
2612    /**
2613     * Creates a new {@link Set} backed by a ConcurrentHashMap
2614     * from the given type to {@code Boolean.TRUE}.
2615     *
2616     * @param initialCapacity The implementation performs internal
2617     * sizing to accommodate this many elements.
2618     * @throws IllegalArgumentException if the initial capacity of
2619     * elements is negative
2620     * @return the new set
2621     */
2622    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2623        return new KeySetView<K,Boolean>
2624            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2625    }
2626
2627    /**
2628     * {@inheritDoc}
2629     */
2630    public boolean isEmpty() {
2631        return sumCount() <= 0L; // ignore transient negative values
2632    }
3279  
3280 <    /**
3281 <     * {@inheritDoc}
3282 <     */
3283 <    public int size() {
3284 <        long n = sumCount();
3285 <        return ((n < 0L) ? 0 :
3286 <                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
3287 <                (int)n);
3288 <    }
2643 <
2644 <    /**
2645 <     * Returns the number of mappings. This method should be used
2646 <     * instead of {@link #size} because a ConcurrentHashMap may
2647 <     * contain more mappings than can be represented as an int. The
2648 <     * value returned is an estimate; the actual count may differ if
2649 <     * there are concurrent insertions or removals.
2650 <     *
2651 <     * @return the number of mappings
2652 <     */
2653 <    public long mappingCount() {
2654 <        long n = sumCount();
2655 <        return (n < 0L) ? 0L : n; // ignore transient negative values
2656 <    }
2657 <
2658 <    /**
2659 <     * Returns the value to which the specified key is mapped,
2660 <     * or {@code null} if this map contains no mapping for the key.
2661 <     *
2662 <     * <p>More formally, if this map contains a mapping from a key
2663 <     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2664 <     * then this method returns {@code v}; otherwise it returns
2665 <     * {@code null}.  (There can be at most one such mapping.)
2666 <     *
2667 <     * @throws NullPointerException if the specified key is null
2668 <     */
2669 <    public V get(Object key) {
2670 <        return internalGet(key);
2671 <    }
2672 <
2673 <    /**
2674 <     * Returns the value to which the specified key is mapped,
2675 <     * or the given defaultValue if this map contains no mapping for the key.
2676 <     *
2677 <     * @param key the key
2678 <     * @param defaultValue the value to return if this map contains
2679 <     * no mapping for the given key
2680 <     * @return the mapping for the key, if present; else the defaultValue
2681 <     * @throws NullPointerException if the specified key is null
2682 <     */
2683 <    public V getOrDefault(Object key, V defaultValue) {
2684 <        V v;
2685 <        return (v = internalGet(key)) == null ? defaultValue : v;
2686 <    }
2687 <
2688 <    /**
2689 <     * Tests if the specified object is a key in this table.
2690 <     *
2691 <     * @param  key possible key
2692 <     * @return {@code true} if and only if the specified object
2693 <     *         is a key in this table, as determined by the
2694 <     *         {@code equals} method; {@code false} otherwise
2695 <     * @throws NullPointerException if the specified key is null
2696 <     */
2697 <    public boolean containsKey(Object key) {
2698 <        return internalGet(key) != null;
2699 <    }
2700 <
2701 <    /**
2702 <     * Returns {@code true} if this map maps one or more keys to the
2703 <     * specified value. Note: This method may require a full traversal
2704 <     * of the map, and is much slower than method {@code containsKey}.
2705 <     *
2706 <     * @param value value whose presence in this map is to be tested
2707 <     * @return {@code true} if this map maps one or more keys to the
2708 <     *         specified value
2709 <     * @throws NullPointerException if the specified value is null
2710 <     */
2711 <    public boolean containsValue(Object value) {
2712 <        if (value == null)
2713 <            throw new NullPointerException();
2714 <        V v;
2715 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2716 <        while ((v = it.advanceValue()) != null) {
2717 <            if (v == value || value.equals(v))
2718 <                return true;
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          }
2720        return false;
3290      }
3291  
3292 <    /**
2724 <     * Legacy method testing if some key maps into the specified value
2725 <     * in this table.  This method is identical in functionality to
2726 <     * {@link #containsValue(Object)}, and exists solely to ensure
2727 <     * full compatibility with class {@link java.util.Hashtable},
2728 <     * which supported this method prior to introduction of the
2729 <     * Java Collections framework.
2730 <     *
2731 <     * @param  value a value to search for
2732 <     * @return {@code true} if and only if some key maps to the
2733 <     *         {@code value} argument in this table as
2734 <     *         determined by the {@code equals} method;
2735 <     *         {@code false} otherwise
2736 <     * @throws NullPointerException if the specified value is null
2737 <     */
2738 <    @Deprecated public boolean contains(Object value) {
2739 <        return containsValue(value);
2740 <    }
2741 <
2742 <    /**
2743 <     * Maps the specified key to the specified value in this table.
2744 <     * Neither the key nor the value can be null.
2745 <     *
2746 <     * <p>The value can be retrieved by calling the {@code get} method
2747 <     * with a key that is equal to the original key.
2748 <     *
2749 <     * @param key key with which the specified value is to be associated
2750 <     * @param value value to be associated with the specified key
2751 <     * @return the previous value associated with {@code key}, or
2752 <     *         {@code null} if there was no mapping for {@code key}
2753 <     * @throws NullPointerException if the specified key or value is null
2754 <     */
2755 <    public V put(K key, V value) {
2756 <        return internalPut(key, value, false);
2757 <    }
2758 <
2759 <    /**
2760 <     * {@inheritDoc}
2761 <     *
2762 <     * @return the previous value associated with the specified key,
2763 <     *         or {@code null} if there was no mapping for the key
2764 <     * @throws NullPointerException if the specified key or value is null
2765 <     */
2766 <    public V putIfAbsent(K key, V value) {
2767 <        return internalPut(key, value, true);
2768 <    }
2769 <
2770 <    /**
2771 <     * Copies all of the mappings from the specified map to this one.
2772 <     * These mappings replace any mappings that this map had for any of the
2773 <     * keys currently in the specified map.
2774 <     *
2775 <     * @param m mappings to be stored in this map
2776 <     */
2777 <    public void putAll(Map<? extends K, ? extends V> m) {
2778 <        internalPutAll(m);
2779 <    }
2780 <
2781 <    /**
2782 <     * If the specified key is not already associated with a value (or
2783 <     * is mapped to {@code null}), attempts to compute its value using
2784 <     * the given mapping function and enters it into this map unless
2785 <     * {@code null}. The entire method invocation is performed
2786 <     * atomically, so the function is applied at most once per key.
2787 <     * Some attempted update operations on this map by other threads
2788 <     * may be blocked while computation is in progress, so the
2789 <     * computation should be short and simple, and must not attempt to
2790 <     * update any other mappings of this Map.
2791 <     *
2792 <     * @param key key with which the specified value is to be associated
2793 <     * @param mappingFunction the function to compute a value
2794 <     * @return the current (existing or computed) value associated with
2795 <     *         the specified key, or null if the computed value is null
2796 <     * @throws NullPointerException if the specified key or mappingFunction
2797 <     *         is null
2798 <     * @throws IllegalStateException if the computation detectably
2799 <     *         attempts a recursive update to this map that would
2800 <     *         otherwise never complete
2801 <     * @throws RuntimeException or Error if the mappingFunction does so,
2802 <     *         in which case the mapping is left unestablished
2803 <     */
2804 <    public V computeIfAbsent
2805 <        (K key, Function<? super K, ? extends V> mappingFunction) {
2806 <        return internalComputeIfAbsent(key, mappingFunction);
2807 <    }
2808 <
2809 <    /**
2810 <     * If the value for the specified key is present and non-null,
2811 <     * attempts to compute a new mapping given the key and its current
2812 <     * mapped value.  The entire method invocation is performed
2813 <     * atomically.  Some attempted update operations on this map by
2814 <     * other threads may be blocked while computation is in progress,
2815 <     * so the computation should be short and simple, and must not
2816 <     * attempt to update any other mappings of this Map.
2817 <     *
2818 <     * @param key key with which a value may be associated
2819 <     * @param remappingFunction the function to compute a value
2820 <     * @return the new value associated with the specified key, or null if none
2821 <     * @throws NullPointerException if the specified key or remappingFunction
2822 <     *         is null
2823 <     * @throws IllegalStateException if the computation detectably
2824 <     *         attempts a recursive update to this map that would
2825 <     *         otherwise never complete
2826 <     * @throws RuntimeException or Error if the remappingFunction does so,
2827 <     *         in which case the mapping is unchanged
2828 <     */
2829 <    public V computeIfPresent
2830 <        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2831 <        return internalCompute(key, true, remappingFunction);
2832 <    }
2833 <
2834 <    /**
2835 <     * Attempts to compute a mapping for the specified key and its
2836 <     * current mapped value (or {@code null} if there is no current
2837 <     * mapping). The entire method invocation is performed atomically.
2838 <     * Some attempted update operations on this map by other threads
2839 <     * may be blocked while computation is in progress, so the
2840 <     * computation should be short and simple, and must not attempt to
2841 <     * update any other mappings of this Map.
2842 <     *
2843 <     * @param key key with which the specified value is to be associated
2844 <     * @param remappingFunction the function to compute a value
2845 <     * @return the new value associated with the specified key, or null if none
2846 <     * @throws NullPointerException if the specified key or remappingFunction
2847 <     *         is null
2848 <     * @throws IllegalStateException if the computation detectably
2849 <     *         attempts a recursive update to this map that would
2850 <     *         otherwise never complete
2851 <     * @throws RuntimeException or Error if the remappingFunction does so,
2852 <     *         in which case the mapping is unchanged
2853 <     */
2854 <    public V compute
2855 <        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2856 <        return internalCompute(key, false, remappingFunction);
2857 <    }
2858 <
2859 <    /**
2860 <     * If the specified key is not already associated with a
2861 <     * (non-null) value, associates it with the given value.
2862 <     * Otherwise, replaces the value with the results of the given
2863 <     * remapping function, or removes if {@code null}. The entire
2864 <     * method invocation is performed atomically.  Some attempted
2865 <     * update operations on this map by other threads may be blocked
2866 <     * while computation is in progress, so the computation should be
2867 <     * short and simple, and must not attempt to update any other
2868 <     * mappings of this Map.
2869 <     *
2870 <     * @param key key with which the specified value is to be associated
2871 <     * @param value the value to use if absent
2872 <     * @param remappingFunction the function to recompute a value if present
2873 <     * @return the new value associated with the specified key, or null if none
2874 <     * @throws NullPointerException if the specified key or the
2875 <     *         remappingFunction is null
2876 <     * @throws RuntimeException or Error if the remappingFunction does so,
2877 <     *         in which case the mapping is unchanged
2878 <     */
2879 <    public V merge
2880 <        (K key, V value,
2881 <         BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2882 <        return internalMerge(key, value, remappingFunction);
2883 <    }
2884 <
2885 <    /**
2886 <     * Removes the key (and its corresponding value) from this map.
2887 <     * This method does nothing if the key is not in the map.
2888 <     *
2889 <     * @param  key the key that needs to be removed
2890 <     * @return the previous value associated with {@code key}, or
2891 <     *         {@code null} if there was no mapping for {@code key}
2892 <     * @throws NullPointerException if the specified key is null
2893 <     */
2894 <    public V remove(Object key) {
2895 <        return internalReplace(key, null, null);
2896 <    }
2897 <
2898 <    /**
2899 <     * {@inheritDoc}
2900 <     *
2901 <     * @throws NullPointerException if the specified key is null
2902 <     */
2903 <    public boolean remove(Object key, Object value) {
2904 <        if (key == null)
2905 <            throw new NullPointerException();
2906 <        return value != null && internalReplace(key, null, value) != null;
2907 <    }
2908 <
2909 <    /**
2910 <     * {@inheritDoc}
2911 <     *
2912 <     * @throws NullPointerException if any of the arguments are null
2913 <     */
2914 <    public boolean replace(K key, V oldValue, V newValue) {
2915 <        if (key == null || oldValue == null || newValue == null)
2916 <            throw new NullPointerException();
2917 <        return internalReplace(key, newValue, oldValue) != null;
2918 <    }
2919 <
2920 <    /**
2921 <     * {@inheritDoc}
2922 <     *
2923 <     * @return the previous value associated with the specified key,
2924 <     *         or {@code null} if there was no mapping for the key
2925 <     * @throws NullPointerException if the specified key or value is null
2926 <     */
2927 <    public V replace(K key, V value) {
2928 <        if (key == null || value == null)
2929 <            throw new NullPointerException();
2930 <        return internalReplace(key, value, null);
2931 <    }
2932 <
2933 <    /**
2934 <     * Removes all of the mappings from this map.
2935 <     */
2936 <    public void clear() {
2937 <        internalClear();
2938 <    }
2939 <
2940 <    /**
2941 <     * Returns a {@link Set} view of the keys contained in this map.
2942 <     * The set is backed by the map, so changes to the map are
2943 <     * reflected in the set, and vice-versa.
2944 <     *
2945 <     * @return the set view
2946 <     */
2947 <    public KeySetView<K,V> keySet() {
2948 <        KeySetView<K,V> ks = keySet;
2949 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2950 <    }
2951 <
2952 <    /**
2953 <     * Returns a {@link Set} view of the keys in this map, using the
2954 <     * given common mapped value for any additions (i.e., {@link
2955 <     * Collection#add} and {@link Collection#addAll(Collection)}).
2956 <     * This is of course only appropriate if it is acceptable to use
2957 <     * the same value for all additions from this view.
2958 <     *
2959 <     * @param mappedValue the mapped value to use for any additions
2960 <     * @return the set view
2961 <     * @throws NullPointerException if the mappedValue is null
2962 <     */
2963 <    public KeySetView<K,V> keySet(V mappedValue) {
2964 <        if (mappedValue == null)
2965 <            throw new NullPointerException();
2966 <        return new KeySetView<K,V>(this, mappedValue);
2967 <    }
3292 >    /* ----------------Table Traversal -------------- */
3293  
3294      /**
3295 <     * Returns a {@link Collection} view of the values contained in this map.
3296 <     * The collection is backed by the map, so changes to the map are
3297 <     * reflected in the collection, and vice-versa.
3298 <     *
3299 <     * @return the collection view
3300 <     */
3301 <    public ValuesView<K,V> values() {
3302 <        ValuesView<K,V> vs = values;
3303 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
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 mappings contained in this map.
3308 <     * The set is backed by the map, so changes to the map are
2984 <     * reflected in the set, and vice-versa.  The set supports element
2985 <     * removal, which removes the corresponding mapping from the map,
2986 <     * via the {@code Iterator.remove}, {@code Set.remove},
2987 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
2988 <     * operations.  It does not support the {@code add} or
2989 <     * {@code addAll} operations.
2990 <     *
2991 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2992 <     * that will never throw {@link ConcurrentModificationException},
2993 <     * and guarantees to traverse elements as they existed upon
2994 <     * construction of the iterator, and may (but is not guaranteed to)
2995 <     * reflect any modifications subsequent to construction.
3307 >     * Encapsulates traversal for methods such as containsValue; also
3308 >     * serves as a base class for other iterators and spliterators.
3309       *
3310 <     * @return the set view
3311 <     */
3312 <    public Set<Map.Entry<K,V>> entrySet() {
3313 <        EntrySetView<K,V> es = entrySet;
3314 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
3315 <    }
3316 <
3317 <    /**
3005 <     * Returns an enumeration of the keys in this table.
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 <     * @return an enumeration of the keys in this table
3320 <     * @see #keySet()
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 Enumeration<K> keys() {
3328 <        return new KeyIterator<K,V>(this);
3329 <    }
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 values in this table.
3346 <     *
3347 <     * @return an enumeration of the values in this table
3348 <     * @see #values()
3349 <     */
3350 <    public Enumeration<V> elements() {
3351 <        return new ValueIterator<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 the hash code value for this {@link Map}, i.e.,
3379 <     * the sum of, for each key-value pair in the map,
3380 <     * {@code key.hashCode() ^ value.hashCode()}.
3381 <     *
3382 <     * @return the hash code value for this map
3383 <     */
3384 <    public int hashCode() {
3385 <        int h = 0;
3386 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3387 <        V v;
3388 <        while ((v = it.advanceValue()) != null) {
3389 <            h += it.nextKey.hashCode() ^ v.hashCode();
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          }
3038        return h;
3039    }
3392  
3393 <    /**
3394 <     * Returns a string representation of this map.  The string
3395 <     * representation consists of a list of key-value mappings (in no
3396 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3397 <     * mappings are separated by the characters {@code ", "} (comma
3398 <     * and space).  Each key-value mapping is rendered as the key
3399 <     * followed by an equals sign ("{@code =}") followed by the
3400 <     * associated value.
3401 <     *
3402 <     * @return a string representation of this map
3403 <     */
3404 <    public String toString() {
3405 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3406 <        StringBuilder sb = new StringBuilder();
3407 <        sb.append('{');
3408 <        V v;
3057 <        if ((v = it.advanceValue()) != null) {
3058 <            for (;;) {
3059 <                K k = it.nextKey;
3060 <                sb.append(k == this ? "(this Map)" : k);
3061 <                sb.append('=');
3062 <                sb.append(v == this ? "(this Map)" : v);
3063 <                if ((v = it.advanceValue()) == null)
3064 <                    break;
3065 <                sb.append(',').append(' ');
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          }
3068        return sb.append('}').toString();
3413      }
3414  
3415      /**
3416 <     * Compares the specified object with this map for equality.
3417 <     * Returns {@code true} if the given object is a map with the same
3074 <     * mappings as this map.  This operation may return misleading
3075 <     * results if either map is concurrently modified during execution
3076 <     * of this method.
3077 <     *
3078 <     * @param o object to be compared for equality with this map
3079 <     * @return {@code true} if the specified object is equal to this map
3416 >     * Base of key, value, and entry Iterators. Adds fields to
3417 >     * Traverser to support iterator.remove.
3418       */
3419 <    public boolean equals(Object o) {
3420 <        if (o != this) {
3421 <            if (!(o instanceof Map))
3422 <                return false;
3423 <            Map<?,?> m = (Map<?,?>) o;
3424 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3425 <            V val;
3426 <            while ((val = it.advanceValue()) != null) {
3089 <                Object v = m.get(it.nextKey);
3090 <                if (v == null || (v != val && !v.equals(val)))
3091 <                    return false;
3092 <            }
3093 <            for (Map.Entry<?,?> e : m.entrySet()) {
3094 <                Object mk, mv, v;
3095 <                if ((mk = e.getKey()) == null ||
3096 <                    (mv = e.getValue()) == null ||
3097 <                    (v = internalGet(mk)) == null ||
3098 <                    (mv != v && !mv.equals(v)))
3099 <                    return false;
3100 <            }
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          }
3102        return true;
3103    }
3428  
3429 <    /* ----------------Iterators -------------- */
3429 >        public final boolean hasNext() { return next != null; }
3430 >        public final boolean hasMoreElements() { return next != null; }
3431  
3432 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3433 <        extends Traverser<K,V,Object>
3434 <        implements Spliterator<K>, Iterator<K>, Enumeration<K> {
3435 <        KeyIterator(ConcurrentHashMap<K,V> map) { super(map); }
3436 <        KeyIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3437 <            super(map, it);
3113 <        }
3114 <        public Spliterator<K> trySplit() {
3115 <            return (baseLimit - baseIndex <= 1) ? null :
3116 <                new KeyIterator<K,V>(map, this);
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          }
3439 +    }
3440 +
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 +
3448          public final K next() {
3449 <            K k;
3450 <            if ((k = (nextVal == null) ? advanceKey() : nextKey) == null)
3449 >            Node<K,V> p;
3450 >            if ((p = next) == null)
3451                  throw new NoSuchElementException();
3452 <            nextVal = null;
3452 >            K k = p.key;
3453 >            lastReturned = p;
3454 >            advance();
3455              return k;
3456          }
3457  
3458          public final K nextElement() { return next(); }
3127
3128        public Iterator<K> iterator() { return this; }
3129
3130        public void forEachRemaining(Consumer<? super K> action) {
3131            forEachKey(action);
3132        }
3133
3134        public boolean tryAdvance(Consumer<? super K> block) {
3135            if (block == null) throw new NullPointerException();
3136            K k;
3137            if ((k = advanceKey()) == null)
3138                return false;
3139            block.accept(k);
3140            return true;
3141        }
3142
3143        public int characteristics() {
3144            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3145                Spliterator.NONNULL;
3146        }
3147
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) {
3155 <            super(map, it);
3156 <        }
3157 <        public Spliterator<V> trySplit() {
3158 <            return (baseLimit - baseIndex <= 1) ? null :
3159 <                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 = advanceValue()) == 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(); }
3171
3172        public Iterator<V> iterator() { return this; }
3173
3174        public void forEachRemaining(Consumer<? super V> action) {
3175            forEachValue(action);
3176        }
3177
3178        public boolean tryAdvance(Consumer<? super V> block) {
3179            V v;
3180            if (block == null) throw new NullPointerException();
3181            if ((v = advanceValue()) == null)
3182                return false;
3183            block.accept(v);
3184            return true;
3185        }
3186
3187        public int characteristics() {
3188            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3189        }
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) {
3197 <            super(map, it);
3198 <        }
3199 <        public Spliterator<Map.Entry<K,V>> trySplit() {
3200 <            return (baseLimit - baseIndex <= 1) ? null :
3201 <                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          public final Map.Entry<K,V> next() {
3489 <            V v;
3490 <            if ((v = nextVal) == null && (v = advanceValue()) == null)
3489 >            Node<K,V> p;
3490 >            if ((p = next) == null)
3491                  throw new NoSuchElementException();
3492 <            K k = nextKey;
3493 <            nextVal = null;
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          }
3212
3213        public Iterator<Map.Entry<K,V>> iterator() { return this; }
3214
3215        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3216            if (action == null) throw new NullPointerException();
3217            V v;
3218            while ((v = advanceValue()) != null)
3219                action.accept(entryFor(nextKey, v));
3220        }
3221
3222        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> block) {
3223            V v;
3224            if (block == null) throw new NullPointerException();
3225            if ((v = advanceValue()) == null)
3226                return false;
3227            block.accept(entryFor(nextKey, v));
3228            return true;
3229        }
3230
3231        public int characteristics() {
3232            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3233                Spliterator.NONNULL;
3234        }
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> {
3504          final K key; // non-null
# Line 3246 | Line 3509 | public class ConcurrentHashMap<K,V>
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 3265 | 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 3277 | 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 <    /* ---------------- Serialization Support -------------- */
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 <    /**
3562 <     * Stripped-down version of helper class used in previous version,
3563 <     * declared for the sake of serialization compatibility
3564 <     */
3565 <    static class Segment<K,V> implements Serializable {
3566 <        private static final long serialVersionUID = 2249069246763182397L;
3567 <        final float loadFactor;
3568 <        Segment(float lf) { this.loadFactor = lf; }
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 >        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.
3307 <     * The key-value mappings are emitted in no particular order.
3308 <     */
3309 <    @SuppressWarnings("unchecked") private void writeObject
3310 <        (java.io.ObjectOutputStream s)
3311 <        throws java.io.IOException {
3312 <        if (segments == null) { // for serialization compatibility
3313 <            segments = (Segment<K,V>[])
3314 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3315 <            for (int i = 0; i < segments.length; ++i)
3316 <                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.advanceValue()) != 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          }
3325        s.writeObject(null);
3326        s.writeObject(null);
3327        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();
3345 <            V v = (V) s.readObject();
3346 <            if (k != null && v != null) {
3347 <                int h = spread(k.hashCode());
3348 <                p = new Node<V>(h, k, v, p);
3349 <                ++size;
3350 <            }
3351 <            else
3352 <                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;
3375 <                            Node<V> next = p.next;
3376 <                            Node<V> q = p.next = tabAt(tab, j);
3377 <                            setTabAt(tab, j, p);
3378 <                            if (!collide && q != null && q.hash == p.hash)
3379 <                                collide = true;
3380 <                            p = next;
3381 <                        }
3382 <                        table = tab;
3383 <                        addCount(size, -1);
3384 <                        sc = n - (n >>> 2);
3385 <                    }
3386 <                } finally {
3387 <                    sizeCtl = sc;
3388 <                }
3389 <                if (collide) { // rescan and convert to TreeBins
3390 <                    Node<V>[] tab = table;
3391 <                    for (int i = 0; i < tab.length; ++i) {
3392 <                        int c = 0;
3393 <                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3394 <                            if (++c > TREE_THRESHOLD &&
3395 <                                (e.key instanceof Comparable)) {
3396 <                                replaceWithTreeBin(tab, i, e.key);
3397 <                                break;
3398 <                            }
3399 <                        }
3400 <                    }
3401 <                }
3402 <            }
3403 <            if (!init) { // Can only happen if unsafely published.
3404 <                while (p != null) {
3405 <                    internalPut((K)p.key, p.val, false);
3406 <                    p = p.next;
3407 <                }
3408 <            }
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 <    public void forEachSequentially
3690 <        (BiConsumer<? 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.advanceValue()) != null)
3427 <            action.accept(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 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 <    public <U> void forEachSequentially
3711 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3712 <         Consumer<? 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.advanceValue()) != null) {
3447 <            if ((u = transformer.apply(it.nextKey, v)) != null)
3448 <                action.accept(u);
3449 <        }
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 <    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.advanceValue()) != null) {
3467 <            if ((u = searchFunction.apply(it.nextKey, v)) != null)
3468 <                return u;
3469 <        }
3470 <        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 3475 | 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 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 <    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.advanceValue()) != null) {
3493 <            if ((u = transformer.apply(it.nextKey, v)) != null)
3494 <                r = (r == null) ? u : reducer.apply(r, u);
3495 <        }
3496 <        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 3501 | 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 <    public double reduceToDoubleSequentially
3786 <        (ToDoubleBiFunction<? 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.advanceValue()) != null)
3520 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey, v));
3521 <        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 3526 | 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 <    public long reduceToLongSequentially
3812 <        (ToLongBiFunction<? 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.advanceValue()) != null)
3545 <            r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey, v));
3546 <        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 3551 | 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 <    public int reduceToIntSequentially
3838 <        (ToIntBiFunction<? 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.advanceValue()) != null)
3570 <            r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey, v));
3571 <        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 <    public void forEachKeySequentially
3857 <        (Consumer<? super K> action) {
3858 <        new Traverser<K,V,Object>(this).forEachKey(action);
3856 >    public void forEachKey(long parallelismThreshold,
3857 >                           Consumer<? super K> action) {
3858 >        if (action == null) throw new NullPointerException();
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 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 <    public <U> void forEachKeySequentially
3878 <        (Function<? super K, ? extends U> transformer,
3879 <         Consumer<? 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 <        K k; U u;
3884 <        while ((k = it.advanceKey()) != null) {
3601 <            if ((u = transformer.apply(k)) != null)
3602 <                action.accept(u);
3603 <        }
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 <    public <U> U searchKeysSequentially
3904 <        (Function<? super K, ? extends U> searchFunction) {
3905 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3906 <        K k; U u;
3907 <        while ((k = it.advanceKey()) != null) {
3908 <            if ((u = searchFunction.apply(k)) != null)
3621 <                return u;
3622 <        }
3623 <        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 <    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 u, r = null;
3927 <        while ((u = it.advanceKey()) != null) {
3640 <            r = (r == null) ? u : reducer.apply(r, u);
3641 <        }
3642 <        return r;
3925 >        return new ReduceKeysTask<K,V>
3926 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3927 >             null, reducer).invoke();
3928      }
3929  
3930      /**
# Line 3647 | 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 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 <    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 <        K k; U r = null, u;
3953 <        while ((k = it.advanceKey()) != null) {
3665 <            if ((u = transformer.apply(k)) != null)
3666 <                r = (r == null) ? u : reducer.apply(r, u);
3667 <        }
3668 <        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 3673 | 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 <    public double reduceKeysToDoubleSequentially
3972 <        (ToDoubleFunction<? 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 <        K k;
3692 <        while ((k = it.advanceKey()) != null)
3693 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(k));
3694 <        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 3699 | 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 <    public long reduceKeysToLongSequentially
3998 <        (ToLongFunction<? 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 <        K k;
3718 <        while ((k = it.advanceKey()) != null)
3719 <            r = reducer.applyAsLong(r, transformer.applyAsLong(k));
3720 <        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 3725 | 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 <    public int reduceKeysToIntSequentially
4024 <        (ToIntFunction<? 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 <        K k;
3744 <        while ((k = it.advanceKey()) != null)
3745 <            r = reducer.applyAsInt(r, transformer.applyAsInt(k));
3746 <        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(Consumer<? super V> action) {
4043 <        new Traverser<K,V,Object>(this).forEachValue(action);
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 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 <         Consumer<? 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.advanceValue()) != null) {
3775 <            if ((u = transformer.apply(v)) != null)
3776 <                action.accept(u);
3777 <        }
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.advanceValue()) != null) {
3795 <            if ((u = searchFunction.apply(v)) != null)
3796 <                return u;
3797 <        }
3798 <        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.advanceValue()) != null)
3814 <            r = (r == null) ? v : reducer.apply(r, v);
3815 <        return r;
4111 >        return new ReduceValuesTask<K,V>
4112 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4113 >             null, reducer).invoke();
4114      }
4115  
4116      /**
# Line 3820 | 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 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.advanceValue()) != null) {
3838 <            if ((u = transformer.apply(v)) != null)
3839 <                r = (r == null) ? u : reducer.apply(r, u);
3840 <        }
3841 <        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 3846 | 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 <        (ToDoubleFunction<? 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.advanceValue()) != null)
3865 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
3866 <        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 3871 | 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 <        (ToLongFunction<? 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.advanceValue()) != null)
3890 <            r = reducer.applyAsLong(r, transformer.applyAsLong(v));
3891 <        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 3896 | 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 <        (ToIntFunction<? 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.advanceValue()) != null)
3915 <            r = reducer.applyAsInt(r, transformer.applyAsInt(v));
3916 <        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 <    public void forEachEntrySequentially
4229 <        (Consumer<? 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;
3929 <        while ((v = it.advanceValue()) != null)
3930 <            action.accept(entryFor(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 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 <    public <U> void forEachEntrySequentially
4249 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4250 <         Consumer<? 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.advanceValue()) != null) {
3950 <            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3951 <                action.accept(u);
3952 <        }
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 <    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.advanceValue()) != null) {
3970 <            if ((u = searchFunction.apply(entryFor(it.nextKey, v))) != null)
3971 <                return u;
3972 <        }
3973 <        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 <    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.advanceValue()) != null) {
3989 <            Map.Entry<K,V> u = entryFor(it.nextKey, v);
3990 <            r = (r == null) ? u : reducer.apply(r, u);
3991 <        }
3992 <        return r;
4295 >        return new ReduceEntriesTask<K,V>
4296 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4297 >             null, reducer).invoke();
4298      }
4299  
4300      /**
# Line 3997 | 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 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 <    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.advanceValue()) != null) {
4015 <            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
4016 <                r = (r == null) ? u : reducer.apply(r, u);
4017 <        }
4018 <        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 4023 | 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 <    public double reduceEntriesToDoubleSequentially
4342 <        (ToDoubleFunction<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.advanceValue()) != null)
4042 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(it.nextKey, v)));
4043 <        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 4048 | 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 <    public long reduceEntriesToLongSequentially
4368 <        (ToLongFunction<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.advanceValue()) != null)
4067 <            r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(it.nextKey, v)));
4068 <        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 4073 | 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 <    public int reduceEntriesToIntSequentially
4394 <        (ToIntFunction<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.advanceValue()) != null)
4092 <            r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(it.nextKey, v)));
4093 <        return r;
4094 <    }
4095 <
4096 <    // Parallel bulk operations
4097 <
4098 <    /**
4099 <     * Performs the given action for each (key, value).
4100 <     *
4101 <     * @param action the action
4102 <     */
4103 <    public void forEachInParallel(BiConsumer<? super K,? super V> action) {
4104 <        ForkJoinTasks.forEach
4105 <            (this, action).invoke();
4106 <    }
4107 <
4108 <    /**
4109 <     * Performs the given action for each non-null transformation
4110 <     * of each (key, value).
4111 <     *
4112 <     * @param transformer a function returning the transformation
4113 <     * for an element, or null if there is no transformation (in
4114 <     * which case the action is not applied)
4115 <     * @param action the action
4116 <     */
4117 <    public <U> void forEachInParallel
4118 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
4119 <                            Consumer<? super U> action) {
4120 <        ForkJoinTasks.forEach
4121 <            (this, transformer, action).invoke();
4122 <    }
4123 <
4124 <    /**
4125 <     * Returns a non-null result from applying the given search
4126 <     * function on each (key, value), or null if none.  Upon
4127 <     * success, further element processing is suppressed and the
4128 <     * results of any other parallel invocations of the search
4129 <     * function are ignored.
4130 <     *
4131 <     * @param searchFunction a function returning a non-null
4132 <     * result on success, else null
4133 <     * @return a non-null result from applying the given search
4134 <     * function on each (key, value), or null if none
4135 <     */
4136 <    public <U> U searchInParallel
4137 <        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
4138 <        return ForkJoinTasks.search
4139 <            (this, searchFunction).invoke();
4140 <    }
4141 <
4142 <    /**
4143 <     * Returns the result of accumulating the given transformation
4144 <     * of all (key, value) pairs using the given reducer to
4145 <     * combine values, or null if none.
4146 <     *
4147 <     * @param transformer a function returning the transformation
4148 <     * for an element, or null if there is no transformation (in
4149 <     * which case it is not combined)
4150 <     * @param reducer a commutative associative combining function
4151 <     * @return the result of accumulating the given transformation
4152 <     * of all (key, value) pairs
4153 <     */
4154 <    public <U> U reduceInParallel
4155 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
4156 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4157 <        return ForkJoinTasks.reduce
4158 <            (this, transformer, reducer).invoke();
4159 <    }
4160 <
4161 <    /**
4162 <     * Returns the result of accumulating the given transformation
4163 <     * of all (key, value) pairs using the given reducer to
4164 <     * combine values, and the given basis as an identity value.
4165 <     *
4166 <     * @param transformer a function returning the transformation
4167 <     * for an element
4168 <     * @param basis the identity (initial default value) for the reduction
4169 <     * @param reducer a commutative associative combining function
4170 <     * @return the result of accumulating the given transformation
4171 <     * of all (key, value) pairs
4172 <     */
4173 <    public double reduceToDoubleInParallel
4174 <        (ToDoubleBiFunction<? super K, ? super V> transformer,
4175 <         double basis,
4176 <         DoubleBinaryOperator reducer) {
4177 <        return ForkJoinTasks.reduceToDouble
4178 <            (this, transformer, basis, reducer).invoke();
4179 <    }
4180 <
4181 <    /**
4182 <     * Returns the result of accumulating the given transformation
4183 <     * of all (key, value) pairs using the given reducer to
4184 <     * combine values, and the given basis as an identity value.
4185 <     *
4186 <     * @param transformer a function returning the transformation
4187 <     * for an element
4188 <     * @param basis the identity (initial default value) for the reduction
4189 <     * @param reducer a commutative associative combining function
4190 <     * @return the result of accumulating the given transformation
4191 <     * of all (key, value) pairs
4192 <     */
4193 <    public long reduceToLongInParallel
4194 <        (ToLongBiFunction<? super K, ? super V> transformer,
4195 <         long basis,
4196 <         LongBinaryOperator reducer) {
4197 <        return ForkJoinTasks.reduceToLong
4198 <            (this, transformer, basis, reducer).invoke();
4199 <    }
4200 <
4201 <    /**
4202 <     * Returns the result of accumulating the given transformation
4203 <     * of all (key, value) pairs using the given reducer to
4204 <     * combine values, and the given basis as an identity value.
4205 <     *
4206 <     * @param transformer a function returning the transformation
4207 <     * for an element
4208 <     * @param basis the identity (initial default value) for the reduction
4209 <     * @param reducer a commutative associative combining function
4210 <     * @return the result of accumulating the given transformation
4211 <     * of all (key, value) pairs
4212 <     */
4213 <    public int reduceToIntInParallel
4214 <        (ToIntBiFunction<? super K, ? super V> transformer,
4215 <         int basis,
4216 <         IntBinaryOperator reducer) {
4217 <        return ForkJoinTasks.reduceToInt
4218 <            (this, transformer, basis, reducer).invoke();
4219 <    }
4220 <
4221 <    /**
4222 <     * Performs the given action for each key.
4223 <     *
4224 <     * @param action the action
4225 <     */
4226 <    public void forEachKeyInParallel(Consumer<? super K> action) {
4227 <        ForkJoinTasks.forEachKey
4228 <            (this, action).invoke();
4229 <    }
4230 <
4231 <    /**
4232 <     * Performs the given action for each non-null transformation
4233 <     * of each key.
4234 <     *
4235 <     * @param transformer a function returning the transformation
4236 <     * for an element, or null if there is no transformation (in
4237 <     * which case the action is not applied)
4238 <     * @param action the action
4239 <     */
4240 <    public <U> void forEachKeyInParallel
4241 <        (Function<? super K, ? extends U> transformer,
4242 <         Consumer<? super U> action) {
4243 <        ForkJoinTasks.forEachKey
4244 <            (this, transformer, action).invoke();
4245 <    }
4246 <
4247 <    /**
4248 <     * Returns a non-null result from applying the given search
4249 <     * function on each key, or null if none. Upon success,
4250 <     * further element processing is suppressed and the results of
4251 <     * any other parallel invocations of the search function are
4252 <     * ignored.
4253 <     *
4254 <     * @param searchFunction a function returning a non-null
4255 <     * result on success, else null
4256 <     * @return a non-null result from applying the given search
4257 <     * function on each key, or null if none
4258 <     */
4259 <    public <U> U searchKeysInParallel
4260 <        (Function<? super K, ? extends U> searchFunction) {
4261 <        return ForkJoinTasks.searchKeys
4262 <            (this, searchFunction).invoke();
4263 <    }
4264 <
4265 <    /**
4266 <     * Returns the result of accumulating all keys using the given
4267 <     * reducer to combine values, or null if none.
4268 <     *
4269 <     * @param reducer a commutative associative combining function
4270 <     * @return the result of accumulating all keys using the given
4271 <     * reducer to combine values, or null if none
4272 <     */
4273 <    public K reduceKeysInParallel
4274 <        (BiFunction<? super K, ? super K, ? extends K> reducer) {
4275 <        return ForkJoinTasks.reduceKeys
4276 <            (this, reducer).invoke();
4277 <    }
4278 <
4279 <    /**
4280 <     * Returns the result of accumulating the given transformation
4281 <     * of all keys using the given reducer to combine values, or
4282 <     * null if none.
4283 <     *
4284 <     * @param transformer a function returning the transformation
4285 <     * for an element, or null if there is no transformation (in
4286 <     * which case it is not combined)
4287 <     * @param reducer a commutative associative combining function
4288 <     * @return the result of accumulating the given transformation
4289 <     * of all keys
4290 <     */
4291 <    public <U> U reduceKeysInParallel
4292 <        (Function<? super K, ? extends U> transformer,
4293 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4294 <        return ForkJoinTasks.reduceKeys
4295 <            (this, transformer, reducer).invoke();
4296 <    }
4297 <
4298 <    /**
4299 <     * Returns the result of accumulating the given transformation
4300 <     * of all keys using the given reducer to combine values, and
4301 <     * 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 keys
4309 <     */
4310 <    public double reduceKeysToDoubleInParallel
4311 <        (ToDoubleFunction<? super K> transformer,
4312 <         double basis,
4313 <         DoubleBinaryOperator reducer) {
4314 <        return ForkJoinTasks.reduceKeysToDouble
4315 <            (this, transformer, basis, reducer).invoke();
4316 <    }
4317 <
4318 <    /**
4319 <     * Returns the result of accumulating the given transformation
4320 <     * of all keys using the given reducer to combine values, and
4321 <     * the given basis as an identity value.
4322 <     *
4323 <     * @param transformer a function returning the transformation
4324 <     * for an element
4325 <     * @param basis the identity (initial default value) for the reduction
4326 <     * @param reducer a commutative associative combining function
4327 <     * @return the result of accumulating the given transformation
4328 <     * of all keys
4329 <     */
4330 <    public long reduceKeysToLongInParallel
4331 <        (ToLongFunction<? super K> transformer,
4332 <         long basis,
4333 <         LongBinaryOperator reducer) {
4334 <        return ForkJoinTasks.reduceKeysToLong
4335 <            (this, transformer, basis, reducer).invoke();
4336 <    }
4337 <
4338 <    /**
4339 <     * Returns the result of accumulating the given transformation
4340 <     * of all keys using the given reducer to combine values, and
4341 <     * the given basis as an identity value.
4342 <     *
4343 <     * @param transformer a function returning the transformation
4344 <     * for an element
4345 <     * @param basis the identity (initial default value) for the reduction
4346 <     * @param reducer a commutative associative combining function
4347 <     * @return the result of accumulating the given transformation
4348 <     * of all keys
4349 <     */
4350 <    public int reduceKeysToIntInParallel
4351 <        (ToIntFunction<? super K> transformer,
4352 <         int basis,
4353 <         IntBinaryOperator reducer) {
4354 <        return ForkJoinTasks.reduceKeysToInt
4355 <            (this, transformer, basis, reducer).invoke();
4356 <    }
4357 <
4358 <    /**
4359 <     * Performs the given action for each value.
4360 <     *
4361 <     * @param action the action
4362 <     */
4363 <    public void forEachValueInParallel(Consumer<? super V> action) {
4364 <        ForkJoinTasks.forEachValue
4365 <            (this, action).invoke();
4366 <    }
4367 <
4368 <    /**
4369 <     * Performs the given action for each non-null transformation
4370 <     * of each value.
4371 <     *
4372 <     * @param transformer a function returning the transformation
4373 <     * for an element, or null if there is no transformation (in
4374 <     * which case the action is not applied)
4375 <     * @param action the action
4376 <     */
4377 <    public <U> void forEachValueInParallel
4378 <        (Function<? super V, ? extends U> transformer,
4379 <         Consumer<? super U> action) {
4380 <        ForkJoinTasks.forEachValue
4381 <            (this, transformer, action).invoke();
4382 <    }
4383 <
4384 <    /**
4385 <     * Returns a non-null result from applying the given search
4386 <     * function on each value, or null if none.  Upon success,
4387 <     * further element processing is suppressed and the results of
4388 <     * any other parallel invocations of the search function are
4389 <     * ignored.
4390 <     *
4391 <     * @param searchFunction a function returning a non-null
4392 <     * result on success, else null
4393 <     * @return a non-null result from applying the given search
4394 <     * function on each value, or null if none
4395 <     */
4396 <    public <U> U searchValuesInParallel
4397 <        (Function<? super V, ? extends U> searchFunction) {
4398 <        return ForkJoinTasks.searchValues
4399 <            (this, searchFunction).invoke();
4400 <    }
4401 <
4402 <    /**
4403 <     * Returns the result of accumulating all values using the
4404 <     * given reducer to combine values, or null if none.
4405 <     *
4406 <     * @param reducer a commutative associative combining function
4407 <     * @return the result of accumulating all values
4408 <     */
4409 <    public V reduceValuesInParallel
4410 <        (BiFunction<? super V, ? super V, ? extends V> reducer) {
4411 <        return ForkJoinTasks.reduceValues
4412 <            (this, reducer).invoke();
4413 <    }
4414 <
4415 <    /**
4416 <     * Returns the result of accumulating the given transformation
4417 <     * of all values using the given reducer to combine values, or
4418 <     * null if none.
4419 <     *
4420 <     * @param transformer a function returning the transformation
4421 <     * for an element, or null if there is no transformation (in
4422 <     * which case it is not combined)
4423 <     * @param reducer a commutative associative combining function
4424 <     * @return the result of accumulating the given transformation
4425 <     * of all values
4426 <     */
4427 <    public <U> U reduceValuesInParallel
4428 <        (Function<? super V, ? extends U> transformer,
4429 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4430 <        return ForkJoinTasks.reduceValues
4431 <            (this, transformer, reducer).invoke();
4432 <    }
4433 <
4434 <    /**
4435 <     * Returns the result of accumulating the given transformation
4436 <     * of all values 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 values
4445 <     */
4446 <    public double reduceValuesToDoubleInParallel
4447 <        (ToDoubleFunction<? super V> transformer,
4448 <         double basis,
4449 <         DoubleBinaryOperator reducer) {
4450 <        return ForkJoinTasks.reduceValuesToDouble
4451 <            (this, transformer, basis, reducer).invoke();
4452 <    }
4453 <
4454 <    /**
4455 <     * Returns the result of accumulating the given transformation
4456 <     * of all values using the given reducer to combine values,
4457 <     * and the given basis as an identity value.
4458 <     *
4459 <     * @param transformer a function returning the transformation
4460 <     * for an element
4461 <     * @param basis the identity (initial default value) for the reduction
4462 <     * @param reducer a commutative associative combining function
4463 <     * @return the result of accumulating the given transformation
4464 <     * of all values
4465 <     */
4466 <    public long reduceValuesToLongInParallel
4467 <        (ToLongFunction<? super V> transformer,
4468 <         long basis,
4469 <         LongBinaryOperator reducer) {
4470 <        return ForkJoinTasks.reduceValuesToLong
4471 <            (this, transformer, basis, reducer).invoke();
4472 <    }
4473 <
4474 <    /**
4475 <     * Returns the result of accumulating the given transformation
4476 <     * of all values using the given reducer to combine values,
4477 <     * and the given basis as an identity value.
4478 <     *
4479 <     * @param transformer a function returning the transformation
4480 <     * for an element
4481 <     * @param basis the identity (initial default value) for the reduction
4482 <     * @param reducer a commutative associative combining function
4483 <     * @return the result of accumulating the given transformation
4484 <     * of all values
4485 <     */
4486 <    public int reduceValuesToIntInParallel
4487 <        (ToIntFunction<? super V> transformer,
4488 <         int basis,
4489 <         IntBinaryOperator reducer) {
4490 <        return ForkJoinTasks.reduceValuesToInt
4491 <            (this, transformer, basis, reducer).invoke();
4492 <    }
4493 <
4494 <    /**
4495 <     * Performs the given action for each entry.
4496 <     *
4497 <     * @param action the action
4498 <     */
4499 <    public void forEachEntryInParallel(Consumer<? super Map.Entry<K,V>> action) {
4500 <        ForkJoinTasks.forEachEntry
4501 <            (this, action).invoke();
4502 <    }
4503 <
4504 <    /**
4505 <     * Performs the given action for each non-null transformation
4506 <     * of each entry.
4507 <     *
4508 <     * @param transformer a function returning the transformation
4509 <     * for an element, or null if there is no transformation (in
4510 <     * which case the action is not applied)
4511 <     * @param action the action
4512 <     */
4513 <    public <U> void forEachEntryInParallel
4514 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4515 <         Consumer<? super U> action) {
4516 <        ForkJoinTasks.forEachEntry
4517 <            (this, transformer, action).invoke();
4518 <    }
4519 <
4520 <    /**
4521 <     * Returns a non-null result from applying the given search
4522 <     * function on each entry, or null if none.  Upon success,
4523 <     * further element processing is suppressed and the results of
4524 <     * any other parallel invocations of the search function are
4525 <     * ignored.
4526 <     *
4527 <     * @param searchFunction a function returning a non-null
4528 <     * result on success, else null
4529 <     * @return a non-null result from applying the given search
4530 <     * function on each entry, or null if none
4531 <     */
4532 <    public <U> U searchEntriesInParallel
4533 <        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4534 <        return ForkJoinTasks.searchEntries
4535 <            (this, searchFunction).invoke();
4536 <    }
4537 <
4538 <    /**
4539 <     * Returns the result of accumulating all entries using the
4540 <     * given reducer to combine values, or null if none.
4541 <     *
4542 <     * @param reducer a commutative associative combining function
4543 <     * @return the result of accumulating all entries
4544 <     */
4545 <    public Map.Entry<K,V> reduceEntriesInParallel
4546 <        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4547 <        return ForkJoinTasks.reduceEntries
4548 <            (this, reducer).invoke();
4549 <    }
4550 <
4551 <    /**
4552 <     * Returns the result of accumulating the given transformation
4553 <     * of all entries using the given reducer to combine values,
4554 <     * or null if none.
4555 <     *
4556 <     * @param transformer a function returning the transformation
4557 <     * for an element, or null if there is no transformation (in
4558 <     * which case it is not combined)
4559 <     * @param reducer a commutative associative combining function
4560 <     * @return the result of accumulating the given transformation
4561 <     * of all entries
4562 <     */
4563 <    public <U> U reduceEntriesInParallel
4564 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4565 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4566 <        return ForkJoinTasks.reduceEntries
4567 <            (this, transformer, reducer).invoke();
4568 <    }
4569 <
4570 <    /**
4571 <     * Returns the result of accumulating the given transformation
4572 <     * of all entries using the given reducer to combine values,
4573 <     * and the given basis as an identity value.
4574 <     *
4575 <     * @param transformer a function returning the transformation
4576 <     * for an element
4577 <     * @param basis the identity (initial default value) for the reduction
4578 <     * @param reducer a commutative associative combining function
4579 <     * @return the result of accumulating the given transformation
4580 <     * of all entries
4581 <     */
4582 <    public double reduceEntriesToDoubleInParallel
4583 <        (ToDoubleFunction<Map.Entry<K,V>> transformer,
4584 <         double basis,
4585 <         DoubleBinaryOperator reducer) {
4586 <        return ForkJoinTasks.reduceEntriesToDouble
4587 <            (this, transformer, basis, reducer).invoke();
4588 <    }
4589 <
4590 <    /**
4591 <     * Returns the result of accumulating the given transformation
4592 <     * of all entries using the given reducer to combine values,
4593 <     * and the given basis as an identity value.
4594 <     *
4595 <     * @param transformer a function returning the transformation
4596 <     * for an element
4597 <     * @param basis the identity (initial default value) for the reduction
4598 <     * @param reducer a commutative associative combining function
4599 <     * @return the result of accumulating the given transformation
4600 <     * of all entries
4601 <     */
4602 <    public long reduceEntriesToLongInParallel
4603 <        (ToLongFunction<Map.Entry<K,V>> transformer,
4604 <         long basis,
4605 <         LongBinaryOperator reducer) {
4606 <        return ForkJoinTasks.reduceEntriesToLong
4607 <            (this, transformer, basis, reducer).invoke();
4608 <    }
4609 <
4610 <    /**
4611 <     * Returns the result of accumulating the given transformation
4612 <     * of all entries using the given reducer to combine values,
4613 <     * and the given basis as an identity value.
4614 <     *
4615 <     * @param transformer a function returning the transformation
4616 <     * for an element
4617 <     * @param basis the identity (initial default value) for the reduction
4618 <     * @param reducer a commutative associative combining function
4619 <     * @return the result of accumulating the given transformation
4620 <     * of all entries
4621 <     */
4622 <    public int reduceEntriesToIntInParallel
4623 <        (ToIntFunction<Map.Entry<K,V>> transformer,
4624 <         int basis,
4625 <         IntBinaryOperator reducer) {
4626 <        return ForkJoinTasks.reduceEntriesToInt
4627 <            (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 4633 | Line 4407 | public class ConcurrentHashMap<K,V>
4407      /**
4408       * Base class for views.
4409       */
4410 <    abstract static class CHMCollectionView<K,V,E>
4411 <            implements Collection<E>, 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 <        CHMCollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4414 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4415  
4416          /**
4417           * Returns the map backing this view.
# Line 4657 | Line 4431 | public class ConcurrentHashMap<K,V>
4431          // implementations below rely on concrete classes supplying these
4432          // abstract methods
4433          /**
4434 <         * Returns a "weakly consistent" iterator that will never
4435 <         * throw {@link ConcurrentModificationException}, and
4436 <         * guarantees to traverse elements as they existed upon
4437 <         * construction of the iterator, and may (but is not
4438 <         * guaranteed to) reflect any modifications subsequent to
4439 <         * construction.
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 > MAX_ARRAY_SIZE)
4450 <                throw new OutOfMemoryError(oomeMsg);
4450 >                throw new OutOfMemoryError(OOME_MSG);
4451              int n = (int)sz;
4452              Object[] r = new Object[n];
4453              int i = 0;
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
# Line 4696 | Line 4470 | public class ConcurrentHashMap<K,V>
4470          public final <T> T[] toArray(T[] a) {
4471              long sz = map.mappingCount();
4472              if (sz > MAX_ARRAY_SIZE)
4473 <                throw new OutOfMemoryError(oomeMsg);
4473 >                throw new OutOfMemoryError(OOME_MSG);
4474              int m = (int)sz;
4475              T[] r = (a.length >= m) ? a :
4476                  (T[])java.lang.reflect.Array
# Line 4706 | Line 4480 | public class ConcurrentHashMap<K,V>
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
# Line 4759 | 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<E> 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<E> it = iterator(); it.hasNext();) {
4562                  if (!c.contains(it.next())) {
# Line 4783 | Line 4569 | public class ConcurrentHashMap<K,V>
4569  
4570      }
4571  
4786    abstract static class CHMSetView<K,V,E>
4787            extends CHMCollectionView<K,V,E>
4788            implements Set<E>, java.io.Serializable {
4789        private static final long serialVersionUID = 7249069246763182397L;
4790        CHMSetView(ConcurrentHashMap<K,V> map) { super(map); }
4791
4792        // Implement Set API
4793
4794        /**
4795         * Implements {@link Set#hashCode()}.
4796         * @return the hash code value for this set
4797         */
4798        public final int hashCode() {
4799            int h = 0;
4800            for (E e : this)
4801                h += e.hashCode();
4802            return h;
4803        }
4804
4805        /**
4806         * Implements {@link Set#equals(Object)}.
4807         * @param o object to be compared for equality with this set
4808         * @return {@code true} if the specified object is equal to this set
4809        */
4810        public final boolean equals(Object o) {
4811            Set<?> c;
4812            return ((o instanceof Set) &&
4813                    ((c = (Set<?>)o) == this ||
4814                     (containsAll(c) && c.containsAll(this))));
4815        }
4816    }
4817
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
# Line 4823 | Line 4577 | public class ConcurrentHashMap<K,V>
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>
4584 <            extends CHMSetView<K,V,K>
4829 <            implements Set<K>, java.io.Serializable {
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
# Line 4863 | Line 4618 | public class ConcurrentHashMap<K,V>
4618          /**
4619           * @return an iterator over the keys of the backing map
4620           */
4621 <        public Iterator<K> iterator() { return new KeyIterator<K,V>(map); }
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
# Line 4879 | Line 4639 | public class ConcurrentHashMap<K,V>
4639              V v;
4640              if ((v = value) == null)
4641                  throw new UnsupportedOperationException();
4642 <            return map.internalPut(e, v, true) == null;
4642 >            return map.putVal(e, v, true) == null;
4643          }
4644  
4645          /**
# Line 4899 | Line 4659 | public class ConcurrentHashMap<K,V>
4659              if ((v = value) == null)
4660                  throw new UnsupportedOperationException();
4661              for (K e : c) {
4662 <                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) &&
4678 +                    ((c = (Set<?>)o) == this ||
4679 +                     (containsAll(c) && c.containsAll(this))));
4680 +        }
4681 +
4682          public Spliterator<K> spliterator() {
4683 <            return new KeyIterator<>(map, null);
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  
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},
4921 <     * and guarantees to traverse elements as they existed upon
4922 <     * construction of the iterator, and may (but is not guaranteed to)
4923 <     * reflect any modifications subsequent to construction.
4924 <     */
4925 <    public static final class ValuesView<K,V>
4926 <            extends CHMCollectionView<K,V,V>
4927 <            implements Collection<V>, java.io.Serializable {
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                  for (Iterator<V> it = iterator(); it.hasNext();) {
# Line 4942 | Line 4723 | public class ConcurrentHashMap<K,V>
4723              return false;
4724          }
4725  
4945        /**
4946         * @return an iterator over the values of the backing map
4947         */
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  
4952        /** Always throws {@link UnsupportedOperationException}. */
4733          public final boolean add(V e) {
4734              throw new UnsupportedOperationException();
4735          }
4956        /** Always throws {@link UnsupportedOperationException}. */
4736          public final boolean addAll(Collection<? extends V> c) {
4737              throw new UnsupportedOperationException();
4738          }
4739  
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 Spliterator<V> spliterator() {
4757 <            return new ValueIterator<K,V>(map, null);
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      /**
# Line 4969 | Line 4777 | public class ConcurrentHashMap<K,V>
4777       * entries.  This class cannot be directly instantiated. See
4778       * {@link #entrySet()}.
4779       */
4780 <    public static final class EntrySetView<K,V>
4781 <            extends CHMSetView<K,V,Map.Entry<K,V>>
4974 <            implements Set<Map.Entry<K,V>>, java.io.Serializable {
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 final boolean contains(Object o) {
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 4983 | 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 4994 | Line 4802 | public class ConcurrentHashMap<K,V>
4802          /**
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 <        /**
4813 <         * Adds the specified mapping to this view.
5003 <         *
5004 <         * @param e mapping to be added
5005 <         * @return {@code true} if this set changed as a result of the call
5006 <         * @throws NullPointerException if the entry, its key, or its
5007 <         * value is null
5008 <         */
5009 <        public final boolean add(Entry<K,V> e) {
5010 <            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4812 >        public boolean add(Entry<K,V> e) {
4813 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4814          }
4815  
4816 <        /**
5014 <         * Adds all of the mappings in the specified collection to this
5015 <         * set, as if by calling {@link #add(Map.Entry)} on each one.
5016 <         * @param c the mappings to be inserted into this set
5017 <         * @return {@code true} if this set changed as a result of the call
5018 <         * @throws NullPointerException if the collection or any of its
5019 <         * entries, keys, or values are null
5020 <         */
5021 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
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 5027 | Line 4822 | public class ConcurrentHashMap<K,V>
4822              return added;
4823          }
4824  
4825 <        public Spliterator<Map.Entry<K,V>> spliterator() {
4826 <            return new EntryIterator<K,V>(map, null);
5032 <        }
5033 <
5034 <    }
5035 <
5036 <    // ---------------------------------------------------------------------
5037 <
5038 <    /**
5039 <     * Predefined tasks for performing bulk parallel operations on
5040 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
5041 <     * for bulk operations. Each method has the same name, but returns
5042 <     * a task rather than invoking it. These methods may be useful in
5043 <     * custom applications such as submitting a task without waiting
5044 <     * for completion, using a custom pool, or combining with other
5045 <     * tasks.
5046 <     */
5047 <    public static class ForkJoinTasks {
5048 <        private ForkJoinTasks() {}
5049 <
5050 <        /**
5051 <         * Returns a task that when invoked, performs the given
5052 <         * action for each (key, value)
5053 <         *
5054 <         * @param map the map
5055 <         * @param action the action
5056 <         * @return the task
5057 <         */
5058 <        public static <K,V> ForkJoinTask<Void> forEach
5059 <            (ConcurrentHashMap<K,V> map,
5060 <             BiConsumer<? super K, ? super V> action) {
5061 <            if (action == null) throw new NullPointerException();
5062 <            return new ForEachMappingTask<K,V>(map, null, -1, action);
5063 <        }
5064 <
5065 <        /**
5066 <         * Returns a task that when invoked, performs the given
5067 <         * action for each non-null transformation of each (key, value)
5068 <         *
5069 <         * @param map the map
5070 <         * @param transformer a function returning the transformation
5071 <         * for an element, or null if there is no transformation (in
5072 <         * which case the action is not applied)
5073 <         * @param action the action
5074 <         * @return the task
5075 <         */
5076 <        public static <K,V,U> ForkJoinTask<Void> forEach
5077 <            (ConcurrentHashMap<K,V> map,
5078 <             BiFunction<? super K, ? super V, ? extends U> transformer,
5079 <             Consumer<? super U> action) {
5080 <            if (transformer == null || action == null)
5081 <                throw new NullPointerException();
5082 <            return new ForEachTransformedMappingTask<K,V,U>
5083 <                (map, null, -1, transformer, action);
5084 <        }
5085 <
5086 <        /**
5087 <         * Returns a task that when invoked, returns a non-null result
5088 <         * from applying the given search function on each (key,
5089 <         * value), or null if none. Upon success, further element
5090 <         * processing is suppressed and the results of any other
5091 <         * parallel invocations of the search function are ignored.
5092 <         *
5093 <         * @param map the map
5094 <         * @param searchFunction a function returning a non-null
5095 <         * result on success, else null
5096 <         * @return the task
5097 <         */
5098 <        public static <K,V,U> ForkJoinTask<U> search
5099 <            (ConcurrentHashMap<K,V> map,
5100 <             BiFunction<? super K, ? super V, ? extends U> searchFunction) {
5101 <            if (searchFunction == null) throw new NullPointerException();
5102 <            return new SearchMappingsTask<K,V,U>
5103 <                (map, null, -1, searchFunction,
5104 <                 new AtomicReference<U>());
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, returns the result of
4831 <         * accumulating the given transformation of all (key, value) pairs
4832 <         * using the given reducer to combine values, or null if none.
4833 <         *
4834 <         * @param map the map
4835 <         * @param transformer a function returning the transformation
4836 <         * for an element, or null if there is no transformation (in
4837 <         * which case it is not combined)
4838 <         * @param reducer a commutative associative combining function
5117 <         * @return the task
5118 <         */
5119 <        public static <K,V,U> ForkJoinTask<U> reduce
5120 <            (ConcurrentHashMap<K,V> map,
5121 <             BiFunction<? super K, ? super V, ? extends U> transformer,
5122 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5123 <            if (transformer == null || reducer == null)
5124 <                throw new NullPointerException();
5125 <            return new MapReduceMappingsTask<K,V,U>
5126 <                (map, null, -1, null, transformer, reducer);
5127 <        }
5128 <
5129 <        /**
5130 <         * Returns a task that when invoked, returns the result of
5131 <         * accumulating the given transformation of all (key, value) pairs
5132 <         * using the given reducer to combine values, and the given
5133 <         * basis as an identity value.
5134 <         *
5135 <         * @param map the map
5136 <         * @param transformer a function returning the transformation
5137 <         * for an element
5138 <         * @param basis the identity (initial default value) for the reduction
5139 <         * @param reducer a commutative associative combining function
5140 <         * @return the task
5141 <         */
5142 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
5143 <            (ConcurrentHashMap<K,V> map,
5144 <             ToDoubleBiFunction<? super K, ? super V> transformer,
5145 <             double basis,
5146 <             DoubleBinaryOperator reducer) {
5147 <            if (transformer == null || reducer == null)
5148 <                throw new NullPointerException();
5149 <            return new MapReduceMappingsToDoubleTask<K,V>
5150 <                (map, null, -1, null, transformer, basis, reducer);
5151 <        }
5152 <
5153 <        /**
5154 <         * Returns a task that when invoked, returns the result of
5155 <         * accumulating the given transformation of all (key, value) pairs
5156 <         * using the given reducer to combine values, and the given
5157 <         * basis as an identity value.
5158 <         *
5159 <         * @param map the map
5160 <         * @param transformer a function returning the transformation
5161 <         * for an element
5162 <         * @param basis the identity (initial default value) for the reduction
5163 <         * @param reducer a commutative associative combining function
5164 <         * @return the task
5165 <         */
5166 <        public static <K,V> ForkJoinTask<Long> reduceToLong
5167 <            (ConcurrentHashMap<K,V> map,
5168 <             ToLongBiFunction<? super K, ? super V> transformer,
5169 <             long basis,
5170 <             LongBinaryOperator reducer) {
5171 <            if (transformer == null || reducer == null)
5172 <                throw new NullPointerException();
5173 <            return new MapReduceMappingsToLongTask<K,V>
5174 <                (map, null, -1, null, transformer, basis, reducer);
5175 <        }
5176 <
5177 <        /**
5178 <         * Returns a task that when invoked, returns the result of
5179 <         * accumulating the given transformation of all (key, value) pairs
5180 <         * using the given reducer to combine values, and the given
5181 <         * basis as an identity value.
5182 <         *
5183 <         * @param map the map
5184 <         * @param transformer a function returning the transformation
5185 <         * for an element
5186 <         * @param basis the identity (initial default value) for the reduction
5187 <         * @param reducer a commutative associative combining function
5188 <         * @return the task
5189 <         */
5190 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
5191 <            (ConcurrentHashMap<K,V> map,
5192 <             ToIntBiFunction<? super K, ? super V> transformer,
5193 <             int basis,
5194 <             IntBinaryOperator reducer) {
5195 <            if (transformer == null || reducer == null)
5196 <                throw new NullPointerException();
5197 <            return new MapReduceMappingsToIntTask<K,V>
5198 <                (map, null, -1, null, transformer, basis, reducer);
5199 <        }
5200 <
5201 <        /**
5202 <         * Returns a task that when invoked, performs the given action
5203 <         * for each key.
5204 <         *
5205 <         * @param map the map
5206 <         * @param action the action
5207 <         * @return the task
5208 <         */
5209 <        public static <K,V> ForkJoinTask<Void> forEachKey
5210 <            (ConcurrentHashMap<K,V> map,
5211 <             Consumer<? super K> action) {
5212 <            if (action == null) throw new NullPointerException();
5213 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
5214 <        }
5215 <
5216 <        /**
5217 <         * Returns a task that when invoked, performs the given action
5218 <         * for each non-null transformation of each key.
5219 <         *
5220 <         * @param map the map
5221 <         * @param transformer a function returning the transformation
5222 <         * for an element, or null if there is no transformation (in
5223 <         * which case the action is not applied)
5224 <         * @param action the action
5225 <         * @return the task
5226 <         */
5227 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
5228 <            (ConcurrentHashMap<K,V> map,
5229 <             Function<? super K, ? extends U> transformer,
5230 <             Consumer<? super U> action) {
5231 <            if (transformer == null || action == null)
5232 <                throw new NullPointerException();
5233 <            return new ForEachTransformedKeyTask<K,V,U>
5234 <                (map, null, -1, transformer, action);
5235 <        }
5236 <
5237 <        /**
5238 <         * Returns a task that when invoked, returns a non-null result
5239 <         * from applying the given search function on each key, or
5240 <         * null if none.  Upon success, further element processing is
5241 <         * suppressed and the results of any other parallel
5242 <         * invocations of the search function are ignored.
5243 <         *
5244 <         * @param map the map
5245 <         * @param searchFunction a function returning a non-null
5246 <         * result on success, else null
5247 <         * @return the task
5248 <         */
5249 <        public static <K,V,U> ForkJoinTask<U> searchKeys
5250 <            (ConcurrentHashMap<K,V> map,
5251 <             Function<? super K, ? extends U> searchFunction) {
5252 <            if (searchFunction == null) throw new NullPointerException();
5253 <            return new SearchKeysTask<K,V,U>
5254 <                (map, null, -1, searchFunction,
5255 <                 new AtomicReference<U>());
5256 <        }
5257 <
5258 <        /**
5259 <         * Returns a task that when invoked, returns the result of
5260 <         * accumulating all keys using the given reducer to combine
5261 <         * values, or null if none.
5262 <         *
5263 <         * @param map the map
5264 <         * @param reducer a commutative associative combining function
5265 <         * @return the task
5266 <         */
5267 <        public static <K,V> ForkJoinTask<K> reduceKeys
5268 <            (ConcurrentHashMap<K,V> map,
5269 <             BiFunction<? super K, ? super K, ? extends K> reducer) {
5270 <            if (reducer == null) throw new NullPointerException();
5271 <            return new ReduceKeysTask<K,V>
5272 <                (map, null, -1, null, reducer);
5273 <        }
5274 <
5275 <        /**
5276 <         * Returns a task that when invoked, returns the result of
5277 <         * accumulating the given transformation of all keys using the given
5278 <         * reducer to combine values, or null if none.
5279 <         *
5280 <         * @param map the map
5281 <         * @param transformer a function returning the transformation
5282 <         * for an element, or null if there is no transformation (in
5283 <         * which case it is not combined)
5284 <         * @param reducer a commutative associative combining function
5285 <         * @return the task
5286 <         */
5287 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
5288 <            (ConcurrentHashMap<K,V> map,
5289 <             Function<? super K, ? extends U> transformer,
5290 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5291 <            if (transformer == null || reducer == null)
5292 <                throw new NullPointerException();
5293 <            return new MapReduceKeysTask<K,V,U>
5294 <                (map, null, -1, null, transformer, reducer);
5295 <        }
5296 <
5297 <        /**
5298 <         * Returns a task that when invoked, returns the result of
5299 <         * accumulating the given transformation of all keys using the given
5300 <         * reducer to combine values, and the given basis as an
5301 <         * identity value.
5302 <         *
5303 <         * @param map the map
5304 <         * @param transformer a function returning the transformation
5305 <         * for an element
5306 <         * @param basis the identity (initial default value) for the reduction
5307 <         * @param reducer a commutative associative combining function
5308 <         * @return the task
5309 <         */
5310 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5311 <            (ConcurrentHashMap<K,V> map,
5312 <             ToDoubleFunction<? super K> transformer,
5313 <             double basis,
5314 <             DoubleBinaryOperator reducer) {
5315 <            if (transformer == null || reducer == null)
5316 <                throw new NullPointerException();
5317 <            return new MapReduceKeysToDoubleTask<K,V>
5318 <                (map, null, -1, null, transformer, basis, reducer);
5319 <        }
5320 <
5321 <        /**
5322 <         * Returns a task that when invoked, returns the result of
5323 <         * accumulating the given transformation of all keys using the given
5324 <         * reducer to combine values, and the given basis as an
5325 <         * identity value.
5326 <         *
5327 <         * @param map the map
5328 <         * @param transformer a function returning the transformation
5329 <         * for an element
5330 <         * @param basis the identity (initial default value) for the reduction
5331 <         * @param reducer a commutative associative combining function
5332 <         * @return the task
5333 <         */
5334 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5335 <            (ConcurrentHashMap<K,V> map,
5336 <             ToLongFunction<? super K> transformer,
5337 <             long basis,
5338 <             LongBinaryOperator reducer) {
5339 <            if (transformer == null || reducer == null)
5340 <                throw new NullPointerException();
5341 <            return new MapReduceKeysToLongTask<K,V>
5342 <                (map, null, -1, null, transformer, basis, reducer);
5343 <        }
5344 <
5345 <        /**
5346 <         * Returns a task that when invoked, returns the result of
5347 <         * accumulating the given transformation of all keys using the given
5348 <         * reducer to combine values, and the given basis as an
5349 <         * identity value.
5350 <         *
5351 <         * @param map the map
5352 <         * @param transformer a function returning the transformation
5353 <         * for an element
5354 <         * @param basis the identity (initial default value) for the reduction
5355 <         * @param reducer a commutative associative combining function
5356 <         * @return the task
5357 <         */
5358 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5359 <            (ConcurrentHashMap<K,V> map,
5360 <             ToIntFunction<? super K> transformer,
5361 <             int basis,
5362 <             IntBinaryOperator reducer) {
5363 <            if (transformer == null || reducer == null)
5364 <                throw new NullPointerException();
5365 <            return new MapReduceKeysToIntTask<K,V>
5366 <                (map, null, -1, null, transformer, basis, reducer);
5367 <        }
5368 <
5369 <        /**
5370 <         * Returns a task that when invoked, performs the given action
5371 <         * for each value.
5372 <         *
5373 <         * @param map the map
5374 <         * @param action the action
5375 <         * @return the task
5376 <         */
5377 <        public static <K,V> ForkJoinTask<Void> forEachValue
5378 <            (ConcurrentHashMap<K,V> map,
5379 <             Consumer<? super V> action) {
5380 <            if (action == null) throw new NullPointerException();
5381 <            return new ForEachValueTask<K,V>(map, null, -1, action);
5382 <        }
5383 <
5384 <        /**
5385 <         * Returns a task that when invoked, performs the given action
5386 <         * for each non-null transformation of each value.
5387 <         *
5388 <         * @param map the map
5389 <         * @param transformer a function returning the transformation
5390 <         * for an element, or null if there is no transformation (in
5391 <         * which case the action is not applied)
5392 <         * @param action the action
5393 <         * @return the task
5394 <         */
5395 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
5396 <            (ConcurrentHashMap<K,V> map,
5397 <             Function<? super V, ? extends U> transformer,
5398 <             Consumer<? super U> action) {
5399 <            if (transformer == null || action == null)
5400 <                throw new NullPointerException();
5401 <            return new ForEachTransformedValueTask<K,V,U>
5402 <                (map, null, -1, transformer, action);
5403 <        }
5404 <
5405 <        /**
5406 <         * Returns a task that when invoked, returns a non-null result
5407 <         * from applying the given search function on each value, or
5408 <         * null if none.  Upon success, further element processing is
5409 <         * suppressed and the results of any other parallel
5410 <         * invocations of the search function are ignored.
5411 <         *
5412 <         * @param map the map
5413 <         * @param searchFunction a function returning a non-null
5414 <         * result on success, else null
5415 <         * @return the task
5416 <         */
5417 <        public static <K,V,U> ForkJoinTask<U> searchValues
5418 <            (ConcurrentHashMap<K,V> map,
5419 <             Function<? super V, ? extends U> searchFunction) {
5420 <            if (searchFunction == null) throw new NullPointerException();
5421 <            return new SearchValuesTask<K,V,U>
5422 <                (map, null, -1, searchFunction,
5423 <                 new AtomicReference<U>());
5424 <        }
5425 <
5426 <        /**
5427 <         * Returns a task that when invoked, returns the result of
5428 <         * accumulating all values using the given reducer to combine
5429 <         * values, or null if none.
5430 <         *
5431 <         * @param map the map
5432 <         * @param reducer a commutative associative combining function
5433 <         * @return the task
5434 <         */
5435 <        public static <K,V> ForkJoinTask<V> reduceValues
5436 <            (ConcurrentHashMap<K,V> map,
5437 <             BiFunction<? super V, ? super V, ? extends V> reducer) {
5438 <            if (reducer == null) throw new NullPointerException();
5439 <            return new ReduceValuesTask<K,V>
5440 <                (map, null, -1, null, reducer);
5441 <        }
5442 <
5443 <        /**
5444 <         * Returns a task that when invoked, returns the result of
5445 <         * accumulating the given transformation of all values using the
5446 <         * given reducer to combine values, or null if none.
5447 <         *
5448 <         * @param map the map
5449 <         * @param transformer a function returning the transformation
5450 <         * for an element, or null if there is no transformation (in
5451 <         * which case it is not combined)
5452 <         * @param reducer a commutative associative combining function
5453 <         * @return the task
5454 <         */
5455 <        public static <K,V,U> ForkJoinTask<U> reduceValues
5456 <            (ConcurrentHashMap<K,V> map,
5457 <             Function<? super V, ? extends U> transformer,
5458 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5459 <            if (transformer == null || reducer == null)
5460 <                throw new NullPointerException();
5461 <            return new MapReduceValuesTask<K,V,U>
5462 <                (map, null, -1, null, transformer, reducer);
5463 <        }
5464 <
5465 <        /**
5466 <         * Returns a task that when invoked, returns the result of
5467 <         * accumulating the given transformation of all values using the
5468 <         * given reducer to combine values, and the given basis as an
5469 <         * identity value.
5470 <         *
5471 <         * @param map the map
5472 <         * @param transformer a function returning the transformation
5473 <         * for an element
5474 <         * @param basis the identity (initial default value) for the reduction
5475 <         * @param reducer a commutative associative combining function
5476 <         * @return the task
5477 <         */
5478 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5479 <            (ConcurrentHashMap<K,V> map,
5480 <             ToDoubleFunction<? super V> transformer,
5481 <             double basis,
5482 <             DoubleBinaryOperator reducer) {
5483 <            if (transformer == null || reducer == null)
5484 <                throw new NullPointerException();
5485 <            return new MapReduceValuesToDoubleTask<K,V>
5486 <                (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.
5494 <         *
5495 <         * @param map the map
5496 <         * @param transformer a function returning the transformation
5497 <         * for an element
5498 <         * @param basis the identity (initial default value) for the reduction
5499 <         * @param reducer a commutative associative combining function
5500 <         * @return the task
5501 <         */
5502 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5503 <            (ConcurrentHashMap<K,V> map,
5504 <             ToLongFunction<? super V> transformer,
5505 <             long basis,
5506 <             LongBinaryOperator reducer) {
5507 <            if (transformer == null || reducer == null)
5508 <                throw new NullPointerException();
5509 <            return new MapReduceValuesToLongTask<K,V>
5510 <                (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 <         *
5519 <         * @param map the map
5520 <         * @param transformer a function returning the transformation
5521 <         * for an element
5522 <         * @param basis the identity (initial default value) for the reduction
5523 <         * @param reducer a commutative associative combining function
5524 <         * @return the task
5525 <         */
5526 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5527 <            (ConcurrentHashMap<K,V> map,
5528 <             ToIntFunction<? super V> transformer,
5529 <             int basis,
5530 <             IntBinaryOperator reducer) {
5531 <            if (transformer == null || reducer == null)
5532 <                throw new NullPointerException();
5533 <            return new MapReduceValuesToIntTask<K,V>
5534 <                (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 <        /**
5538 <         * Returns a task that when invoked, perform the given action
5539 <         * for each entry.
5540 <         *
5541 <         * @param map the map
5542 <         * @param action the action
5543 <         * @return the task
5544 <         */
5545 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5546 <            (ConcurrentHashMap<K,V> map,
5547 <             Consumer<? 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.
5555 <         *
5556 <         * @param map the map
5557 <         * @param transformer a function returning the transformation
5558 <         * for an element, or null if there is no transformation (in
5559 <         * which case the action is not applied)
5560 <         * @param action the action
5561 <         * @return the task
5562 <         */
5563 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5564 <            (ConcurrentHashMap<K,V> map,
5565 <             Function<Map.Entry<K,V>, ? extends U> transformer,
5566 <             Consumer<? super U> action) {
5567 <            if (transformer == null || action == null)
5568 <                throw new NullPointerException();
5569 <            return new ForEachTransformedEntryTask<K,V,U>
5570 <                (map, null, -1, transformer, action);
5571 <        }
5572 <
5573 <        /**
5574 <         * Returns a task that when invoked, returns a non-null result
5575 <         * from applying the given search function on each entry, or
5576 <         * null if none.  Upon success, further element processing is
5577 <         * suppressed and the results of any other parallel
5578 <         * invocations of the search function are ignored.
5579 <         *
5580 <         * @param map the map
5581 <         * @param searchFunction a function returning a non-null
5582 <         * result on success, else null
5583 <         * @return the task
5584 <         */
5585 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5586 <            (ConcurrentHashMap<K,V> map,
5587 <             Function<Map.Entry<K,V>, ? extends U> searchFunction) {
5588 <            if (searchFunction == null) throw new NullPointerException();
5589 <            return new SearchEntriesTask<K,V,U>
5590 <                (map, null, -1, searchFunction,
5591 <                 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 <        /**
5595 <         * Returns a task that when invoked, returns the result of
5596 <         * accumulating all entries using the given reducer to combine
5597 <         * values, or null if none.
5598 <         *
5599 <         * @param map the map
5600 <         * @param reducer a commutative associative combining function
5601 <         * @return the task
5602 <         */
5603 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5604 <            (ConcurrentHashMap<K,V> map,
5605 <             BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5606 <            if (reducer == null) throw new NullPointerException();
5607 <            return new ReduceEntriesTask<K,V>
5608 <                (map, null, -1, null, reducer);
5609 <        }
4866 >    }
4867  
4868 <        /**
5612 <         * Returns a task that when invoked, returns the result of
5613 <         * accumulating the given transformation of all entries using the
5614 <         * given reducer to combine values, or null if none.
5615 <         *
5616 <         * @param map the map
5617 <         * @param transformer a function returning the transformation
5618 <         * for an element, or null if there is no transformation (in
5619 <         * which case it is not combined)
5620 <         * @param reducer a commutative associative combining function
5621 <         * @return the task
5622 <         */
5623 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5624 <            (ConcurrentHashMap<K,V> map,
5625 <             Function<Map.Entry<K,V>, ? extends U> transformer,
5626 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5627 <            if (transformer == null || reducer == null)
5628 <                throw new NullPointerException();
5629 <            return new MapReduceEntriesTask<K,V,U>
5630 <                (map, null, -1, null, transformer, reducer);
5631 <        }
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 <             ToDoubleFunction<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
5659 <         * accumulating the given transformation of all entries using the
5660 <         * given reducer to combine values, and the given basis as an
5661 <         * identity value.
5662 <         *
5663 <         * @param map the map
5664 <         * @param transformer a function returning the transformation
5665 <         * for an element
5666 <         * @param basis the identity (initial default value) for the reduction
5667 <         * @param reducer a commutative associative combining function
5668 <         * @return the task
4900 >         * Same as Traverser version.
4901           */
4902 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4903 <            (ConcurrentHashMap<K,V> map,
4904 <             ToLongFunction<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 <             ToIntFunction<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  
5706    // -------------------------------------------------------
5707
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 5712 | 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> {
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,
4974 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4975               Consumer<? super K> action) {
4976 <            super(m, p, b);
4976 >            super(p, b, i, f, t);
4977              this.action = action;
4978          }
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 <                forEachKey(action);
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> {
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,
5001 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5002               Consumer<? super V> action) {
5003 <            super(m, p, b);
5003 >            super(p, b, i, f, t);
5004              this.action = action;
5005          }
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 <                forEachValue(action);
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> {
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,
5028 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5029               Consumer<? super Entry<K,V>> action) {
5030 <            super(m, p, b);
5030 >            super(p, b, i, f, t);
5031              this.action = action;
5032          }
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 = advanceValue()) != null)
5040 <                    action.accept(entryFor(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> {
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,
5055 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5056               BiConsumer<? super K,? super V> action) {
5057 <            super(m, p, b);
5057 >            super(p, b, i, f, t);
5058              this.action = action;
5059          }
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 = advanceValue()) != null)
5067 <                    action.accept(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 Consumer<? super U> action;
5082          ForEachTransformedKeyTask
5083 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int 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(m, p, b);
5085 >            super(p, b, i, f, t);
5086              this.transformer = transformer; this.action = action;
5087          }
5088          public final void compute() {
# Line 5812 | Line 5090 | public class ConcurrentHashMap<K,V>
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 <                K k; U u;
5099 <                while ((k = advanceKey()) != null) {
5100 <                    if ((u = transformer.apply(k)) != 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 5825 | 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 Consumer<? super U> action;
5115          ForEachTransformedValueTask
5116 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int 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(m, p, b);
5118 >            super(p, b, i, f, t);
5119              this.transformer = transformer; this.action = action;
5120          }
5121          public final void compute() {
# Line 5840 | Line 5123 | public class ConcurrentHashMap<K,V>
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 = advanceValue()) != 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 5853 | 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 Consumer<? super U> action;
5148          ForEachTransformedEntryTask
5149 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int 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(m, p, b);
5151 >            super(p, b, i, f, t);
5152              this.transformer = transformer; this.action = action;
5153          }
5154          public final void compute() {
# Line 5868 | Line 5156 | public class ConcurrentHashMap<K,V>
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 = advanceValue()) != null) {
5166 <                    if ((u = transformer.apply(entryFor(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 5882 | 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 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               Consumer<? super U> action) {
5185 <            super(m, p, b);
5185 >            super(p, b, i, f, t);
5186              this.transformer = transformer; this.action = action;
5187          }
5188          public final void compute() {
# Line 5898 | Line 5190 | public class ConcurrentHashMap<K,V>
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 = advanceValue()) != null) {
5200 <                    if ((u = transformer.apply(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 5911 | 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(); }
# Line 5928 | Line 5225 | public class ConcurrentHashMap<K,V>
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)
5935 <                        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 <                    K k; U u;
5239 <                    if ((k = advanceKey()) == null) {
5238 >                    U u;
5239 >                    Node<K,V> p;
5240 >                    if ((p = advance()) == null) {
5241                          propagateCompletion();
5242                          break;
5243                      }
5244 <                    if ((u = searchFunction.apply(k)) != null) {
5244 >                    if ((u = searchFunction.apply(p.key)) != null) {
5245                          if (result.compareAndSet(null, u))
5246                              quietlyCompleteRoot();
5247                          break;
# Line 5952 | 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(); }
# Line 5969 | Line 5269 | public class ConcurrentHashMap<K,V>
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)
5976 <                        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 = advanceValue()) == 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 5993 | 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(); }
# Line 6010 | Line 5313 | public class ConcurrentHashMap<K,V>
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)
6017 <                        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 = advanceValue()) == 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(nextKey,
6028 <                                                           v))) != null) {
5332 >                    if ((u = searchFunction.apply(p)) != null) {
5333                          if (result.compareAndSet(null, u))
5334                              quietlyCompleteRoot();
5335                          return;
# Line 6035 | 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(); }
# Line 6052 | Line 5357 | public class ConcurrentHashMap<K,V>
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)
6059 <                        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 = advanceValue()) == null) {
5370 >                    U u;
5371 >                    Node<K,V> p;
5372 >                    if ((p = advance()) == null) {
5373                          propagateCompletion();
5374                          break;
5375                      }
5376 <                    if ((u = searchFunction.apply(nextKey, v)) != null) {
5376 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5377                          if (result.compareAndSet(null, u))
5378                              quietlyCompleteRoot();
5379                          break;
# Line 6076 | 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();
5408 <                K u, r = null;
5409 <                while ((u = advanceKey()) != null) {
5407 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5408 >                      rights, reducer)).fork();
5409 >                }
5410 >                K r = null;
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 6117 | 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 = advanceValue()) != 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 6157 | 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;
6180 <                V v;
6181 <                while ((v = advanceValue()) != null) {
6182 <                    Map.Entry<K,V> u = entryFor(nextKey, v);
6183 <                    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 6200 | 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 <                K k; U r = null, u;
5556 <                while ((k = advanceKey()) != null) {
5557 <                    if ((u = transformer.apply(k)) != 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 6247 | 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 = advanceValue()) != 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 6295 | 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 = advanceValue()) != null) {
5666 <                    if ((u = transformer.apply(entryFor(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 6344 | 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 = advanceValue()) != null) {
5720 <                    if ((u = transformer.apply(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 6392 | 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> {
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               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() {
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 <                K k;
5775 <                while ((k = advanceKey()) != null)
5776 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(k));
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 6437 | 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> {
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               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() {
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 = advanceValue()) != 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 6482 | 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> {
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               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() {
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 = advanceValue()) != null)
5876 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(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 6528 | 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> {
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               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() {
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 = advanceValue()) != null)
5926 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(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 6573 | 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> {
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               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() {
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 <                K k;
5975 <                while ((k = advanceKey()) != null)
5976 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(k));
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 6618 | 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> {
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               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() {
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 = advanceValue()) != 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 6663 | 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> {
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               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() {
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 = advanceValue()) != null)
6076 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(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 6708 | 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> {
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               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() {
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 = advanceValue()) != null)
6126 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(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 6753 | 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> {
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               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() {
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 <                K k;
6175 <                while ((k = advanceKey()) != null)
6176 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(k));
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 6798 | 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> {
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               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() {
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 = advanceValue()) != 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 6843 | 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> {
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               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() {
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 = advanceValue()) != null)
6276 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(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 6889 | 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> {
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               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() {
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 = advanceValue()) != null)
6326 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(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 6935 | 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;
6941    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 {
6355          try {
6950            U = sun.misc.Unsafe.getUnsafe();
6951            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"));
6956 <            TRANSFERORIGIN = U.objectFieldOffset
6957 <                (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 <            int scale = U.arrayIndexScale(sc);
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("data type scale not a power of two");
6371 >                throw new Error("array index scale not a power of two");
6372              ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6373 <        } catch (Exception e) {
6373 >        } catch (ReflectiveOperationException e) {
6374              throw new Error(e);
6375          }
6974    }
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