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.199 by dl, Wed Mar 27 19:46:34 2013 UTC vs.
Revision 1.324 by dl, Fri Mar 18 16:01:41 2022 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;
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 56 | Line 62 | import java.io.Serializable;
62   * that key reporting the updated value.)  For aggregate operations
63   * such as {@code putAll} and {@code clear}, concurrent retrievals may
64   * reflect insertion or removal of only some entries.  Similarly,
65 < * Iterators and Enumerations return elements reflecting the state of
66 < * the hash table at some point at or since the creation of the
65 > * Iterators, Spliterators and Enumerations return elements reflecting the
66 > * state of the hash table at some point at or since the creation of the
67   * iterator/enumeration.  They do <em>not</em> throw {@link
68 < * ConcurrentModificationException}.  However, iterators are designed
69 < * to be used by only one thread at a time.  Bear in mind that the
70 < * results of aggregate status methods including {@code size}, {@code
71 < * isEmpty}, and {@code containsValue} are typically useful only when
72 < * a map is not undergoing concurrent updates in other threads.
68 > * java.util.ConcurrentModificationException ConcurrentModificationException}.
69 > * However, iterators are designed to be used by only one thread at a time.
70 > * Bear in mind that the results of aggregate status methods including
71 > * {@code size}, {@code isEmpty}, and {@code containsValue} are typically
72 > * useful only when a map is not undergoing concurrent updates in other threads.
73   * Otherwise the results of these methods reflect transient states
74   * that may be adequate for monitoring or estimation purposes, but not
75   * for program control.
# Line 87 | Line 93 | import java.io.Serializable;
93   * expected {@code concurrencyLevel} as an additional hint for
94   * internal sizing.  Note that using many keys with exactly the same
95   * {@code hashCode()} is a sure way to slow down performance of any
96 < * hash table.
96 > * hash table. To ameliorate impact, when keys are {@link Comparable},
97 > * this class may use comparison order among keys to help break ties.
98   *
99   * <p>A {@link Set} projection of a ConcurrentHashMap may be created
100   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
# Line 95 | Line 102 | import java.io.Serializable;
102   * mapped values are (perhaps transiently) not used or all take the
103   * same mapping value.
104   *
105 < * <p>A ConcurrentHashMap can be used as scalable frequency map (a
105 > * <p>A ConcurrentHashMap can be used as a scalable frequency map (a
106   * form of histogram or multiset) by using {@link
107   * java.util.concurrent.atomic.LongAdder} values and initializing via
108   * {@link #computeIfAbsent 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 109 | Line 116 | import java.io.Serializable;
116   * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
117   * does <em>not</em> allow {@code null} to be used as a key or value.
118   *
119 < * <p>ConcurrentHashMaps support sequential and parallel operations
120 < * bulk operations. (Parallel forms use the {@link
121 < * ForkJoinPool#commonPool()}). Tasks that may be used in other
122 < * contexts are available in class {@link ForkJoinTasks}. These
123 < * operations are designed to be safely, and often sensibly, applied
124 < * even with maps that are being concurrently updated by other
125 < * threads; for example, when computing a snapshot summary of the
126 < * values in a shared registry.  There are three kinds of operation,
127 < * each with four forms, accepting functions with Keys, Values,
128 < * Entries, and (Key, Value) arguments and/or return values. Because
129 < * the elements of a ConcurrentHashMap are not ordered in any
130 < * particular way, and may be processed in different orders in
131 < * different parallel executions, the correctness of supplied
132 < * functions should not depend on any ordering, or on any other
133 < * objects or values that may transiently change while computation is
127 < * in progress; and except for forEach actions, should ideally be
128 < * 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 Map.Entry} objects do not support method {@code setValue}.
134   *
135   * <ul>
136 < * <li> forEach: Perform a given action on each element.
136 > * <li>forEach: Performs a given action on each element.
137   * A variant form applies a given transformation on each element
138 < * before performing the action.</li>
138 > * before performing the action.
139   *
140 < * <li> search: Return the first available non-null result of
140 > * <li>search: Returns the first available non-null result of
141   * applying a given function on each element; skipping further
142 < * search when a result is found.</li>
142 > * search when a result is found.
143   *
144 < * <li> reduce: Accumulate each element.  The supplied reduction
144 > * <li>reduce: Accumulates each element.  The supplied reduction
145   * function cannot rely on ordering (more formally, it should be
146   * both associative and commutative).  There are five variants:
147   *
148   * <ul>
149   *
150 < * <li> Plain reductions. (There is not a form of this method for
150 > * <li>Plain reductions. (There is not a form of this method for
151   * (key, value) function arguments since there is no corresponding
152 < * return type.)</li>
152 > * return type.)
153   *
154 < * <li> Mapped reductions that accumulate the results of a given
155 < * function applied to each element.</li>
154 > * <li>Mapped reductions that accumulate the results of a given
155 > * function applied to each element.
156   *
157 < * <li> Reductions to scalar doubles, longs, and ints, using a
158 < * given basis value.</li>
157 > * <li>Reductions to scalar doubles, longs, and ints, using a
158 > * given basis value.
159   *
160   * </ul>
156 * </li>
161   * </ul>
162   *
163 + * <p>These bulk operations accept a {@code parallelismThreshold}
164 + * argument. Methods proceed sequentially if the current map size is
165 + * estimated to be less than the given threshold. Using a value of
166 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
167 + * of {@code 1} results in maximal parallelism by partitioning into
168 + * enough subtasks to fully utilize the {@link
169 + * ForkJoinPool#commonPool()} that is used for all parallel
170 + * computations. Normally, you would initially choose one of these
171 + * extreme values, and then measure performance of using in-between
172 + * values that trade off overhead versus throughput.
173 + *
174   * <p>The concurrency properties of bulk operations follow
175   * from those of ConcurrentHashMap: Any non-null result returned
176   * from {@code get(key)} and related access methods bears a
# Line 209 | Line 224 | import java.io.Serializable;
224   * <p>All arguments to all task methods must be non-null.
225   *
226   * <p>This class is a member of the
227 < * <a href="{@docRoot}/../technotes/guides/collections/index.html">
227 > * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
228   * Java Collections Framework</a>.
229   *
230   * @since 1.5
# Line 217 | Line 232 | import java.io.Serializable;
232   * @param <K> the type of keys maintained by this map
233   * @param <V> the type of mapped values
234   */
235 < public class ConcurrentHashMap<K,V>
235 > public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
236      implements ConcurrentMap<K,V>, Serializable {
237      private static final long serialVersionUID = 7249069246763182397L;
238  
# Line 231 | Line 246 | public class ConcurrentHashMap<K,V>
246       * the same or better than java.util.HashMap, and to support high
247       * initial insertion rates on an empty table by many threads.
248       *
249 <     * Each key-value mapping is held in a Node.  Because Node key
250 <     * fields can contain special values, they are defined using plain
251 <     * Object types (not type "K"). This leads to a lot of explicit
252 <     * casting (and many explicit warning suppressions to tell
253 <     * compilers not to complain about it). It also allows some of the
254 <     * public methods to be factored into a smaller number of internal
255 <     * methods (although sadly not so for the five variants of
256 <     * put-related operations). The validation-based approach
257 <     * explained below leads to a lot of code sprawl because
258 <     * retry-control precludes factoring into smaller methods.
249 >     * This map usually acts as a binned (bucketed) hash table.  Each
250 >     * key-value mapping is held in a Node.  Most nodes are instances
251 >     * of the basic Node class with hash, key, value, and next
252 >     * fields. However, various subclasses exist: TreeNodes are
253 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
254 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
255 >     * of bins during resizing. ReservationNodes are used as
256 >     * placeholders while establishing values in computeIfAbsent and
257 >     * related methods.  The types TreeBin, ForwardingNode, and
258 >     * ReservationNode do not hold normal user keys, values, or
259 >     * hashes, and are readily distinguishable during search etc
260 >     * because they have negative hash fields and null key and value
261 >     * fields. (These special nodes are either uncommon or transient,
262 >     * so the impact of carrying around some unused fields is
263 >     * insignificant.)
264       *
265       * The table is lazily initialized to a power-of-two size upon the
266       * first insertion.  Each bin in the table normally contains a
# Line 248 | Line 268 | public class ConcurrentHashMap<K,V>
268       * Table accesses require volatile/atomic reads, writes, and
269       * CASes.  Because there is no other way to arrange this without
270       * adding further indirections, we use intrinsics
271 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
252 <     * are always accurately traversable under volatile reads, so long
253 <     * as lookups check hash code and non-nullness of value before
254 <     * checking key equality.
271 >     * (jdk.internal.misc.Unsafe) operations.
272       *
273       * We use the top (sign) bit of Node hash fields for control
274       * purposes -- it is available anyway because of addressing
275 <     * constraints.  Nodes with negative hash fields are forwarding
276 <     * nodes to either TreeBins or resized tables.  The lower 31 bits
260 <     * of each normal Node's hash field contain a transformation of
261 <     * the key's hash code.
275 >     * constraints.  Nodes with negative hash fields are specially
276 >     * handled or ignored in map methods.
277       *
278       * Insertion (via put or its variants) of the first node in an
279       * empty bin is performed by just CASing it to the bin.  This is
# Line 275 | Line 290 | public class ConcurrentHashMap<K,V>
290       * validate that it is still the first node after locking it, and
291       * retry if not. Because new nodes are always appended to lists,
292       * once a node is first in a bin, it remains first until deleted
293 <     * or the bin becomes invalidated (upon resizing).  However,
279 <     * operations that only conditionally update may inspect nodes
280 <     * until the point of update. This is a converse of sorts to the
281 <     * lazy locking technique described by Herlihy & Shavit.
293 >     * or the bin becomes invalidated (upon resizing).
294       *
295       * The main disadvantage of per-bin locks is that other update
296       * operations on other nodes in a bin list protected by the same
# Line 311 | Line 323 | public class ConcurrentHashMap<K,V>
323       * sometimes deviate significantly from uniform randomness.  This
324       * includes the case when N > (1<<30), so some keys MUST collide.
325       * Similarly for dumb or hostile usages in which multiple keys are
326 <     * designed to have identical hash codes. Also, although we guard
327 <     * against the worst effects of this (see method spread), sets of
328 <     * hashes may differ only in bits that do not impact their bin
329 <     * index for a given power-of-two mask.  So we use a secondary
330 <     * strategy that applies when the number of nodes in a bin exceeds
331 <     * a threshold, and at least one of the keys implements
320 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
321 <     * (a specialized form of red-black trees), bounding search time
322 <     * to O(log N).  Each search step in a TreeBin is around twice as
326 >     * designed to have identical hash codes or ones that differs only
327 >     * in masked-out high bits. So we use a secondary strategy that
328 >     * applies when the number of nodes in a bin exceeds a
329 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
330 >     * specialized form of red-black trees), bounding search time to
331 >     * O(log N).  Each search step in a TreeBin is at least twice as
332       * slow as in a regular list, but given that N cannot exceed
333       * (1<<64) (before running out of addresses) this bounds search
334       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 332 | Line 341 | public class ConcurrentHashMap<K,V>
341       * The table is resized when occupancy exceeds a percentage
342       * threshold (nominally, 0.75, but see below).  Any thread
343       * noticing an overfull bin may assist in resizing after the
344 <     * initiating thread allocates and sets up the replacement
345 <     * array. However, rather than stalling, these other threads may
346 <     * proceed with insertions etc.  The use of TreeBins shields us
347 <     * from the worst case effects of overfilling while resizes are in
344 >     * initiating thread allocates and sets up the replacement array.
345 >     * However, rather than stalling, these other threads may proceed
346 >     * with insertions etc.  The use of TreeBins shields us from the
347 >     * worst case effects of overfilling while resizes are in
348       * progress.  Resizing proceeds by transferring bins, one by one,
349 <     * from the table to the next table. To enable concurrency, the
350 <     * next table must be (incrementally) prefilled with place-holders
351 <     * serving as reverse forwarders to the old table.  Because we are
349 >     * from the table to the next table. However, threads claim small
350 >     * blocks of indices to transfer (via field transferIndex) before
351 >     * doing so, reducing contention.  A generation stamp in field
352 >     * sizeCtl ensures that resizings do not overlap. Because we are
353       * using power-of-two expansion, the elements from each bin must
354       * either stay at same index, or move with a power of two
355       * offset. We eliminate unnecessary node creation by catching
356       * cases where old nodes can be reused because their next fields
357       * won't change.  On average, only about one-sixth of them need
358       * cloning when a table doubles. The nodes they replace will be
359 <     * garbage collectable as soon as they are no longer referenced by
359 >     * garbage collectible as soon as they are no longer referenced by
360       * any reader thread that may be in the midst of concurrently
361       * traversing table.  Upon transfer, the old table bin contains
362       * only a special forwarding node (with hash field "MOVED") that
# Line 360 | Line 370 | public class ConcurrentHashMap<K,V>
370       * locks, average aggregate waits become shorter as resizing
371       * progresses.  The transfer operation must also ensure that all
372       * accessible bins in both the old and new table are usable by any
373 <     * traversal.  This is arranged by proceeding from the last bin
374 <     * (table.length - 1) up towards the first.  Upon seeing a
375 <     * forwarding node, traversals (see class Traverser) arrange to
376 <     * move to the new table without revisiting nodes.  However, to
377 <     * ensure that no intervening nodes are skipped, bin splitting can
378 <     * only begin after the associated reverse-forwarders are in
379 <     * place.
373 >     * traversal.  This is arranged in part by proceeding from the
374 >     * last bin (table.length - 1) up towards the first.  Upon seeing
375 >     * a forwarding node, traversals (see class Traverser) arrange to
376 >     * move to the new table without revisiting nodes.  To ensure that
377 >     * no intervening nodes are skipped even when moved out of order,
378 >     * a stack (see class TableStack) is created on first encounter of
379 >     * a forwarding node during a traversal, to maintain its place if
380 >     * later processing the current table. The need for these
381 >     * save/restore mechanics is relatively rare, but when one
382 >     * forwarding node is encountered, typically many more will be.
383 >     * So Traversers use a simple caching scheme to avoid creating so
384 >     * many new TableStack nodes. (Thanks to Peter Levart for
385 >     * suggesting use of a stack here.)
386       *
387       * The traversal scheme also applies to partial traversals of
388       * ranges of bins (via an alternate Traverser constructor)
# Line 385 | Line 401 | public class ConcurrentHashMap<K,V>
401       * LongAdder. We need to incorporate a specialization rather than
402       * just use a LongAdder in order to access implicit
403       * contention-sensing that leads to creation of multiple
404 <     * Cells.  The counter mechanics avoid contention on
404 >     * CounterCells.  The counter mechanics avoid contention on
405       * updates but can encounter cache thrashing if read too
406       * frequently during concurrent access. To avoid reading so often,
407       * resizing under contention is attempted only upon adding to a
408       * bin already holding two or more nodes. Under uniform hash
409       * distributions, the probability of this occurring at threshold
410       * is around 13%, meaning that only about 1 in 8 puts check
411 <     * threshold (and after resizing, many fewer do so). The bulk
412 <     * putAll operation further reduces contention by only committing
413 <     * count updates upon these size checks.
411 >     * threshold (and after resizing, many fewer do so).
412 >     *
413 >     * TreeBins use a special form of comparison for search and
414 >     * related operations (which is the main reason we cannot use
415 >     * existing collections such as TreeMaps). TreeBins contain
416 >     * Comparable elements, but may contain others, as well as
417 >     * elements that are Comparable but not necessarily Comparable for
418 >     * the same T, so we cannot invoke compareTo among them. To handle
419 >     * this, the tree is ordered primarily by hash value, then by
420 >     * Comparable.compareTo order if applicable.  On lookup at a node,
421 >     * if elements are not comparable or compare as 0 then both left
422 >     * and right children may need to be searched in the case of tied
423 >     * hash values. (This corresponds to the full list search that
424 >     * would be necessary if all elements were non-Comparable and had
425 >     * tied hashes.) On insertion, to keep a total ordering (or as
426 >     * close as is required here) across rebalancings, we compare
427 >     * classes and identityHashCodes as tie-breakers. The red-black
428 >     * balancing code is updated from pre-jdk-collections
429 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
430 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
431 >     * Algorithms" (CLR).
432 >     *
433 >     * TreeBins also require an additional locking mechanism.  While
434 >     * list traversal is always possible by readers even during
435 >     * updates, tree traversal is not, mainly because of tree-rotations
436 >     * that may change the root node and/or its linkages.  TreeBins
437 >     * include a simple read-write lock mechanism parasitic on the
438 >     * main bin-synchronization strategy: Structural adjustments
439 >     * associated with an insertion or removal are already bin-locked
440 >     * (and so cannot conflict with other writers) but must wait for
441 >     * ongoing readers to finish. Since there can be only one such
442 >     * waiter, we use a simple scheme using a single "waiter" field to
443 >     * block writers.  However, readers need never block.  If the root
444 >     * lock is held, they proceed along the slow traversal path (via
445 >     * next-pointers) until the lock becomes available or the list is
446 >     * exhausted, whichever comes first. These cases are not fast, but
447 >     * maximize aggregate expected throughput.
448       *
449       * Maintaining API and serialization compatibility with previous
450       * versions of this class introduces several oddities. Mainly: We
451 <     * leave untouched but unused constructor arguments refering to
451 >     * leave untouched but unused constructor arguments referring to
452       * concurrencyLevel. We accept a loadFactor constructor argument,
453       * but apply it only to initial table capacity (which is the only
454       * time that we can guarantee to honor it.) We also declare an
455       * unused "Segment" class that is instantiated in minimal form
456       * only when serializing.
457 +     *
458 +     * Also, solely for compatibility with previous versions of this
459 +     * class, it extends AbstractMap, even though all of its methods
460 +     * are overridden, so it is just useless baggage.
461 +     *
462 +     * This file is organized to make things a little easier to follow
463 +     * while reading than they might otherwise: First the main static
464 +     * declarations and utilities, then fields, then main public
465 +     * methods (with a few factorings of multiple public methods into
466 +     * internal ones), then sizing methods, trees, traversers, and
467 +     * bulk operations.
468       */
469  
470      /* ---------------- Constants -------------- */
# Line 446 | Line 507 | public class ConcurrentHashMap<K,V>
507  
508      /**
509       * The bin count threshold for using a tree rather than list for a
510 <     * bin.  The value reflects the approximate break-even point for
511 <     * using tree-based operations.
510 >     * bin.  Bins are converted to trees when adding an element to a
511 >     * bin with at least this many nodes. The value must be greater
512 >     * than 2, and should be at least 8 to mesh with assumptions in
513 >     * tree removal about conversion back to plain bins upon
514 >     * shrinkage.
515       */
516 <    private static final int TREE_THRESHOLD = 8;
516 >    static final int TREEIFY_THRESHOLD = 8;
517 >
518 >    /**
519 >     * The bin count threshold for untreeifying a (split) bin during a
520 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
521 >     * most 6 to mesh with shrinkage detection under removal.
522 >     */
523 >    static final int UNTREEIFY_THRESHOLD = 6;
524 >
525 >    /**
526 >     * The smallest table capacity for which bins may be treeified.
527 >     * (Otherwise the table is resized if too many nodes in a bin.)
528 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
529 >     * conflicts between resizing and treeification thresholds.
530 >     */
531 >    static final int MIN_TREEIFY_CAPACITY = 64;
532  
533      /**
534       * Minimum number of rebinnings per transfer step. Ranges are
# Line 460 | Line 539 | public class ConcurrentHashMap<K,V>
539       */
540      private static final int MIN_TRANSFER_STRIDE = 16;
541  
542 +    /**
543 +     * The number of bits used for generation stamp in sizeCtl.
544 +     * Must be at least 6 for 32bit arrays.
545 +     */
546 +    private static final int RESIZE_STAMP_BITS = 16;
547 +
548 +    /**
549 +     * The maximum number of threads that can help resize.
550 +     * Must fit in 32 - RESIZE_STAMP_BITS bits.
551 +     */
552 +    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
553 +
554 +    /**
555 +     * The bit shift for recording size stamp in sizeCtl.
556 +     */
557 +    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
558 +
559      /*
560       * Encodings for Node hash fields. See above for explanation.
561       */
562 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
562 >    static final int MOVED     = -1; // hash for forwarding nodes
563 >    static final int TREEBIN   = -2; // hash for roots of trees
564 >    static final int RESERVED  = -3; // hash for transient reservations
565      static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
566  
567      /** Number of CPUS, to place bounds on some sizings */
568      static final int NCPU = Runtime.getRuntime().availableProcessors();
569  
570 <    /* ---------------- Counters -------------- */
570 >    /**
571 >     * Serialized pseudo-fields, provided only for jdk7 compatibility.
572 >     * @serialField segments Segment[]
573 >     *   The segments, each of which is a specialized hash table.
574 >     * @serialField segmentMask int
575 >     *   Mask value for indexing into segments. The upper bits of a
576 >     *   key's hash code are used to choose the segment.
577 >     * @serialField segmentShift int
578 >     *   Shift value for indexing within segments.
579 >     */
580 >    private static final ObjectStreamField[] serialPersistentFields = {
581 >        new ObjectStreamField("segments", Segment[].class),
582 >        new ObjectStreamField("segmentMask", Integer.TYPE),
583 >        new ObjectStreamField("segmentShift", Integer.TYPE),
584 >    };
585  
586 <    // Adapted from LongAdder and Striped64.
475 <    // See their internal docs for explanation.
586 >    /* ---------------- Nodes -------------- */
587  
588 <    // A padded cell for distributing counts
589 <    static final class Cell {
590 <        volatile long p0, p1, p2, p3, p4, p5, p6;
591 <        volatile long value;
592 <        volatile long q0, q1, q2, q3, q4, q5, q6;
593 <        Cell(long x) { value = x; }
588 >    /**
589 >     * Key-value entry.  This class is never exported out as a
590 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
591 >     * MapEntry below), but can be used for read-only traversals used
592 >     * in bulk tasks.  Subclasses of Node with a negative hash field
593 >     * are special, and contain null keys and values (but are never
594 >     * exported).  Otherwise, keys and vals are never null.
595 >     */
596 >    static class Node<K,V> implements Map.Entry<K,V> {
597 >        final int hash;
598 >        final K key;
599 >        volatile V val;
600 >        volatile Node<K,V> next;
601 >
602 >        Node(int hash, K key, V val) {
603 >            this.hash = hash;
604 >            this.key = key;
605 >            this.val = val;
606 >        }
607 >
608 >        Node(int hash, K key, V val, Node<K,V> next) {
609 >            this(hash, key, val);
610 >            this.next = next;
611 >        }
612 >
613 >        public final K getKey()     { return key; }
614 >        public final V getValue()   { return val; }
615 >        public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
616 >        public final String toString() {
617 >            return Helpers.mapEntryToString(key, val);
618 >        }
619 >        public final V setValue(V value) {
620 >            throw new UnsupportedOperationException();
621 >        }
622 >
623 >        public final boolean equals(Object o) {
624 >            Object k, v, u; Map.Entry<?,?> e;
625 >            return ((o instanceof Map.Entry) &&
626 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
627 >                    (v = e.getValue()) != null &&
628 >                    (k == key || k.equals(key)) &&
629 >                    (v == (u = val) || v.equals(u)));
630 >        }
631 >
632 >        /**
633 >         * Virtualized support for map.get(); overridden in subclasses.
634 >         */
635 >        Node<K,V> find(int h, Object k) {
636 >            Node<K,V> e = this;
637 >            if (k != null) {
638 >                do {
639 >                    K ek;
640 >                    if (e.hash == h &&
641 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
642 >                        return e;
643 >                } while ((e = e.next) != null);
644 >            }
645 >            return null;
646 >        }
647 >    }
648 >
649 >    /* ---------------- Static utilities -------------- */
650 >
651 >    /**
652 >     * Spreads (XORs) higher bits of hash to lower and also forces top
653 >     * bit to 0. Because the table uses power-of-two masking, sets of
654 >     * hashes that vary only in bits above the current mask will
655 >     * always collide. (Among known examples are sets of Float keys
656 >     * holding consecutive whole numbers in small tables.)  So we
657 >     * apply a transform that spreads the impact of higher bits
658 >     * downward. There is a tradeoff between speed, utility, and
659 >     * quality of bit-spreading. Because many common sets of hashes
660 >     * are already reasonably distributed (so don't benefit from
661 >     * spreading), and because we use trees to handle large sets of
662 >     * collisions in bins, we just XOR some shifted bits in the
663 >     * cheapest possible way to reduce systematic lossage, as well as
664 >     * to incorporate impact of the highest bits that would otherwise
665 >     * never be used in index calculations because of table bounds.
666 >     */
667 >    static final int spread(int h) {
668 >        return (h ^ (h >>> 16)) & HASH_BITS;
669 >    }
670 >
671 >    /**
672 >     * Returns a power of two table size for the given desired capacity.
673 >     * See Hackers Delight, sec 3.2
674 >     */
675 >    private static final int tableSizeFor(int c) {
676 >        int n = -1 >>> Integer.numberOfLeadingZeros(c - 1);
677 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
678 >    }
679 >
680 >    /**
681 >     * Returns x's Class if it is of the form "class C implements
682 >     * Comparable<C>", else null.
683 >     */
684 >    static Class<?> comparableClassFor(Object x) {
685 >        if (x instanceof Comparable) {
686 >            Class<?> c; Type[] ts, as; ParameterizedType p;
687 >            if ((c = x.getClass()) == String.class) // bypass checks
688 >                return c;
689 >            if ((ts = c.getGenericInterfaces()) != null) {
690 >                for (Type t : ts) {
691 >                    if ((t instanceof ParameterizedType) &&
692 >                        ((p = (ParameterizedType)t).getRawType() ==
693 >                         Comparable.class) &&
694 >                        (as = p.getActualTypeArguments()) != null &&
695 >                        as.length == 1 && as[0] == c) // type arg is c
696 >                        return c;
697 >                }
698 >            }
699 >        }
700 >        return null;
701 >    }
702 >
703 >    /**
704 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
705 >     * class), else 0.
706 >     */
707 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
708 >    static int compareComparables(Class<?> kc, Object k, Object x) {
709 >        return (x == null || x.getClass() != kc ? 0 :
710 >                ((Comparable)k).compareTo(x));
711 >    }
712 >
713 >    /* ---------------- Table element access -------------- */
714 >
715 >    /*
716 >     * Atomic access methods are used for table elements as well as
717 >     * elements of in-progress next table while resizing.  All uses of
718 >     * the tab arguments must be null checked by callers.  All callers
719 >     * also paranoically precheck that tab's length is not zero (or an
720 >     * equivalent check), thus ensuring that any index argument taking
721 >     * the form of a hash value anded with (length - 1) is a valid
722 >     * index.  Note that, to be correct wrt arbitrary concurrency
723 >     * errors by users, these checks must operate on local variables,
724 >     * which accounts for some odd-looking inline assignments below.
725 >     * Note that calls to setTabAt always occur within locked regions,
726 >     * and so require only release ordering.
727 >     */
728 >
729 >    @SuppressWarnings("unchecked")
730 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
731 >        return (Node<K,V>)U.getReferenceAcquire(tab, ((long)i << ASHIFT) + ABASE);
732 >    }
733 >
734 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
735 >                                        Node<K,V> c, Node<K,V> v) {
736 >        return U.compareAndSetReference(tab, ((long)i << ASHIFT) + ABASE, c, v);
737 >    }
738 >
739 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
740 >        U.putReferenceRelease(tab, ((long)i << ASHIFT) + ABASE, v);
741      }
742  
743      /* ---------------- Fields -------------- */
# Line 488 | Line 746 | public class ConcurrentHashMap<K,V>
746       * The array of bins. Lazily initialized upon first insertion.
747       * Size is always a power of two. Accessed directly by iterators.
748       */
749 <    transient volatile Node<V>[] table;
749 >    transient volatile Node<K,V>[] table;
750  
751      /**
752       * The next table to use; non-null only while resizing.
753       */
754 <    private transient volatile Node<V>[] nextTable;
754 >    private transient volatile Node<K,V>[] nextTable;
755  
756      /**
757       * Base counter value, used mainly when there is no contention,
# Line 518 | Line 776 | public class ConcurrentHashMap<K,V>
776      private transient volatile int transferIndex;
777  
778      /**
779 <     * The least available table index to split while resizing.
522 <     */
523 <    private transient volatile int transferOrigin;
524 <
525 <    /**
526 <     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
779 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
780       */
781      private transient volatile int cellsBusy;
782  
783      /**
784       * Table of counter cells. When non-null, size is a power of 2.
785       */
786 <    private transient volatile Cell[] counterCells;
786 >    private transient volatile CounterCell[] counterCells;
787  
788      // views
789      private transient KeySetView<K,V> keySet;
790      private transient ValuesView<K,V> values;
791      private transient EntrySetView<K,V> entrySet;
792  
540    /** For serialization compatibility. Null unless serialized; see below */
541    private Segment<K,V>[] segments;
793  
794 <    /* ---------------- Table element access -------------- */
794 >    /* ---------------- Public operations -------------- */
795  
796 <    /*
797 <     * Volatile access methods are used for table elements as well as
798 <     * elements of in-progress next table while resizing.  Uses are
799 <     * null checked by callers, and implicitly bounds-checked, relying
549 <     * on the invariants that tab arrays have non-zero size, and all
550 <     * indices are masked with (tab.length - 1) which is never
551 <     * negative and always less than length. Note that, to be correct
552 <     * wrt arbitrary concurrency errors by users, bounds checks must
553 <     * operate on local variables, which accounts for some odd-looking
554 <     * inline assignments below.
555 <     */
556 <
557 <    @SuppressWarnings("unchecked") static final <V> Node<V> tabAt
558 <        (Node<V>[] tab, int i) { // used by Traverser
559 <        return (Node<V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
560 <    }
561 <
562 <    private static final <V> boolean casTabAt
563 <        (Node<V>[] tab, int i, Node<V> c, Node<V> v) {
564 <        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
565 <    }
566 <
567 <    private static final <V> void setTabAt
568 <        (Node<V>[] tab, int i, Node<V> v) {
569 <        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
796 >    /**
797 >     * Creates a new, empty map with the default initial table size (16).
798 >     */
799 >    public ConcurrentHashMap() {
800      }
801  
802 <    /* ---------------- Nodes -------------- */
802 >    /**
803 >     * Creates a new, empty map with an initial table size
804 >     * accommodating the specified number of elements without the need
805 >     * to dynamically resize.
806 >     *
807 >     * @param initialCapacity The implementation performs internal
808 >     * sizing to accommodate this many elements.
809 >     * @throws IllegalArgumentException if the initial capacity of
810 >     * elements is negative
811 >     */
812 >    public ConcurrentHashMap(int initialCapacity) {
813 >        this(initialCapacity, LOAD_FACTOR, 1);
814 >    }
815  
816      /**
817 <     * Key-value entry. Note that this is never exported out as a
818 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
819 <     * field of MOVED are special, and do not contain user keys or
578 <     * values.  Otherwise, keys are never null, and null val fields
579 <     * indicate that a node is in the process of being deleted or
580 <     * created. For purposes of read-only access, a key may be read
581 <     * before a val, but can only be used after checking val to be
582 <     * non-null.
817 >     * Creates a new map with the same mappings as the given map.
818 >     *
819 >     * @param m the map
820       */
821 <    static class Node<V> {
822 <        final int hash;
823 <        final Object key;
824 <        volatile V val;
588 <        volatile Node<V> next;
821 >    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
822 >        this.sizeCtl = DEFAULT_CAPACITY;
823 >        putAll(m);
824 >    }
825  
826 <        Node(int hash, Object key, V val, Node<V> next) {
827 <            this.hash = hash;
828 <            this.key = key;
829 <            this.val = val;
830 <            this.next = next;
831 <        }
826 >    /**
827 >     * Creates a new, empty map with an initial table size based on
828 >     * the given number of elements ({@code initialCapacity}) and
829 >     * initial table density ({@code loadFactor}).
830 >     *
831 >     * @param initialCapacity the initial capacity. The implementation
832 >     * performs internal sizing to accommodate this many elements,
833 >     * given the specified load factor.
834 >     * @param loadFactor the load factor (table density) for
835 >     * establishing the initial table size
836 >     * @throws IllegalArgumentException if the initial capacity of
837 >     * elements is negative or the load factor is nonpositive
838 >     *
839 >     * @since 1.6
840 >     */
841 >    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
842 >        this(initialCapacity, loadFactor, 1);
843      }
844  
845 <    /* ---------------- TreeBins -------------- */
845 >    /**
846 >     * Creates a new, empty map with an initial table size based on
847 >     * the given number of elements ({@code initialCapacity}), initial
848 >     * table density ({@code loadFactor}), and number of concurrently
849 >     * updating threads ({@code concurrencyLevel}).
850 >     *
851 >     * @param initialCapacity the initial capacity. The implementation
852 >     * performs internal sizing to accommodate this many elements,
853 >     * given the specified load factor.
854 >     * @param loadFactor the load factor (table density) for
855 >     * establishing the initial table size
856 >     * @param concurrencyLevel the estimated number of concurrently
857 >     * updating threads. The implementation may use this value as
858 >     * a sizing hint.
859 >     * @throws IllegalArgumentException if the initial capacity is
860 >     * negative or the load factor or concurrencyLevel are
861 >     * nonpositive
862 >     */
863 >    public ConcurrentHashMap(int initialCapacity,
864 >                             float loadFactor, int concurrencyLevel) {
865 >        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
866 >            throw new IllegalArgumentException();
867 >        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
868 >            initialCapacity = concurrencyLevel;   // as estimated threads
869 >        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
870 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
871 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
872 >        this.sizeCtl = cap;
873 >    }
874 >
875 >    // Original (since JDK1.2) Map methods
876  
877      /**
878 <     * Nodes for use in TreeBins
878 >     * {@inheritDoc}
879       */
880 <    static final class TreeNode<V> extends Node<V> {
881 <        TreeNode<V> parent;  // red-black tree links
882 <        TreeNode<V> left;
883 <        TreeNode<V> right;
884 <        TreeNode<V> prev;    // needed to unlink next upon deletion
885 <        boolean red;
880 >    public int size() {
881 >        long n = sumCount();
882 >        return ((n < 0L) ? 0 :
883 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
884 >                (int)n);
885 >    }
886  
887 <        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
888 <            super(hash, key, val, next);
889 <            this.parent = parent;
890 <        }
887 >    /**
888 >     * {@inheritDoc}
889 >     */
890 >    public boolean isEmpty() {
891 >        return sumCount() <= 0L; // ignore transient negative values
892      }
893  
894      /**
895 <     * A specialized form of red-black tree for use in bins
896 <     * whose size exceeds a threshold.
895 >     * Returns the value to which the specified key is mapped,
896 >     * or {@code null} if this map contains no mapping for the key.
897       *
898 <     * TreeBins use a special form of comparison for search and
899 <     * related operations (which is the main reason we cannot use
900 <     * existing collections such as TreeMaps). TreeBins contain
901 <     * Comparable elements, but may contain others, as well as
624 <     * elements that are Comparable but not necessarily Comparable<T>
625 <     * for the same T, so we cannot invoke compareTo among them. To
626 <     * handle this, the tree is ordered primarily by hash value, then
627 <     * by getClass().getName() order, and then by Comparator order
628 <     * among elements of the same class.  On lookup at a node, if
629 <     * elements are not comparable or compare as 0, both left and
630 <     * right children may need to be searched in the case of tied hash
631 <     * values. (This corresponds to the full list search that would be
632 <     * necessary if all elements were non-Comparable and had tied
633 <     * hashes.)  The red-black balancing code is updated from
634 <     * pre-jdk-collections
635 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
636 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
637 <     * Algorithms" (CLR).
898 >     * <p>More formally, if this map contains a mapping from a key
899 >     * {@code k} to a value {@code v} such that {@code key.equals(k)},
900 >     * then this method returns {@code v}; otherwise it returns
901 >     * {@code null}.  (There can be at most one such mapping.)
902       *
903 <     * TreeBins also maintain a separate locking discipline than
640 <     * regular bins. Because they are forwarded via special MOVED
641 <     * nodes at bin heads (which can never change once established),
642 <     * we cannot use those nodes as locks. Instead, TreeBin
643 <     * extends AbstractQueuedSynchronizer to support a simple form of
644 <     * read-write lock. For update operations and table validation,
645 <     * the exclusive form of lock behaves in the same way as bin-head
646 <     * locks. However, lookups use shared read-lock mechanics to allow
647 <     * multiple readers in the absence of writers.  Additionally,
648 <     * these lookups do not ever block: While the lock is not
649 <     * available, they proceed along the slow traversal path (via
650 <     * next-pointers) until the lock becomes available or the list is
651 <     * exhausted, whichever comes first. (These cases are not fast,
652 <     * but maximize aggregate expected throughput.)  The AQS mechanics
653 <     * for doing this are straightforward.  The lock state is held as
654 <     * AQS getState().  Read counts are negative; the write count (1)
655 <     * is positive.  There are no signalling preferences among readers
656 <     * and writers. Since we don't need to export full Lock API, we
657 <     * just override the minimal AQS methods and use them directly.
903 >     * @throws NullPointerException if the specified key is null
904       */
905 <    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
906 <        private static final long serialVersionUID = 2249069246763182397L;
907 <        transient TreeNode<V> root;  // root of tree
908 <        transient TreeNode<V> first; // head of next-pointer list
909 <
910 <        /* AQS overrides */
911 <        public final boolean isHeldExclusively() { return getState() > 0; }
912 <        public final boolean tryAcquire(int ignore) {
913 <            if (compareAndSetState(0, 1)) {
914 <                setExclusiveOwnerThread(Thread.currentThread());
915 <                return true;
916 <            }
917 <            return false;
918 <        }
919 <        public final boolean tryRelease(int ignore) {
674 <            setExclusiveOwnerThread(null);
675 <            setState(0);
676 <            return true;
677 <        }
678 <        public final int tryAcquireShared(int ignore) {
679 <            for (int c;;) {
680 <                if ((c = getState()) > 0)
681 <                    return -1;
682 <                if (compareAndSetState(c, c -1))
683 <                    return 1;
684 <            }
685 <        }
686 <        public final boolean tryReleaseShared(int ignore) {
687 <            int c;
688 <            do {} while (!compareAndSetState(c = getState(), c + 1));
689 <            return c == -1;
690 <        }
691 <
692 <        /** From CLR */
693 <        private void rotateLeft(TreeNode<V> p) {
694 <            if (p != null) {
695 <                TreeNode<V> r = p.right, pp, rl;
696 <                if ((rl = p.right = r.left) != null)
697 <                    rl.parent = p;
698 <                if ((pp = r.parent = p.parent) == null)
699 <                    root = r;
700 <                else if (pp.left == p)
701 <                    pp.left = r;
702 <                else
703 <                    pp.right = r;
704 <                r.left = p;
705 <                p.parent = r;
905 >    public V get(Object key) {
906 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
907 >        int h = spread(key.hashCode());
908 >        if ((tab = table) != null && (n = tab.length) > 0 &&
909 >            (e = tabAt(tab, (n - 1) & h)) != null) {
910 >            if ((eh = e.hash) == h) {
911 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
912 >                    return e.val;
913 >            }
914 >            else if (eh < 0)
915 >                return (p = e.find(h, key)) != null ? p.val : null;
916 >            while ((e = e.next) != null) {
917 >                if (e.hash == h &&
918 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
919 >                    return e.val;
920              }
921          }
922 +        return null;
923 +    }
924  
925 <        /** From CLR */
926 <        private void rotateRight(TreeNode<V> p) {
927 <            if (p != null) {
928 <                TreeNode<V> l = p.left, pp, lr;
929 <                if ((lr = p.left = l.right) != null)
930 <                    lr.parent = p;
931 <                if ((pp = l.parent = p.parent) == null)
932 <                    root = l;
933 <                else if (pp.right == p)
934 <                    pp.right = l;
935 <                else
936 <                    pp.left = l;
721 <                l.right = p;
722 <                p.parent = l;
723 <            }
724 <        }
925 >    /**
926 >     * Tests if the specified object is a key in this table.
927 >     *
928 >     * @param  key possible key
929 >     * @return {@code true} if and only if the specified object
930 >     *         is a key in this table, as determined by the
931 >     *         {@code equals} method; {@code false} otherwise
932 >     * @throws NullPointerException if the specified key is null
933 >     */
934 >    public boolean containsKey(Object key) {
935 >        return get(key) != null;
936 >    }
937  
938 <        /**
939 <         * Returns the TreeNode (or null if not found) for the given key
940 <         * starting at given root.
941 <         */
942 <        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
943 <            (int h, Object k, TreeNode<V> p) {
944 <            Class<?> c = k.getClass();
945 <            while (p != null) {
946 <                int dir, ph;  Object pk; Class<?> pc;
947 <                if ((ph = p.hash) == h) {
948 <                    if ((pk = p.key) == k || k.equals(pk))
949 <                        return p;
950 <                    if (c != (pc = pk.getClass()) ||
951 <                        !(k instanceof Comparable) ||
952 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
953 <                        if ((dir = (c == pc) ? 0 :
954 <                             c.getName().compareTo(pc.getName())) == 0) {
955 <                            TreeNode<V> r = null, pl, pr; // check both sides
956 <                            if ((pr = p.right) != null && h >= pr.hash &&
957 <                                (r = getTreeNode(h, k, pr)) != null)
746 <                                return r;
747 <                            else if ((pl = p.left) != null && h <= pl.hash)
748 <                                dir = -1;
749 <                            else // nothing there
750 <                                return null;
751 <                        }
752 <                    }
753 <                }
754 <                else
755 <                    dir = (h < ph) ? -1 : 1;
756 <                p = (dir > 0) ? p.right : p.left;
938 >    /**
939 >     * Returns {@code true} if this map maps one or more keys to the
940 >     * specified value. Note: This method may require a full traversal
941 >     * of the map, and is much slower than method {@code containsKey}.
942 >     *
943 >     * @param value value whose presence in this map is to be tested
944 >     * @return {@code true} if this map maps one or more keys to the
945 >     *         specified value
946 >     * @throws NullPointerException if the specified value is null
947 >     */
948 >    public boolean containsValue(Object value) {
949 >        if (value == null)
950 >            throw new NullPointerException();
951 >        Node<K,V>[] t;
952 >        if ((t = table) != null) {
953 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
954 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
955 >                V v;
956 >                if ((v = p.val) == value || (v != null && value.equals(v)))
957 >                    return true;
958              }
758            return null;
959          }
960 +        return false;
961 +    }
962  
963 <        /**
964 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
965 <         * read-lock to call getTreeNode, but during failure to get
966 <         * lock, searches along next links.
967 <         */
968 <        final V getValue(int h, Object k) {
969 <            Node<V> r = null;
970 <            int c = getState(); // Must read lock state first
971 <            for (Node<V> e = first; e != null; e = e.next) {
972 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
973 <                    try {
974 <                        r = getTreeNode(h, k, root);
975 <                    } finally {
976 <                        releaseShared(0);
963 >    /**
964 >     * Maps the specified key to the specified value in this table.
965 >     * Neither the key nor the value can be null.
966 >     *
967 >     * <p>The value can be retrieved by calling the {@code get} method
968 >     * with a key that is equal to the original key.
969 >     *
970 >     * @param key key with which the specified value is to be associated
971 >     * @param value value to be associated with the specified key
972 >     * @return the previous value associated with {@code key}, or
973 >     *         {@code null} if there was no mapping for {@code key}
974 >     * @throws NullPointerException if the specified key or value is null
975 >     */
976 >    public V put(K key, V value) {
977 >        return putVal(key, value, false);
978 >    }
979 >
980 >    /** Implementation for put and putIfAbsent */
981 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
982 >        if (key == null || value == null) throw new NullPointerException();
983 >        int hash = spread(key.hashCode());
984 >        int binCount = 0;
985 >        for (Node<K,V>[] tab = table;;) {
986 >            Node<K,V> f; int n, i, fh; K fk; V fv;
987 >            if (tab == null || (n = tab.length) == 0)
988 >                tab = initTable();
989 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
990 >                if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value)))
991 >                    break;                   // no lock when adding to empty bin
992 >            }
993 >            else if ((fh = f.hash) == MOVED)
994 >                tab = helpTransfer(tab, f);
995 >            else if (onlyIfAbsent // check first node without acquiring lock
996 >                     && fh == hash
997 >                     && ((fk = f.key) == key || (fk != null && key.equals(fk)))
998 >                     && (fv = f.val) != null)
999 >                return fv;
1000 >            else {
1001 >                V oldVal = null;
1002 >                synchronized (f) {
1003 >                    if (tabAt(tab, i) == f) {
1004 >                        if (fh >= 0) {
1005 >                            binCount = 1;
1006 >                            for (Node<K,V> e = f;; ++binCount) {
1007 >                                K ek;
1008 >                                if (e.hash == hash &&
1009 >                                    ((ek = e.key) == key ||
1010 >                                     (ek != null && key.equals(ek)))) {
1011 >                                    oldVal = e.val;
1012 >                                    if (!onlyIfAbsent)
1013 >                                        e.val = value;
1014 >                                    break;
1015 >                                }
1016 >                                Node<K,V> pred = e;
1017 >                                if ((e = e.next) == null) {
1018 >                                    pred.next = new Node<K,V>(hash, key, value);
1019 >                                    break;
1020 >                                }
1021 >                            }
1022 >                        }
1023 >                        else if (f instanceof TreeBin) {
1024 >                            Node<K,V> p;
1025 >                            binCount = 2;
1026 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1027 >                                                           value)) != null) {
1028 >                                oldVal = p.val;
1029 >                                if (!onlyIfAbsent)
1030 >                                    p.val = value;
1031 >                            }
1032 >                        }
1033 >                        else if (f instanceof ReservationNode)
1034 >                            throw new IllegalStateException("Recursive update");
1035                      }
776                    break;
1036                  }
1037 <                else if (e.hash == h && k.equals(e.key)) {
1038 <                    r = e;
1037 >                if (binCount != 0) {
1038 >                    if (binCount >= TREEIFY_THRESHOLD)
1039 >                        treeifyBin(tab, i);
1040 >                    if (oldVal != null)
1041 >                        return oldVal;
1042                      break;
1043                  }
782                else
783                    c = getState();
1044              }
785            return r == null ? null : r.val;
1045          }
1046 +        addCount(1L, binCount);
1047 +        return null;
1048 +    }
1049  
1050 <        /**
1051 <         * Finds or adds a node.
1052 <         * @return null if added
1053 <         */
1054 <        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
1055 <            (int h, Object k, V v) {
1056 <            Class<?> c = k.getClass();
1057 <            TreeNode<V> pp = root, p = null;
1058 <            int dir = 0;
1059 <            while (pp != null) { // find existing node or leaf to insert at
1060 <                int ph;  Object pk; Class<?> pc;
1061 <                p = pp;
800 <                if ((ph = p.hash) == h) {
801 <                    if ((pk = p.key) == k || k.equals(pk))
802 <                        return p;
803 <                    if (c != (pc = pk.getClass()) ||
804 <                        !(k instanceof Comparable) ||
805 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
806 <                        TreeNode<V> s = null, r = null, pr;
807 <                        if ((dir = (c == pc) ? 0 :
808 <                             c.getName().compareTo(pc.getName())) == 0) {
809 <                            if ((pr = p.right) != null && h >= pr.hash &&
810 <                                (r = getTreeNode(h, k, pr)) != null)
811 <                                return r;
812 <                            else // continue left
813 <                                dir = -1;
814 <                        }
815 <                        else if ((pr = p.right) != null && h >= pr.hash)
816 <                            s = pr;
817 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
818 <                            return r;
819 <                    }
820 <                }
821 <                else
822 <                    dir = (h < ph) ? -1 : 1;
823 <                pp = (dir > 0) ? p.right : p.left;
824 <            }
1050 >    /**
1051 >     * Copies all of the mappings from the specified map to this one.
1052 >     * These mappings replace any mappings that this map had for any of the
1053 >     * keys currently in the specified map.
1054 >     *
1055 >     * @param m mappings to be stored in this map
1056 >     */
1057 >    public void putAll(Map<? extends K, ? extends V> m) {
1058 >        tryPresize(m.size());
1059 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1060 >            putVal(e.getKey(), e.getValue(), false);
1061 >    }
1062  
1063 <            TreeNode<V> f = first;
1064 <            TreeNode<V> x = first = new TreeNode<V>(h, k, v, f, p);
1065 <            if (p == null)
1066 <                root = x;
1067 <            else { // attach and rebalance; adapted from CLR
1068 <                TreeNode<V> xp, xpp;
1069 <                if (f != null)
1070 <                    f.prev = x;
1071 <                if (dir <= 0)
1072 <                    p.left = x;
1073 <                else
1074 <                    p.right = x;
1075 <                x.red = true;
1076 <                while (x != null && (xp = x.parent) != null && xp.red &&
1077 <                       (xpp = xp.parent) != null) {
1078 <                    TreeNode<V> xppl = xpp.left;
1079 <                    if (xp == xppl) {
1080 <                        TreeNode<V> y = xpp.right;
1081 <                        if (y != null && y.red) {
1082 <                            y.red = false;
1083 <                            xp.red = false;
1084 <                            xpp.red = true;
1085 <                            x = xpp;
1086 <                        }
1087 <                        else {
1088 <                            if (x == xp.right) {
1089 <                                rotateLeft(x = xp);
1090 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
1091 <                            }
1092 <                            if (xp != null) {
1093 <                                xp.red = false;
1094 <                                if (xpp != null) {
1095 <                                    xpp.red = true;
1096 <                                    rotateRight(xpp);
1063 >    /**
1064 >     * Removes the key (and its corresponding value) from this map.
1065 >     * This method does nothing if the key is not in the map.
1066 >     *
1067 >     * @param  key the key that needs to be removed
1068 >     * @return the previous value associated with {@code key}, or
1069 >     *         {@code null} if there was no mapping for {@code key}
1070 >     * @throws NullPointerException if the specified key is null
1071 >     */
1072 >    public V remove(Object key) {
1073 >        return replaceNode(key, null, null);
1074 >    }
1075 >
1076 >    /**
1077 >     * Implementation for the four public remove/replace methods:
1078 >     * Replaces node value with v, conditional upon match of cv if
1079 >     * non-null.  If resulting value is null, delete.
1080 >     */
1081 >    final V replaceNode(Object key, V value, Object cv) {
1082 >        int hash = spread(key.hashCode());
1083 >        for (Node<K,V>[] tab = table;;) {
1084 >            Node<K,V> f; int n, i, fh;
1085 >            if (tab == null || (n = tab.length) == 0 ||
1086 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1087 >                break;
1088 >            else if ((fh = f.hash) == MOVED)
1089 >                tab = helpTransfer(tab, f);
1090 >            else {
1091 >                V oldVal = null;
1092 >                boolean validated = false;
1093 >                synchronized (f) {
1094 >                    if (tabAt(tab, i) == f) {
1095 >                        if (fh >= 0) {
1096 >                            validated = true;
1097 >                            for (Node<K,V> e = f, pred = null;;) {
1098 >                                K ek;
1099 >                                if (e.hash == hash &&
1100 >                                    ((ek = e.key) == key ||
1101 >                                     (ek != null && key.equals(ek)))) {
1102 >                                    V ev = e.val;
1103 >                                    if (cv == null || cv == ev ||
1104 >                                        (ev != null && cv.equals(ev))) {
1105 >                                        oldVal = ev;
1106 >                                        if (value != null)
1107 >                                            e.val = value;
1108 >                                        else if (pred != null)
1109 >                                            pred.next = e.next;
1110 >                                        else
1111 >                                            setTabAt(tab, i, e.next);
1112 >                                    }
1113 >                                    break;
1114                                  }
1115 +                                pred = e;
1116 +                                if ((e = e.next) == null)
1117 +                                    break;
1118                              }
1119                          }
1120 <                    }
1121 <                    else {
1122 <                        TreeNode<V> y = xppl;
1123 <                        if (y != null && y.red) {
1124 <                            y.red = false;
1125 <                            xp.red = false;
1126 <                            xpp.red = true;
1127 <                            x = xpp;
1128 <                        }
1129 <                        else {
1130 <                            if (x == xp.left) {
1131 <                                rotateRight(x = xp);
1132 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
1133 <                            }
877 <                            if (xp != null) {
878 <                                xp.red = false;
879 <                                if (xpp != null) {
880 <                                    xpp.red = true;
881 <                                    rotateLeft(xpp);
1120 >                        else if (f instanceof TreeBin) {
1121 >                            validated = true;
1122 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1123 >                            TreeNode<K,V> r, p;
1124 >                            if ((r = t.root) != null &&
1125 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1126 >                                V pv = p.val;
1127 >                                if (cv == null || cv == pv ||
1128 >                                    (pv != null && cv.equals(pv))) {
1129 >                                    oldVal = pv;
1130 >                                    if (value != null)
1131 >                                        p.val = value;
1132 >                                    else if (t.removeTreeNode(p))
1133 >                                        setTabAt(tab, i, untreeify(t.first));
1134                                  }
1135                              }
1136                          }
1137 +                        else if (f instanceof ReservationNode)
1138 +                            throw new IllegalStateException("Recursive update");
1139                      }
1140                  }
1141 <                TreeNode<V> r = root;
1142 <                if (r != null && r.red)
1143 <                    r.red = false;
1144 <            }
1145 <            return null;
892 <        }
893 <
894 <        /**
895 <         * Removes the given node, that must be present before this
896 <         * call.  This is messier than typical red-black deletion code
897 <         * because we cannot swap the contents of an interior node
898 <         * with a leaf successor that is pinned by "next" pointers
899 <         * that are accessible independently of lock. So instead we
900 <         * swap the tree linkages.
901 <         */
902 <        final void deleteTreeNode(TreeNode<V> p) {
903 <            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
904 <            TreeNode<V> pred = p.prev;
905 <            if (pred == null)
906 <                first = next;
907 <            else
908 <                pred.next = next;
909 <            if (next != null)
910 <                next.prev = pred;
911 <            TreeNode<V> replacement;
912 <            TreeNode<V> pl = p.left;
913 <            TreeNode<V> pr = p.right;
914 <            if (pl != null && pr != null) {
915 <                TreeNode<V> s = pr, sl;
916 <                while ((sl = s.left) != null) // find successor
917 <                    s = sl;
918 <                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
919 <                TreeNode<V> sr = s.right;
920 <                TreeNode<V> pp = p.parent;
921 <                if (s == pr) { // p was s's direct parent
922 <                    p.parent = s;
923 <                    s.right = p;
924 <                }
925 <                else {
926 <                    TreeNode<V> sp = s.parent;
927 <                    if ((p.parent = sp) != null) {
928 <                        if (s == sp.left)
929 <                            sp.left = p;
930 <                        else
931 <                            sp.right = p;
1141 >                if (validated) {
1142 >                    if (oldVal != null) {
1143 >                        if (value == null)
1144 >                            addCount(-1L, -1);
1145 >                        return oldVal;
1146                      }
1147 <                    if ((s.right = pr) != null)
934 <                        pr.parent = s;
1147 >                    break;
1148                  }
936                p.left = null;
937                if ((p.right = sr) != null)
938                    sr.parent = p;
939                if ((s.left = pl) != null)
940                    pl.parent = s;
941                if ((s.parent = pp) == null)
942                    root = s;
943                else if (p == pp.left)
944                    pp.left = s;
945                else
946                    pp.right = s;
947                replacement = sr;
1149              }
1150 <            else
1151 <                replacement = (pl != null) ? pl : pr;
1152 <            TreeNode<V> pp = p.parent;
1153 <            if (replacement == null) {
1154 <                if (pp == null) {
1155 <                    root = null;
1156 <                    return;
1157 <                }
1158 <                replacement = p;
1150 >        }
1151 >        return null;
1152 >    }
1153 >
1154 >    /**
1155 >     * Removes all of the mappings from this map.
1156 >     */
1157 >    public void clear() {
1158 >        long delta = 0L; // negative number of deletions
1159 >        int i = 0;
1160 >        Node<K,V>[] tab = table;
1161 >        while (tab != null && i < tab.length) {
1162 >            int fh;
1163 >            Node<K,V> f = tabAt(tab, i);
1164 >            if (f == null)
1165 >                ++i;
1166 >            else if ((fh = f.hash) == MOVED) {
1167 >                tab = helpTransfer(tab, f);
1168 >                i = 0; // restart
1169              }
1170              else {
1171 <                replacement.parent = pp;
1172 <                if (pp == null)
1173 <                    root = replacement;
1174 <                else if (p == pp.left)
1175 <                    pp.left = replacement;
1176 <                else
1177 <                    pp.right = replacement;
1178 <                p.left = p.right = p.parent = null;
968 <            }
969 <            if (!p.red) { // rebalance, from CLR
970 <                TreeNode<V> x = replacement;
971 <                while (x != null) {
972 <                    TreeNode<V> xp, xpl;
973 <                    if (x.red || (xp = x.parent) == null) {
974 <                        x.red = false;
975 <                        break;
976 <                    }
977 <                    if (x == (xpl = xp.left)) {
978 <                        TreeNode<V> sib = xp.right;
979 <                        if (sib != null && sib.red) {
980 <                            sib.red = false;
981 <                            xp.red = true;
982 <                            rotateLeft(xp);
983 <                            sib = (xp = x.parent) == null ? null : xp.right;
984 <                        }
985 <                        if (sib == null)
986 <                            x = xp;
987 <                        else {
988 <                            TreeNode<V> sl = sib.left, sr = sib.right;
989 <                            if ((sr == null || !sr.red) &&
990 <                                (sl == null || !sl.red)) {
991 <                                sib.red = true;
992 <                                x = xp;
993 <                            }
994 <                            else {
995 <                                if (sr == null || !sr.red) {
996 <                                    if (sl != null)
997 <                                        sl.red = false;
998 <                                    sib.red = true;
999 <                                    rotateRight(sib);
1000 <                                    sib = (xp = x.parent) == null ?
1001 <                                        null : xp.right;
1002 <                                }
1003 <                                if (sib != null) {
1004 <                                    sib.red = (xp == null) ? false : xp.red;
1005 <                                    if ((sr = sib.right) != null)
1006 <                                        sr.red = false;
1007 <                                }
1008 <                                if (xp != null) {
1009 <                                    xp.red = false;
1010 <                                    rotateLeft(xp);
1011 <                                }
1012 <                                x = root;
1013 <                            }
1014 <                        }
1015 <                    }
1016 <                    else { // symmetric
1017 <                        TreeNode<V> sib = xpl;
1018 <                        if (sib != null && sib.red) {
1019 <                            sib.red = false;
1020 <                            xp.red = true;
1021 <                            rotateRight(xp);
1022 <                            sib = (xp = x.parent) == null ? null : xp.left;
1023 <                        }
1024 <                        if (sib == null)
1025 <                            x = xp;
1026 <                        else {
1027 <                            TreeNode<V> sl = sib.left, sr = sib.right;
1028 <                            if ((sl == null || !sl.red) &&
1029 <                                (sr == null || !sr.red)) {
1030 <                                sib.red = true;
1031 <                                x = xp;
1032 <                            }
1033 <                            else {
1034 <                                if (sl == null || !sl.red) {
1035 <                                    if (sr != null)
1036 <                                        sr.red = false;
1037 <                                    sib.red = true;
1038 <                                    rotateLeft(sib);
1039 <                                    sib = (xp = x.parent) == null ?
1040 <                                        null : xp.left;
1041 <                                }
1042 <                                if (sib != null) {
1043 <                                    sib.red = (xp == null) ? false : xp.red;
1044 <                                    if ((sl = sib.left) != null)
1045 <                                        sl.red = false;
1046 <                                }
1047 <                                if (xp != null) {
1048 <                                    xp.red = false;
1049 <                                    rotateRight(xp);
1050 <                                }
1051 <                                x = root;
1052 <                            }
1171 >                synchronized (f) {
1172 >                    if (tabAt(tab, i) == f) {
1173 >                        Node<K,V> p = (fh >= 0 ? f :
1174 >                                       (f instanceof TreeBin) ?
1175 >                                       ((TreeBin<K,V>)f).first : null);
1176 >                        while (p != null) {
1177 >                            --delta;
1178 >                            p = p.next;
1179                          }
1180 +                        setTabAt(tab, i++, null);
1181                      }
1182                  }
1183              }
1057            if (p == replacement && (pp = p.parent) != null) {
1058                if (p == pp.left) // detach pointers
1059                    pp.left = null;
1060                else if (p == pp.right)
1061                    pp.right = null;
1062                p.parent = null;
1063            }
1184          }
1185 +        if (delta != 0L)
1186 +            addCount(delta, -1);
1187      }
1188  
1189 <    /* ---------------- Collision reduction methods -------------- */
1189 >    /**
1190 >     * Returns a {@link Set} view of the keys contained in this map.
1191 >     * The set is backed by the map, so changes to the map are
1192 >     * reflected in the set, and vice-versa. The set supports element
1193 >     * removal, which removes the corresponding mapping from this map,
1194 >     * via the {@code Iterator.remove}, {@code Set.remove},
1195 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1196 >     * operations.  It does not support the {@code add} or
1197 >     * {@code addAll} operations.
1198 >     *
1199 >     * <p>The view's iterators and spliterators are
1200 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1201 >     *
1202 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1203 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1204 >     *
1205 >     * @return the set view
1206 >     */
1207 >    public KeySetView<K,V> keySet() {
1208 >        KeySetView<K,V> ks;
1209 >        if ((ks = keySet) != null) return ks;
1210 >        return keySet = new KeySetView<K,V>(this, null);
1211 >    }
1212  
1213      /**
1214 <     * Spreads higher bits to lower, and also forces top bit to 0.
1215 <     * Because the table uses power-of-two masking, sets of hashes
1216 <     * that vary only in bits above the current mask will always
1217 <     * collide. (Among known examples are sets of Float keys holding
1218 <     * consecutive whole numbers in small tables.)  To counter this,
1219 <     * we apply a transform that spreads the impact of higher bits
1220 <     * downward. There is a tradeoff between speed, utility, and
1221 <     * quality of bit-spreading. Because many common sets of hashes
1222 <     * are already reasonably distributed across bits (so don't benefit
1223 <     * from spreading), and because we use trees to handle large sets
1224 <     * of collisions in bins, we don't need excessively high quality.
1214 >     * Returns a {@link Collection} view of the values contained in this map.
1215 >     * The collection is backed by the map, so changes to the map are
1216 >     * reflected in the collection, and vice-versa.  The collection
1217 >     * supports element removal, which removes the corresponding
1218 >     * mapping from this map, via the {@code Iterator.remove},
1219 >     * {@code Collection.remove}, {@code removeAll},
1220 >     * {@code retainAll}, and {@code clear} operations.  It does not
1221 >     * support the {@code add} or {@code addAll} operations.
1222 >     *
1223 >     * <p>The view's iterators and spliterators are
1224 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1225 >     *
1226 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}
1227 >     * and {@link Spliterator#NONNULL}.
1228 >     *
1229 >     * @return the collection view
1230 >     */
1231 >    public Collection<V> values() {
1232 >        ValuesView<K,V> vs;
1233 >        if ((vs = values) != null) return vs;
1234 >        return values = new ValuesView<K,V>(this);
1235 >    }
1236 >
1237 >    /**
1238 >     * Returns a {@link Set} view of the mappings contained in this map.
1239 >     * The set is backed by the map, so changes to the map are
1240 >     * reflected in the set, and vice-versa.  The set supports element
1241 >     * removal, which removes the corresponding mapping from the map,
1242 >     * via the {@code Iterator.remove}, {@code Set.remove},
1243 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1244 >     * operations.
1245 >     *
1246 >     * <p>The view's iterators and spliterators are
1247 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1248 >     *
1249 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1250 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1251 >     *
1252 >     * @return the set view
1253 >     */
1254 >    public Set<Map.Entry<K,V>> entrySet() {
1255 >        EntrySetView<K,V> es;
1256 >        if ((es = entrySet) != null) return es;
1257 >        return entrySet = new EntrySetView<K,V>(this);
1258 >    }
1259 >
1260 >    /**
1261 >     * Returns the hash code value for this {@link Map}, i.e.,
1262 >     * the sum of, for each key-value pair in the map,
1263 >     * {@code key.hashCode() ^ value.hashCode()}.
1264 >     *
1265 >     * @return the hash code value for this map
1266 >     */
1267 >    public int hashCode() {
1268 >        int h = 0;
1269 >        Node<K,V>[] t;
1270 >        if ((t = table) != null) {
1271 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1272 >            for (Node<K,V> p; (p = it.advance()) != null; )
1273 >                h += p.key.hashCode() ^ p.val.hashCode();
1274 >        }
1275 >        return h;
1276 >    }
1277 >
1278 >    /**
1279 >     * Returns a string representation of this map.  The string
1280 >     * representation consists of a list of key-value mappings (in no
1281 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1282 >     * mappings are separated by the characters {@code ", "} (comma
1283 >     * and space).  Each key-value mapping is rendered as the key
1284 >     * followed by an equals sign ("{@code =}") followed by the
1285 >     * associated value.
1286 >     *
1287 >     * @return a string representation of this map
1288       */
1289 <    private static final int spread(int h) {
1290 <        h ^= (h >>> 18) ^ (h >>> 12);
1291 <        return (h ^ (h >>> 10)) & HASH_BITS;
1289 >    public String toString() {
1290 >        Node<K,V>[] t;
1291 >        int f = (t = table) == null ? 0 : t.length;
1292 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1293 >        StringBuilder sb = new StringBuilder();
1294 >        sb.append('{');
1295 >        Node<K,V> p;
1296 >        if ((p = it.advance()) != null) {
1297 >            for (;;) {
1298 >                K k = p.key;
1299 >                V v = p.val;
1300 >                sb.append(k == this ? "(this Map)" : k);
1301 >                sb.append('=');
1302 >                sb.append(v == this ? "(this Map)" : v);
1303 >                if ((p = it.advance()) == null)
1304 >                    break;
1305 >                sb.append(',').append(' ');
1306 >            }
1307 >        }
1308 >        return sb.append('}').toString();
1309      }
1310  
1311      /**
1312 <     * Replaces a list bin with a tree bin if key is comparable.  Call
1313 <     * only when locked.
1312 >     * Compares the specified object with this map for equality.
1313 >     * Returns {@code true} if the given object is a map with the same
1314 >     * mappings as this map.  This operation may return misleading
1315 >     * results if either map is concurrently modified during execution
1316 >     * of this method.
1317 >     *
1318 >     * @param o object to be compared for equality with this map
1319 >     * @return {@code true} if the specified object is equal to this map
1320       */
1321 <    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1322 <        if (key instanceof Comparable) {
1323 <            TreeBin<V> t = new TreeBin<V>();
1324 <            for (Node<V> e = tabAt(tab, index); e != null; e = e.next)
1325 <                t.putTreeNode(e.hash, e.key, e.val);
1326 <            setTabAt(tab, index, new Node<V>(MOVED, t, null, null));
1321 >    public boolean equals(Object o) {
1322 >        if (o != this) {
1323 >            if (!(o instanceof Map))
1324 >                return false;
1325 >            Map<?,?> m = (Map<?,?>) o;
1326 >            Node<K,V>[] t;
1327 >            int f = (t = table) == null ? 0 : t.length;
1328 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1329 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1330 >                V val = p.val;
1331 >                Object v = m.get(p.key);
1332 >                if (v == null || (v != val && !v.equals(val)))
1333 >                    return false;
1334 >            }
1335 >            for (Map.Entry<?,?> e : m.entrySet()) {
1336 >                Object mk, mv, v;
1337 >                if ((mk = e.getKey()) == null ||
1338 >                    (mv = e.getValue()) == null ||
1339 >                    (v = get(mk)) == null ||
1340 >                    (mv != v && !mv.equals(v)))
1341 >                    return false;
1342 >            }
1343          }
1344 +        return true;
1345      }
1346  
1347 <    /* ---------------- Internal access and update methods -------------- */
1347 >    /**
1348 >     * Stripped-down version of helper class used in previous version,
1349 >     * declared for the sake of serialization compatibility.
1350 >     */
1351 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1352 >        private static final long serialVersionUID = 2249069246763182397L;
1353 >        final float loadFactor;
1354 >        Segment(float lf) { this.loadFactor = lf; }
1355 >    }
1356  
1357 <    /** Implementation for get and containsKey */
1358 <    @SuppressWarnings("unchecked") private final V internalGet(Object k) {
1359 <        int h = spread(k.hashCode());
1360 <        retry: for (Node<V>[] tab = table; tab != null;) {
1361 <            Node<V> e; Object ek; V ev; int eh; // locals to read fields once
1362 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1363 <                if ((eh = e.hash) < 0) {
1364 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1365 <                        return ((TreeBin<V>)ek).getValue(h, k);
1366 <                    else {                      // restart with new table
1367 <                        tab = (Node<V>[])ek;
1368 <                        continue retry;
1369 <                    }
1370 <                }
1371 <                else if (eh == h && (ev = e.val) != null &&
1372 <                         ((ek = e.key) == k || k.equals(ek)))
1373 <                    return ev;
1357 >    /**
1358 >     * Saves this map to a stream (that is, serializes it).
1359 >     *
1360 >     * @param s the stream
1361 >     * @throws java.io.IOException if an I/O error occurs
1362 >     * @serialData
1363 >     * the serialized fields, followed by the key (Object) and value
1364 >     * (Object) for each key-value mapping, followed by a null pair.
1365 >     * The key-value mappings are emitted in no particular order.
1366 >     */
1367 >    private void writeObject(java.io.ObjectOutputStream s)
1368 >        throws java.io.IOException {
1369 >        // For serialization compatibility
1370 >        // Emulate segment calculation from previous version of this class
1371 >        int sshift = 0;
1372 >        int ssize = 1;
1373 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1374 >            ++sshift;
1375 >            ssize <<= 1;
1376 >        }
1377 >        int segmentShift = 32 - sshift;
1378 >        int segmentMask = ssize - 1;
1379 >        @SuppressWarnings("unchecked")
1380 >        Segment<K,V>[] segments = (Segment<K,V>[])
1381 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1382 >        for (int i = 0; i < segments.length; ++i)
1383 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1384 >        java.io.ObjectOutputStream.PutField streamFields = s.putFields();
1385 >        streamFields.put("segments", segments);
1386 >        streamFields.put("segmentShift", segmentShift);
1387 >        streamFields.put("segmentMask", segmentMask);
1388 >        s.writeFields();
1389 >
1390 >        Node<K,V>[] t;
1391 >        if ((t = table) != null) {
1392 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1393 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1394 >                s.writeObject(p.key);
1395 >                s.writeObject(p.val);
1396              }
1120            break;
1397          }
1398 <        return null;
1398 >        s.writeObject(null);
1399 >        s.writeObject(null);
1400      }
1401  
1402      /**
1403 <     * Implementation for the four public remove/replace methods:
1404 <     * Replaces node value with v, conditional upon match of cv if
1405 <     * non-null.  If resulting value is null, delete.
1403 >     * Reconstitutes this map from a stream (that is, deserializes it).
1404 >     * @param s the stream
1405 >     * @throws ClassNotFoundException if the class of a serialized object
1406 >     *         could not be found
1407 >     * @throws java.io.IOException if an I/O error occurs
1408       */
1409 <    @SuppressWarnings("unchecked") private final V internalReplace
1410 <        (Object k, V v, Object cv) {
1411 <        int h = spread(k.hashCode());
1412 <        V oldVal = null;
1413 <        for (Node<V>[] tab = table;;) {
1414 <            Node<V> f; int i, fh; Object fk;
1415 <            if (tab == null ||
1416 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1409 >    private void readObject(java.io.ObjectInputStream s)
1410 >        throws java.io.IOException, ClassNotFoundException {
1411 >        /*
1412 >         * To improve performance in typical cases, we create nodes
1413 >         * while reading, then place in table once size is known.
1414 >         * However, we must also validate uniqueness and deal with
1415 >         * overpopulated bins while doing so, which requires
1416 >         * specialized versions of putVal mechanics.
1417 >         */
1418 >        sizeCtl = -1; // force exclusion for table construction
1419 >        s.defaultReadObject();
1420 >        long size = 0L;
1421 >        Node<K,V> p = null;
1422 >        for (;;) {
1423 >            @SuppressWarnings("unchecked")
1424 >            K k = (K) s.readObject();
1425 >            @SuppressWarnings("unchecked")
1426 >            V v = (V) s.readObject();
1427 >            if (k != null && v != null) {
1428 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1429 >                ++size;
1430 >            }
1431 >            else
1432                  break;
1433 <            else if ((fh = f.hash) < 0) {
1434 <                if ((fk = f.key) instanceof TreeBin) {
1435 <                    TreeBin<V> t = (TreeBin<V>)fk;
1436 <                    boolean validated = false;
1437 <                    boolean deleted = false;
1438 <                    t.acquire(0);
1439 <                    try {
1440 <                        if (tabAt(tab, i) == f) {
1441 <                            validated = true;
1442 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1443 <                            if (p != null) {
1444 <                                V pv = p.val;
1445 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1446 <                                    oldVal = pv;
1447 <                                    if ((p.val = v) == null) {
1448 <                                        deleted = true;
1449 <                                        t.deleteTreeNode(p);
1450 <                                    }
1451 <                                }
1452 <                            }
1453 <                        }
1454 <                    } finally {
1455 <                        t.release(0);
1456 <                    }
1163 <                    if (validated) {
1164 <                        if (deleted)
1165 <                            addCount(-1L, -1);
1166 <                        break;
1433 >        }
1434 >        if (size == 0L)
1435 >            sizeCtl = 0;
1436 >        else {
1437 >            long ts = (long)(1.0 + size / LOAD_FACTOR);
1438 >            int n = (ts >= (long)MAXIMUM_CAPACITY) ?
1439 >                MAXIMUM_CAPACITY : tableSizeFor((int)ts);
1440 >            @SuppressWarnings("unchecked")
1441 >            Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1442 >            int mask = n - 1;
1443 >            long added = 0L;
1444 >            while (p != null) {
1445 >                boolean insertAtFront;
1446 >                Node<K,V> next = p.next, first;
1447 >                int h = p.hash, j = h & mask;
1448 >                if ((first = tabAt(tab, j)) == null)
1449 >                    insertAtFront = true;
1450 >                else {
1451 >                    K k = p.key;
1452 >                    if (first.hash < 0) {
1453 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1454 >                        if (t.putTreeVal(h, k, p.val) == null)
1455 >                            ++added;
1456 >                        insertAtFront = false;
1457                      }
1458 <                }
1459 <                else
1460 <                    tab = (Node<V>[])fk;
1461 <            }
1462 <            else if (fh != h && f.next == null) // precheck
1463 <                break;                          // rules out possible existence
1464 <            else {
1465 <                boolean validated = false;
1466 <                boolean deleted = false;
1177 <                synchronized (f) {
1178 <                    if (tabAt(tab, i) == f) {
1179 <                        validated = true;
1180 <                        for (Node<V> e = f, pred = null;;) {
1181 <                            Object ek; V ev;
1182 <                            if (e.hash == h &&
1183 <                                ((ev = e.val) != null) &&
1184 <                                ((ek = e.key) == k || k.equals(ek))) {
1185 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1186 <                                    oldVal = ev;
1187 <                                    if ((e.val = v) == null) {
1188 <                                        deleted = true;
1189 <                                        Node<V> en = e.next;
1190 <                                        if (pred != null)
1191 <                                            pred.next = en;
1192 <                                        else
1193 <                                            setTabAt(tab, i, en);
1194 <                                    }
1195 <                                }
1458 >                    else {
1459 >                        int binCount = 0;
1460 >                        insertAtFront = true;
1461 >                        Node<K,V> q; K qk;
1462 >                        for (q = first; q != null; q = q.next) {
1463 >                            if (q.hash == h &&
1464 >                                ((qk = q.key) == k ||
1465 >                                 (qk != null && k.equals(qk)))) {
1466 >                                insertAtFront = false;
1467                                  break;
1468                              }
1469 <                            pred = e;
1470 <                            if ((e = e.next) == null)
1471 <                                break;
1469 >                            ++binCount;
1470 >                        }
1471 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1472 >                            insertAtFront = false;
1473 >                            ++added;
1474 >                            p.next = first;
1475 >                            TreeNode<K,V> hd = null, tl = null;
1476 >                            for (q = p; q != null; q = q.next) {
1477 >                                TreeNode<K,V> t = new TreeNode<K,V>
1478 >                                    (q.hash, q.key, q.val, null, null);
1479 >                                if ((t.prev = tl) == null)
1480 >                                    hd = t;
1481 >                                else
1482 >                                    tl.next = t;
1483 >                                tl = t;
1484 >                            }
1485 >                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1486                          }
1487                      }
1488                  }
1489 <                if (validated) {
1490 <                    if (deleted)
1491 <                        addCount(-1L, -1);
1492 <                    break;
1489 >                if (insertAtFront) {
1490 >                    ++added;
1491 >                    p.next = first;
1492 >                    setTabAt(tab, j, p);
1493                  }
1494 +                p = next;
1495              }
1496 +            table = tab;
1497 +            sizeCtl = n - (n >>> 2);
1498 +            baseCount = added;
1499          }
1211        return oldVal;
1500      }
1501  
1502 <    /*
1503 <     * Internal versions of insertion methods
1504 <     * All have the same basic structure as the first (internalPut):
1505 <     *  1. If table uninitialized, create
1506 <     *  2. If bin empty, try to CAS new node
1507 <     *  3. If bin stale, use new table
1508 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1509 <     *  5. Lock and validate; if valid, scan and add or update
1222 <     *
1223 <     * The putAll method differs mainly in attempting to pre-allocate
1224 <     * enough table space, and also more lazily performs count updates
1225 <     * and checks.
1226 <     *
1227 <     * Most of the function-accepting methods can't be factored nicely
1228 <     * because they require different functional forms, so instead
1229 <     * sprawl out similar mechanics.
1502 >    // ConcurrentMap methods
1503 >
1504 >    /**
1505 >     * {@inheritDoc}
1506 >     *
1507 >     * @return the previous value associated with the specified key,
1508 >     *         or {@code null} if there was no mapping for the key
1509 >     * @throws NullPointerException if the specified key or value is null
1510       */
1511 +    public V putIfAbsent(K key, V value) {
1512 +        return putVal(key, value, true);
1513 +    }
1514  
1515 <    /** Implementation for put and putIfAbsent */
1516 <    @SuppressWarnings("unchecked") private final V internalPut
1517 <        (K k, V v, boolean onlyIfAbsent) {
1518 <        if (k == null || v == null) throw new NullPointerException();
1519 <        int h = spread(k.hashCode());
1520 <        int len = 0;
1521 <        for (Node<V>[] tab = table;;) {
1522 <            int i, fh; Node<V> f; Object fk; V fv;
1523 <            if (tab == null)
1524 <                tab = initTable();
1525 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1526 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1527 <                    break;                   // no lock when adding to empty bin
1515 >    /**
1516 >     * {@inheritDoc}
1517 >     *
1518 >     * @throws NullPointerException if the specified key is null
1519 >     */
1520 >    public boolean remove(Object key, Object value) {
1521 >        if (key == null)
1522 >            throw new NullPointerException();
1523 >        return value != null && replaceNode(key, null, value) != null;
1524 >    }
1525 >
1526 >    /**
1527 >     * {@inheritDoc}
1528 >     *
1529 >     * @throws NullPointerException if any of the arguments are null
1530 >     */
1531 >    public boolean replace(K key, V oldValue, V newValue) {
1532 >        if (key == null || oldValue == null || newValue == null)
1533 >            throw new NullPointerException();
1534 >        return replaceNode(key, newValue, oldValue) != null;
1535 >    }
1536 >
1537 >    /**
1538 >     * {@inheritDoc}
1539 >     *
1540 >     * @return the previous value associated with the specified key,
1541 >     *         or {@code null} if there was no mapping for the key
1542 >     * @throws NullPointerException if the specified key or value is null
1543 >     */
1544 >    public V replace(K key, V value) {
1545 >        if (key == null || value == null)
1546 >            throw new NullPointerException();
1547 >        return replaceNode(key, value, null);
1548 >    }
1549 >
1550 >    // Overrides of JDK8+ Map extension method defaults
1551 >
1552 >    /**
1553 >     * Returns the value to which the specified key is mapped, or the
1554 >     * given default value if this map contains no mapping for the
1555 >     * key.
1556 >     *
1557 >     * @param key the key whose associated value is to be returned
1558 >     * @param defaultValue the value to return if this map contains
1559 >     * no mapping for the given key
1560 >     * @return the mapping for the key, if present; else the default value
1561 >     * @throws NullPointerException if the specified key is null
1562 >     */
1563 >    public V getOrDefault(Object key, V defaultValue) {
1564 >        V v;
1565 >        return (v = get(key)) == null ? defaultValue : v;
1566 >    }
1567 >
1568 >    public void forEach(BiConsumer<? super K, ? super V> action) {
1569 >        if (action == null) throw new NullPointerException();
1570 >        Node<K,V>[] t;
1571 >        if ((t = table) != null) {
1572 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1573 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1574 >                action.accept(p.key, p.val);
1575              }
1576 <            else if ((fh = f.hash) < 0) {
1577 <                if ((fk = f.key) instanceof TreeBin) {
1578 <                    TreeBin<V> t = (TreeBin<V>)fk;
1579 <                    V oldVal = null;
1580 <                    t.acquire(0);
1581 <                    try {
1582 <                        if (tabAt(tab, i) == f) {
1583 <                            len = 2;
1584 <                            TreeNode<V> p = t.putTreeNode(h, k, v);
1585 <                            if (p != null) {
1586 <                                oldVal = p.val;
1587 <                                if (!onlyIfAbsent)
1588 <                                    p.val = v;
1589 <                            }
1590 <                        }
1591 <                    } finally {
1262 <                        t.release(0);
1263 <                    }
1264 <                    if (len != 0) {
1265 <                        if (oldVal != null)
1266 <                            return oldVal;
1576 >        }
1577 >    }
1578 >
1579 >    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1580 >        if (function == null) throw new NullPointerException();
1581 >        Node<K,V>[] t;
1582 >        if ((t = table) != null) {
1583 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1584 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1585 >                V oldValue = p.val;
1586 >                for (K key = p.key;;) {
1587 >                    V newValue = function.apply(key, oldValue);
1588 >                    if (newValue == null)
1589 >                        throw new NullPointerException();
1590 >                    if (replaceNode(key, newValue, oldValue) != null ||
1591 >                        (oldValue = get(key)) == null)
1592                          break;
1268                    }
1593                  }
1270                else
1271                    tab = (Node<V>[])fk;
1594              }
1595 <            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1596 <                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1597 <                return fv;
1598 <            else {
1599 <                V oldVal = null;
1600 <                synchronized (f) {
1601 <                    if (tabAt(tab, i) == f) {
1602 <                        len = 1;
1603 <                        for (Node<V> e = f;; ++len) {
1604 <                            Object ek; V ev;
1605 <                            if (e.hash == h &&
1606 <                                (ev = e.val) != null &&
1607 <                                ((ek = e.key) == k || k.equals(ek))) {
1608 <                                oldVal = ev;
1609 <                                if (!onlyIfAbsent)
1610 <                                    e.val = v;
1611 <                                break;
1612 <                            }
1291 <                            Node<V> last = e;
1292 <                            if ((e = e.next) == null) {
1293 <                                last.next = new Node<V>(h, k, v, null);
1294 <                                if (len >= TREE_THRESHOLD)
1295 <                                    replaceWithTreeBin(tab, i, k);
1296 <                                break;
1297 <                            }
1298 <                        }
1299 <                    }
1300 <                }
1301 <                if (len != 0) {
1302 <                    if (oldVal != null)
1303 <                        return oldVal;
1304 <                    break;
1305 <                }
1595 >        }
1596 >    }
1597 >
1598 >    /**
1599 >     * Helper method for EntrySetView.removeIf.
1600 >     */
1601 >    boolean removeEntryIf(Predicate<? super Entry<K,V>> function) {
1602 >        if (function == null) throw new NullPointerException();
1603 >        Node<K,V>[] t;
1604 >        boolean removed = false;
1605 >        if ((t = table) != null) {
1606 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1607 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1608 >                K k = p.key;
1609 >                V v = p.val;
1610 >                Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v);
1611 >                if (function.test(e) && replaceNode(k, null, v) != null)
1612 >                    removed = true;
1613              }
1614          }
1615 <        addCount(1L, len);
1309 <        return null;
1615 >        return removed;
1616      }
1617  
1618 <    /** Implementation for computeIfAbsent */
1619 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1620 <        (K k, Function<? super K, ? extends V> mf) {
1621 <        if (k == null || mf == null)
1618 >    /**
1619 >     * Helper method for ValuesView.removeIf.
1620 >     */
1621 >    boolean removeValueIf(Predicate<? super V> function) {
1622 >        if (function == null) throw new NullPointerException();
1623 >        Node<K,V>[] t;
1624 >        boolean removed = false;
1625 >        if ((t = table) != null) {
1626 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1627 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1628 >                K k = p.key;
1629 >                V v = p.val;
1630 >                if (function.test(v) && replaceNode(k, null, v) != null)
1631 >                    removed = true;
1632 >            }
1633 >        }
1634 >        return removed;
1635 >    }
1636 >
1637 >    /**
1638 >     * If the specified key is not already associated with a value,
1639 >     * attempts to compute its value using the given mapping function
1640 >     * and enters it into this map unless {@code null}.  The entire
1641 >     * method invocation is performed atomically.  The supplied
1642 >     * function is invoked exactly once per invocation of this method
1643 >     * if the key is absent, else not at all.  Some attempted update
1644 >     * operations on this map by other threads may be blocked while
1645 >     * computation is in progress, so the computation should be short
1646 >     * and simple.
1647 >     *
1648 >     * <p>The mapping function must not modify this map during computation.
1649 >     *
1650 >     * @param key key with which the specified value is to be associated
1651 >     * @param mappingFunction the function to compute a value
1652 >     * @return the current (existing or computed) value associated with
1653 >     *         the specified key, or null if the computed value is null
1654 >     * @throws NullPointerException if the specified key or mappingFunction
1655 >     *         is null
1656 >     * @throws IllegalStateException if the computation detectably
1657 >     *         attempts a recursive update to this map that would
1658 >     *         otherwise never complete
1659 >     * @throws RuntimeException or Error if the mappingFunction does so,
1660 >     *         in which case the mapping is left unestablished
1661 >     */
1662 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1663 >        if (key == null || mappingFunction == null)
1664              throw new NullPointerException();
1665 <        int h = spread(k.hashCode());
1665 >        int h = spread(key.hashCode());
1666          V val = null;
1667 <        int len = 0;
1668 <        for (Node<V>[] tab = table;;) {
1669 <            Node<V> f; int i; Object fk;
1670 <            if (tab == null)
1667 >        int binCount = 0;
1668 >        for (Node<K,V>[] tab = table;;) {
1669 >            Node<K,V> f; int n, i, fh; K fk; V fv;
1670 >            if (tab == null || (n = tab.length) == 0)
1671                  tab = initTable();
1672 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1673 <                Node<V> node = new Node<V>(h, k, null, null);
1674 <                synchronized (node) {
1675 <                    if (casTabAt(tab, i, null, node)) {
1676 <                        len = 1;
1672 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1673 >                Node<K,V> r = new ReservationNode<K,V>();
1674 >                synchronized (r) {
1675 >                    if (casTabAt(tab, i, null, r)) {
1676 >                        binCount = 1;
1677 >                        Node<K,V> node = null;
1678                          try {
1679 <                            if ((val = mf.apply(k)) != null)
1680 <                                node.val = val;
1679 >                            if ((val = mappingFunction.apply(key)) != null)
1680 >                                node = new Node<K,V>(h, key, val);
1681                          } finally {
1682 <                            if (val == null)
1334 <                                setTabAt(tab, i, null);
1682 >                            setTabAt(tab, i, node);
1683                          }
1684                      }
1685                  }
1686 <                if (len != 0)
1686 >                if (binCount != 0)
1687                      break;
1688              }
1689 <            else if (f.hash < 0) {
1690 <                if ((fk = f.key) instanceof TreeBin) {
1691 <                    TreeBin<V> t = (TreeBin<V>)fk;
1692 <                    boolean added = false;
1693 <                    t.acquire(0);
1694 <                    try {
1695 <                        if (tabAt(tab, i) == f) {
1696 <                            len = 1;
1697 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1698 <                            if (p != null)
1689 >            else if ((fh = f.hash) == MOVED)
1690 >                tab = helpTransfer(tab, f);
1691 >            else if (fh == h    // check first node without acquiring lock
1692 >                     && ((fk = f.key) == key || (fk != null && key.equals(fk)))
1693 >                     && (fv = f.val) != null)
1694 >                return fv;
1695 >            else {
1696 >                boolean added = false;
1697 >                synchronized (f) {
1698 >                    if (tabAt(tab, i) == f) {
1699 >                        if (fh >= 0) {
1700 >                            binCount = 1;
1701 >                            for (Node<K,V> e = f;; ++binCount) {
1702 >                                K ek;
1703 >                                if (e.hash == h &&
1704 >                                    ((ek = e.key) == key ||
1705 >                                     (ek != null && key.equals(ek)))) {
1706 >                                    val = e.val;
1707 >                                    break;
1708 >                                }
1709 >                                Node<K,V> pred = e;
1710 >                                if ((e = e.next) == null) {
1711 >                                    if ((val = mappingFunction.apply(key)) != null) {
1712 >                                        if (pred.next != null)
1713 >                                            throw new IllegalStateException("Recursive update");
1714 >                                        added = true;
1715 >                                        pred.next = new Node<K,V>(h, key, val);
1716 >                                    }
1717 >                                    break;
1718 >                                }
1719 >                            }
1720 >                        }
1721 >                        else if (f instanceof TreeBin) {
1722 >                            binCount = 2;
1723 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1724 >                            TreeNode<K,V> r, p;
1725 >                            if ((r = t.root) != null &&
1726 >                                (p = r.findTreeNode(h, key, null)) != null)
1727                                  val = p.val;
1728 <                            else if ((val = mf.apply(k)) != null) {
1728 >                            else if ((val = mappingFunction.apply(key)) != null) {
1729                                  added = true;
1730 <                                len = 2;
1355 <                                t.putTreeNode(h, k, val);
1730 >                                t.putTreeVal(h, key, val);
1731                              }
1732                          }
1733 <                    } finally {
1734 <                        t.release(0);
1360 <                    }
1361 <                    if (len != 0) {
1362 <                        if (!added)
1363 <                            return val;
1364 <                        break;
1733 >                        else if (f instanceof ReservationNode)
1734 >                            throw new IllegalStateException("Recursive update");
1735                      }
1736                  }
1737 <                else
1738 <                    tab = (Node<V>[])fk;
1737 >                if (binCount != 0) {
1738 >                    if (binCount >= TREEIFY_THRESHOLD)
1739 >                        treeifyBin(tab, i);
1740 >                    if (!added)
1741 >                        return val;
1742 >                    break;
1743 >                }
1744              }
1745 +        }
1746 +        if (val != null)
1747 +            addCount(1L, binCount);
1748 +        return val;
1749 +    }
1750 +
1751 +    /**
1752 +     * If the value for the specified key is present, attempts to
1753 +     * compute a new mapping given the key and its current mapped
1754 +     * value.  The entire method invocation is performed atomically.
1755 +     * The supplied function is invoked exactly once per invocation of
1756 +     * this method if the key is present, else not at all.  Some
1757 +     * attempted update operations on this map by other threads may be
1758 +     * blocked while computation is in progress, so the computation
1759 +     * should be short and simple.
1760 +     *
1761 +     * <p>The remapping function must not modify this map during computation.
1762 +     *
1763 +     * @param key key with which a value may be associated
1764 +     * @param remappingFunction the function to compute a value
1765 +     * @return the new value associated with the specified key, or null if none
1766 +     * @throws NullPointerException if the specified key or remappingFunction
1767 +     *         is null
1768 +     * @throws IllegalStateException if the computation detectably
1769 +     *         attempts a recursive update to this map that would
1770 +     *         otherwise never complete
1771 +     * @throws RuntimeException or Error if the remappingFunction does so,
1772 +     *         in which case the mapping is unchanged
1773 +     */
1774 +    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1775 +        if (key == null || remappingFunction == null)
1776 +            throw new NullPointerException();
1777 +        int h = spread(key.hashCode());
1778 +        V val = null;
1779 +        int delta = 0;
1780 +        int binCount = 0;
1781 +        for (Node<K,V>[] tab = table;;) {
1782 +            Node<K,V> f; int n, i, fh;
1783 +            if (tab == null || (n = tab.length) == 0)
1784 +                tab = initTable();
1785 +            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1786 +                break;
1787 +            else if ((fh = f.hash) == MOVED)
1788 +                tab = helpTransfer(tab, f);
1789              else {
1371                for (Node<V> e = f; e != null; e = e.next) { // prescan
1372                    Object ek; V ev;
1373                    if (e.hash == h && (ev = e.val) != null &&
1374                        ((ek = e.key) == k || k.equals(ek)))
1375                        return ev;
1376                }
1377                boolean added = false;
1790                  synchronized (f) {
1791                      if (tabAt(tab, i) == f) {
1792 <                        len = 1;
1793 <                        for (Node<V> e = f;; ++len) {
1794 <                            Object ek; V ev;
1795 <                            if (e.hash == h &&
1796 <                                (ev = e.val) != null &&
1797 <                                ((ek = e.key) == k || k.equals(ek))) {
1798 <                                val = ev;
1799 <                                break;
1792 >                        if (fh >= 0) {
1793 >                            binCount = 1;
1794 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1795 >                                K ek;
1796 >                                if (e.hash == h &&
1797 >                                    ((ek = e.key) == key ||
1798 >                                     (ek != null && key.equals(ek)))) {
1799 >                                    val = remappingFunction.apply(key, e.val);
1800 >                                    if (val != null)
1801 >                                        e.val = val;
1802 >                                    else {
1803 >                                        delta = -1;
1804 >                                        Node<K,V> en = e.next;
1805 >                                        if (pred != null)
1806 >                                            pred.next = en;
1807 >                                        else
1808 >                                            setTabAt(tab, i, en);
1809 >                                    }
1810 >                                    break;
1811 >                                }
1812 >                                pred = e;
1813 >                                if ((e = e.next) == null)
1814 >                                    break;
1815                              }
1816 <                            Node<V> last = e;
1817 <                            if ((e = e.next) == null) {
1818 <                                if ((val = mf.apply(k)) != null) {
1819 <                                    added = true;
1820 <                                    last.next = new Node<V>(h, k, val, null);
1821 <                                    if (len >= TREE_THRESHOLD)
1822 <                                        replaceWithTreeBin(tab, i, k);
1816 >                        }
1817 >                        else if (f instanceof TreeBin) {
1818 >                            binCount = 2;
1819 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1820 >                            TreeNode<K,V> r, p;
1821 >                            if ((r = t.root) != null &&
1822 >                                (p = r.findTreeNode(h, key, null)) != null) {
1823 >                                val = remappingFunction.apply(key, p.val);
1824 >                                if (val != null)
1825 >                                    p.val = val;
1826 >                                else {
1827 >                                    delta = -1;
1828 >                                    if (t.removeTreeNode(p))
1829 >                                        setTabAt(tab, i, untreeify(t.first));
1830                                  }
1397                                break;
1831                              }
1832                          }
1833 +                        else if (f instanceof ReservationNode)
1834 +                            throw new IllegalStateException("Recursive update");
1835                      }
1836                  }
1837 <                if (len != 0) {
1403 <                    if (!added)
1404 <                        return val;
1837 >                if (binCount != 0)
1838                      break;
1406                }
1839              }
1840          }
1841 <        if (val != null)
1842 <            addCount(1L, len);
1841 >        if (delta != 0)
1842 >            addCount((long)delta, binCount);
1843          return val;
1844      }
1845  
1846 <    /** Implementation for compute */
1847 <    @SuppressWarnings("unchecked") private final V internalCompute
1848 <        (K k, boolean onlyIfPresent,
1849 <         BiFunction<? super K, ? super V, ? extends V> mf) {
1850 <        if (k == null || mf == null)
1846 >    /**
1847 >     * Attempts to compute a mapping for the specified key and its
1848 >     * current mapped value (or {@code null} if there is no current
1849 >     * mapping). The entire method invocation is performed atomically.
1850 >     * The supplied function is invoked exactly once per invocation of
1851 >     * this method.  Some attempted update operations on this map by
1852 >     * other threads may be blocked while computation is in progress,
1853 >     * so the computation should be short and simple.
1854 >     *
1855 >     * <p>The remapping function must not modify this map during computation.
1856 >     *
1857 >     * @param key key with which the specified value is to be associated
1858 >     * @param remappingFunction the function to compute a value
1859 >     * @return the new value associated with the specified key, or null if none
1860 >     * @throws NullPointerException if the specified key or remappingFunction
1861 >     *         is null
1862 >     * @throws IllegalStateException if the computation detectably
1863 >     *         attempts a recursive update to this map that would
1864 >     *         otherwise never complete
1865 >     * @throws RuntimeException or Error if the remappingFunction does so,
1866 >     *         in which case the mapping is unchanged
1867 >     */
1868 >    public V compute(K key,
1869 >                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1870 >        if (key == null || remappingFunction == null)
1871              throw new NullPointerException();
1872 <        int h = spread(k.hashCode());
1872 >        int h = spread(key.hashCode());
1873          V val = null;
1874          int delta = 0;
1875 <        int len = 0;
1876 <        for (Node<V>[] tab = table;;) {
1877 <            Node<V> f; int i, fh; Object fk;
1878 <            if (tab == null)
1875 >        int binCount = 0;
1876 >        for (Node<K,V>[] tab = table;;) {
1877 >            Node<K,V> f; int n, i, fh;
1878 >            if (tab == null || (n = tab.length) == 0)
1879                  tab = initTable();
1880 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1881 <                if (onlyIfPresent)
1882 <                    break;
1883 <                Node<V> node = new Node<V>(h, k, null, null);
1884 <                synchronized (node) {
1885 <                    if (casTabAt(tab, i, null, node)) {
1880 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1881 >                Node<K,V> r = new ReservationNode<K,V>();
1882 >                synchronized (r) {
1883 >                    if (casTabAt(tab, i, null, r)) {
1884 >                        binCount = 1;
1885 >                        Node<K,V> node = null;
1886                          try {
1887 <                            len = 1;
1436 <                            if ((val = mf.apply(k, null)) != null) {
1437 <                                node.val = val;
1887 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1888                                  delta = 1;
1889 +                                node = new Node<K,V>(h, key, val);
1890                              }
1891                          } finally {
1892 <                            if (delta == 0)
1442 <                                setTabAt(tab, i, null);
1892 >                            setTabAt(tab, i, node);
1893                          }
1894                      }
1895                  }
1896 <                if (len != 0)
1896 >                if (binCount != 0)
1897                      break;
1898              }
1899 <            else if ((fh = f.hash) < 0) {
1900 <                if ((fk = f.key) instanceof TreeBin) {
1901 <                    TreeBin<V> t = (TreeBin<V>)fk;
1902 <                    t.acquire(0);
1903 <                    try {
1904 <                        if (tabAt(tab, i) == f) {
1905 <                            len = 1;
1906 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1907 <                            if (p == null && onlyIfPresent)
1908 <                                break;
1899 >            else if ((fh = f.hash) == MOVED)
1900 >                tab = helpTransfer(tab, f);
1901 >            else {
1902 >                synchronized (f) {
1903 >                    if (tabAt(tab, i) == f) {
1904 >                        if (fh >= 0) {
1905 >                            binCount = 1;
1906 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1907 >                                K ek;
1908 >                                if (e.hash == h &&
1909 >                                    ((ek = e.key) == key ||
1910 >                                     (ek != null && key.equals(ek)))) {
1911 >                                    val = remappingFunction.apply(key, e.val);
1912 >                                    if (val != null)
1913 >                                        e.val = val;
1914 >                                    else {
1915 >                                        delta = -1;
1916 >                                        Node<K,V> en = e.next;
1917 >                                        if (pred != null)
1918 >                                            pred.next = en;
1919 >                                        else
1920 >                                            setTabAt(tab, i, en);
1921 >                                    }
1922 >                                    break;
1923 >                                }
1924 >                                pred = e;
1925 >                                if ((e = e.next) == null) {
1926 >                                    val = remappingFunction.apply(key, null);
1927 >                                    if (val != null) {
1928 >                                        if (pred.next != null)
1929 >                                            throw new IllegalStateException("Recursive update");
1930 >                                        delta = 1;
1931 >                                        pred.next = new Node<K,V>(h, key, val);
1932 >                                    }
1933 >                                    break;
1934 >                                }
1935 >                            }
1936 >                        }
1937 >                        else if (f instanceof TreeBin) {
1938 >                            binCount = 1;
1939 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1940 >                            TreeNode<K,V> r, p;
1941 >                            if ((r = t.root) != null)
1942 >                                p = r.findTreeNode(h, key, null);
1943 >                            else
1944 >                                p = null;
1945                              V pv = (p == null) ? null : p.val;
1946 <                            if ((val = mf.apply(k, pv)) != null) {
1946 >                            val = remappingFunction.apply(key, pv);
1947 >                            if (val != null) {
1948                                  if (p != null)
1949                                      p.val = val;
1950                                  else {
1464                                    len = 2;
1951                                      delta = 1;
1952 <                                    t.putTreeNode(h, k, val);
1952 >                                    t.putTreeVal(h, key, val);
1953                                  }
1954                              }
1955                              else if (p != null) {
1956                                  delta = -1;
1957 <                                t.deleteTreeNode(p);
1958 <                            }
1473 <                        }
1474 <                    } finally {
1475 <                        t.release(0);
1476 <                    }
1477 <                    if (len != 0)
1478 <                        break;
1479 <                }
1480 <                else
1481 <                    tab = (Node<V>[])fk;
1482 <            }
1483 <            else {
1484 <                synchronized (f) {
1485 <                    if (tabAt(tab, i) == f) {
1486 <                        len = 1;
1487 <                        for (Node<V> e = f, pred = null;; ++len) {
1488 <                            Object ek; V ev;
1489 <                            if (e.hash == h &&
1490 <                                (ev = e.val) != null &&
1491 <                                ((ek = e.key) == k || k.equals(ek))) {
1492 <                                val = mf.apply(k, ev);
1493 <                                if (val != null)
1494 <                                    e.val = val;
1495 <                                else {
1496 <                                    delta = -1;
1497 <                                    Node<V> en = e.next;
1498 <                                    if (pred != null)
1499 <                                        pred.next = en;
1500 <                                    else
1501 <                                        setTabAt(tab, i, en);
1502 <                                }
1503 <                                break;
1504 <                            }
1505 <                            pred = e;
1506 <                            if ((e = e.next) == null) {
1507 <                                if (!onlyIfPresent &&
1508 <                                    (val = mf.apply(k, null)) != null) {
1509 <                                    pred.next = new Node<V>(h, k, val, null);
1510 <                                    delta = 1;
1511 <                                    if (len >= TREE_THRESHOLD)
1512 <                                        replaceWithTreeBin(tab, i, k);
1513 <                                }
1514 <                                break;
1957 >                                if (t.removeTreeNode(p))
1958 >                                    setTabAt(tab, i, untreeify(t.first));
1959                              }
1960                          }
1961 +                        else if (f instanceof ReservationNode)
1962 +                            throw new IllegalStateException("Recursive update");
1963                      }
1964                  }
1965 <                if (len != 0)
1965 >                if (binCount != 0) {
1966 >                    if (binCount >= TREEIFY_THRESHOLD)
1967 >                        treeifyBin(tab, i);
1968                      break;
1969 +                }
1970              }
1971          }
1972          if (delta != 0)
1973 <            addCount((long)delta, len);
1973 >            addCount((long)delta, binCount);
1974          return val;
1975      }
1976  
1977 <    /** Implementation for merge */
1978 <    @SuppressWarnings("unchecked") private final V internalMerge
1979 <        (K k, V v, BiFunction<? super V, ? super V, ? extends V> mf) {
1980 <        if (k == null || v == null || mf == null)
1977 >    /**
1978 >     * If the specified key is not already associated with a
1979 >     * (non-null) value, associates it with the given value.
1980 >     * Otherwise, replaces the value with the results of the given
1981 >     * remapping function, or removes if {@code null}. The entire
1982 >     * method invocation is performed atomically.  Some attempted
1983 >     * update operations on this map by other threads may be blocked
1984 >     * while computation is in progress, so the computation should be
1985 >     * short and simple, and must not attempt to update any other
1986 >     * mappings of this Map.
1987 >     *
1988 >     * @param key key with which the specified value is to be associated
1989 >     * @param value the value to use if absent
1990 >     * @param remappingFunction the function to recompute a value if present
1991 >     * @return the new value associated with the specified key, or null if none
1992 >     * @throws NullPointerException if the specified key or the
1993 >     *         remappingFunction is null
1994 >     * @throws RuntimeException or Error if the remappingFunction does so,
1995 >     *         in which case the mapping is unchanged
1996 >     */
1997 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1998 >        if (key == null || value == null || remappingFunction == null)
1999              throw new NullPointerException();
2000 <        int h = spread(k.hashCode());
2000 >        int h = spread(key.hashCode());
2001          V val = null;
2002          int delta = 0;
2003 <        int len = 0;
2004 <        for (Node<V>[] tab = table;;) {
2005 <            int i; Node<V> f; Object fk; V fv;
2006 <            if (tab == null)
2003 >        int binCount = 0;
2004 >        for (Node<K,V>[] tab = table;;) {
2005 >            Node<K,V> f; int n, i, fh;
2006 >            if (tab == null || (n = tab.length) == 0)
2007                  tab = initTable();
2008 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
2009 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
2008 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
2009 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value))) {
2010                      delta = 1;
2011 <                    val = v;
2011 >                    val = value;
2012                      break;
2013                  }
2014              }
2015 <            else if (f.hash < 0) {
2016 <                if ((fk = f.key) instanceof TreeBin) {
2017 <                    TreeBin<V> t = (TreeBin<V>)fk;
2018 <                    t.acquire(0);
2019 <                    try {
2020 <                        if (tabAt(tab, i) == f) {
2021 <                            len = 1;
2022 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
2023 <                            val = (p == null) ? v : mf.apply(p.val, v);
2015 >            else if ((fh = f.hash) == MOVED)
2016 >                tab = helpTransfer(tab, f);
2017 >            else {
2018 >                synchronized (f) {
2019 >                    if (tabAt(tab, i) == f) {
2020 >                        if (fh >= 0) {
2021 >                            binCount = 1;
2022 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
2023 >                                K ek;
2024 >                                if (e.hash == h &&
2025 >                                    ((ek = e.key) == key ||
2026 >                                     (ek != null && key.equals(ek)))) {
2027 >                                    val = remappingFunction.apply(e.val, value);
2028 >                                    if (val != null)
2029 >                                        e.val = val;
2030 >                                    else {
2031 >                                        delta = -1;
2032 >                                        Node<K,V> en = e.next;
2033 >                                        if (pred != null)
2034 >                                            pred.next = en;
2035 >                                        else
2036 >                                            setTabAt(tab, i, en);
2037 >                                    }
2038 >                                    break;
2039 >                                }
2040 >                                pred = e;
2041 >                                if ((e = e.next) == null) {
2042 >                                    delta = 1;
2043 >                                    val = value;
2044 >                                    pred.next = new Node<K,V>(h, key, val);
2045 >                                    break;
2046 >                                }
2047 >                            }
2048 >                        }
2049 >                        else if (f instanceof TreeBin) {
2050 >                            binCount = 2;
2051 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2052 >                            TreeNode<K,V> r = t.root;
2053 >                            TreeNode<K,V> p = (r == null) ? null :
2054 >                                r.findTreeNode(h, key, null);
2055 >                            val = (p == null) ? value :
2056 >                                remappingFunction.apply(p.val, value);
2057                              if (val != null) {
2058                                  if (p != null)
2059                                      p.val = val;
2060                                  else {
1561                                    len = 2;
2061                                      delta = 1;
2062 <                                    t.putTreeNode(h, k, val);
2062 >                                    t.putTreeVal(h, key, val);
2063                                  }
2064                              }
2065                              else if (p != null) {
2066                                  delta = -1;
2067 <                                t.deleteTreeNode(p);
2067 >                                if (t.removeTreeNode(p))
2068 >                                    setTabAt(tab, i, untreeify(t.first));
2069                              }
2070                          }
2071 <                    } finally {
2072 <                        t.release(0);
2071 >                        else if (f instanceof ReservationNode)
2072 >                            throw new IllegalStateException("Recursive update");
2073                      }
1574                    if (len != 0)
1575                        break;
2074                  }
2075 <                else
2076 <                    tab = (Node<V>[])fk;
2077 <            }
1580 <            else {
1581 <                synchronized (f) {
1582 <                    if (tabAt(tab, i) == f) {
1583 <                        len = 1;
1584 <                        for (Node<V> e = f, pred = null;; ++len) {
1585 <                            Object ek; V ev;
1586 <                            if (e.hash == h &&
1587 <                                (ev = e.val) != null &&
1588 <                                ((ek = e.key) == k || k.equals(ek))) {
1589 <                                val = mf.apply(ev, v);
1590 <                                if (val != null)
1591 <                                    e.val = val;
1592 <                                else {
1593 <                                    delta = -1;
1594 <                                    Node<V> en = e.next;
1595 <                                    if (pred != null)
1596 <                                        pred.next = en;
1597 <                                    else
1598 <                                        setTabAt(tab, i, en);
1599 <                                }
1600 <                                break;
1601 <                            }
1602 <                            pred = e;
1603 <                            if ((e = e.next) == null) {
1604 <                                val = v;
1605 <                                pred.next = new Node<V>(h, k, val, null);
1606 <                                delta = 1;
1607 <                                if (len >= TREE_THRESHOLD)
1608 <                                    replaceWithTreeBin(tab, i, k);
1609 <                                break;
1610 <                            }
1611 <                        }
1612 <                    }
1613 <                }
1614 <                if (len != 0)
2075 >                if (binCount != 0) {
2076 >                    if (binCount >= TREEIFY_THRESHOLD)
2077 >                        treeifyBin(tab, i);
2078                      break;
2079 +                }
2080              }
2081          }
2082          if (delta != 0)
2083 <            addCount((long)delta, len);
2083 >            addCount((long)delta, binCount);
2084          return val;
2085      }
2086  
2087 <    /** Implementation for putAll */
2088 <    @SuppressWarnings("unchecked") private final void internalPutAll
2089 <        (Map<? extends K, ? extends V> m) {
2090 <        tryPresize(m.size());
2091 <        long delta = 0L;     // number of uncommitted additions
2092 <        boolean npe = false; // to throw exception on exit for nulls
2093 <        try {                // to clean up counts on other exceptions
2094 <            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
2095 <                Object k; V v;
2096 <                if (entry == null || (k = entry.getKey()) == null ||
2097 <                    (v = entry.getValue()) == null) {
2098 <                    npe = true;
2099 <                    break;
2100 <                }
2101 <                int h = spread(k.hashCode());
2102 <                for (Node<V>[] tab = table;;) {
2103 <                    int i; Node<V> f; int fh; Object fk;
2104 <                    if (tab == null)
2105 <                        tab = initTable();
2106 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
2107 <                        if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
2108 <                            ++delta;
2109 <                            break;
2110 <                        }
2111 <                    }
2112 <                    else if ((fh = f.hash) < 0) {
2113 <                        if ((fk = f.key) instanceof TreeBin) {
2114 <                            TreeBin<V> t = (TreeBin<V>)fk;
2115 <                            boolean validated = false;
2116 <                            t.acquire(0);
2117 <                            try {
2118 <                                if (tabAt(tab, i) == f) {
2119 <                                    validated = true;
2120 <                                    TreeNode<V> p = t.getTreeNode(h, k, t.root);
2121 <                                    if (p != null)
2122 <                                        p.val = v;
2123 <                                    else {
2124 <                                        t.putTreeNode(h, k, v);
2125 <                                        ++delta;
2126 <                                    }
2127 <                                }
2128 <                            } finally {
2129 <                                t.release(0);
2130 <                            }
2131 <                            if (validated)
2132 <                                break;
2087 >    // Hashtable legacy methods
2088 >
2089 >    /**
2090 >     * Tests if some key maps into the specified value in this table.
2091 >     *
2092 >     * <p>Note that this method is identical in functionality to
2093 >     * {@link #containsValue(Object)}, and exists solely to ensure
2094 >     * full compatibility with class {@link java.util.Hashtable},
2095 >     * which supported this method prior to introduction of the
2096 >     * Java Collections Framework.
2097 >     *
2098 >     * @param  value a value to search for
2099 >     * @return {@code true} if and only if some key maps to the
2100 >     *         {@code value} argument in this table as
2101 >     *         determined by the {@code equals} method;
2102 >     *         {@code false} otherwise
2103 >     * @throws NullPointerException if the specified value is null
2104 >     */
2105 >    public boolean contains(Object value) {
2106 >        return containsValue(value);
2107 >    }
2108 >
2109 >    /**
2110 >     * Returns an enumeration of the keys in this table.
2111 >     *
2112 >     * @return an enumeration of the keys in this table
2113 >     * @see #keySet()
2114 >     */
2115 >    public Enumeration<K> keys() {
2116 >        Node<K,V>[] t;
2117 >        int f = (t = table) == null ? 0 : t.length;
2118 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2119 >    }
2120 >
2121 >    /**
2122 >     * Returns an enumeration of the values in this table.
2123 >     *
2124 >     * @return an enumeration of the values in this table
2125 >     * @see #values()
2126 >     */
2127 >    public Enumeration<V> elements() {
2128 >        Node<K,V>[] t;
2129 >        int f = (t = table) == null ? 0 : t.length;
2130 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2131 >    }
2132 >
2133 >    // ConcurrentHashMap-only methods
2134 >
2135 >    /**
2136 >     * Returns the number of mappings. This method should be used
2137 >     * instead of {@link #size} because a ConcurrentHashMap may
2138 >     * contain more mappings than can be represented as an int. The
2139 >     * value returned is an estimate; the actual count may differ if
2140 >     * there are concurrent insertions or removals.
2141 >     *
2142 >     * @return the number of mappings
2143 >     * @since 1.8
2144 >     */
2145 >    public long mappingCount() {
2146 >        long n = sumCount();
2147 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2148 >    }
2149 >
2150 >    /**
2151 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2152 >     * from the given type to {@code Boolean.TRUE}.
2153 >     *
2154 >     * @param <K> the element type of the returned set
2155 >     * @return the new set
2156 >     * @since 1.8
2157 >     */
2158 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2159 >        return new KeySetView<K,Boolean>
2160 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2161 >    }
2162 >
2163 >    /**
2164 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2165 >     * from the given type to {@code Boolean.TRUE}.
2166 >     *
2167 >     * @param initialCapacity The implementation performs internal
2168 >     * sizing to accommodate this many elements.
2169 >     * @param <K> the element type of the returned set
2170 >     * @return the new set
2171 >     * @throws IllegalArgumentException if the initial capacity of
2172 >     * elements is negative
2173 >     * @since 1.8
2174 >     */
2175 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2176 >        return new KeySetView<K,Boolean>
2177 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2178 >    }
2179 >
2180 >    /**
2181 >     * Returns a {@link Set} view of the keys in this map, using the
2182 >     * given common mapped value for any additions (i.e., {@link
2183 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2184 >     * This is of course only appropriate if it is acceptable to use
2185 >     * the same value for all additions from this view.
2186 >     *
2187 >     * @param mappedValue the mapped value to use for any additions
2188 >     * @return the set view
2189 >     * @throws NullPointerException if the mappedValue is null
2190 >     */
2191 >    public KeySetView<K,V> keySet(V mappedValue) {
2192 >        if (mappedValue == null)
2193 >            throw new NullPointerException();
2194 >        return new KeySetView<K,V>(this, mappedValue);
2195 >    }
2196 >
2197 >    /* ---------------- Special Nodes -------------- */
2198 >
2199 >    /**
2200 >     * A node inserted at head of bins during transfer operations.
2201 >     */
2202 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2203 >        final Node<K,V>[] nextTable;
2204 >        ForwardingNode(Node<K,V>[] tab) {
2205 >            super(MOVED, null, null);
2206 >            this.nextTable = tab;
2207 >        }
2208 >
2209 >        Node<K,V> find(int h, Object k) {
2210 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2211 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2212 >                Node<K,V> e; int n;
2213 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2214 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2215 >                    return null;
2216 >                for (;;) {
2217 >                    int eh; K ek;
2218 >                    if ((eh = e.hash) == h &&
2219 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2220 >                        return e;
2221 >                    if (eh < 0) {
2222 >                        if (e instanceof ForwardingNode) {
2223 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2224 >                            continue outer;
2225                          }
2226                          else
2227 <                            tab = (Node<V>[])fk;
1672 <                    }
1673 <                    else {
1674 <                        int len = 0;
1675 <                        synchronized (f) {
1676 <                            if (tabAt(tab, i) == f) {
1677 <                                len = 1;
1678 <                                for (Node<V> e = f;; ++len) {
1679 <                                    Object ek; V ev;
1680 <                                    if (e.hash == h &&
1681 <                                        (ev = e.val) != null &&
1682 <                                        ((ek = e.key) == k || k.equals(ek))) {
1683 <                                        e.val = v;
1684 <                                        break;
1685 <                                    }
1686 <                                    Node<V> last = e;
1687 <                                    if ((e = e.next) == null) {
1688 <                                        ++delta;
1689 <                                        last.next = new Node<V>(h, k, v, null);
1690 <                                        if (len >= TREE_THRESHOLD)
1691 <                                            replaceWithTreeBin(tab, i, k);
1692 <                                        break;
1693 <                                    }
1694 <                                }
1695 <                            }
1696 <                        }
1697 <                        if (len != 0) {
1698 <                            if (len > 1) {
1699 <                                addCount(delta, len);
1700 <                                delta = 0L;
1701 <                            }
1702 <                            break;
1703 <                        }
2227 >                            return e.find(h, k);
2228                      }
2229 +                    if ((e = e.next) == null)
2230 +                        return null;
2231                  }
2232              }
1707        } finally {
1708            if (delta != 0L)
1709                addCount(delta, 2);
2233          }
1711        if (npe)
1712            throw new NullPointerException();
2234      }
2235  
2236      /**
2237 <     * Implementation for clear. Steps through each bin, removing all
1717 <     * nodes.
2237 >     * A place-holder node used in computeIfAbsent and compute.
2238       */
2239 <    @SuppressWarnings("unchecked") private final void internalClear() {
2240 <        long delta = 0L; // negative number of deletions
2241 <        int i = 0;
2242 <        Node<V>[] tab = table;
2243 <        while (tab != null && i < tab.length) {
2244 <            Node<V> f = tabAt(tab, i);
2245 <            if (f == null)
1726 <                ++i;
1727 <            else if (f.hash < 0) {
1728 <                Object fk;
1729 <                if ((fk = f.key) instanceof TreeBin) {
1730 <                    TreeBin<V> t = (TreeBin<V>)fk;
1731 <                    t.acquire(0);
1732 <                    try {
1733 <                        if (tabAt(tab, i) == f) {
1734 <                            for (Node<V> p = t.first; p != null; p = p.next) {
1735 <                                if (p.val != null) { // (currently always true)
1736 <                                    p.val = null;
1737 <                                    --delta;
1738 <                                }
1739 <                            }
1740 <                            t.first = null;
1741 <                            t.root = null;
1742 <                            ++i;
1743 <                        }
1744 <                    } finally {
1745 <                        t.release(0);
1746 <                    }
1747 <                }
1748 <                else
1749 <                    tab = (Node<V>[])fk;
1750 <            }
1751 <            else {
1752 <                synchronized (f) {
1753 <                    if (tabAt(tab, i) == f) {
1754 <                        for (Node<V> e = f; e != null; e = e.next) {
1755 <                            if (e.val != null) {  // (currently always true)
1756 <                                e.val = null;
1757 <                                --delta;
1758 <                            }
1759 <                        }
1760 <                        setTabAt(tab, i, null);
1761 <                        ++i;
1762 <                    }
1763 <                }
1764 <            }
2239 >    static final class ReservationNode<K,V> extends Node<K,V> {
2240 >        ReservationNode() {
2241 >            super(RESERVED, null, null);
2242 >        }
2243 >
2244 >        Node<K,V> find(int h, Object k) {
2245 >            return null;
2246          }
1766        if (delta != 0L)
1767            addCount(delta, -1);
2247      }
2248  
2249      /* ---------------- Table Initialization and Resizing -------------- */
2250  
2251      /**
2252 <     * Returns a power of two table size for the given desired capacity.
2253 <     * See Hackers Delight, sec 3.2
2252 >     * Returns the stamp bits for resizing a table of size n.
2253 >     * Must be negative when shifted left by RESIZE_STAMP_SHIFT.
2254       */
2255 <    private static final int tableSizeFor(int c) {
2256 <        int n = c - 1;
1778 <        n |= n >>> 1;
1779 <        n |= n >>> 2;
1780 <        n |= n >>> 4;
1781 <        n |= n >>> 8;
1782 <        n |= n >>> 16;
1783 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
2255 >    static final int resizeStamp(int n) {
2256 >        return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
2257      }
2258  
2259      /**
2260       * Initializes table, using the size recorded in sizeCtl.
2261       */
2262 <    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
2263 <        Node<V>[] tab; int sc;
2264 <        while ((tab = table) == null) {
2262 >    private final Node<K,V>[] initTable() {
2263 >        Node<K,V>[] tab; int sc;
2264 >        while ((tab = table) == null || tab.length == 0) {
2265              if ((sc = sizeCtl) < 0)
2266                  Thread.yield(); // lost initialization race; just spin
2267 <            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2267 >            else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {
2268                  try {
2269 <                    if ((tab = table) == null) {
2269 >                    if ((tab = table) == null || tab.length == 0) {
2270                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2271 <                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2272 <                        table = tab = (Node<V>[])tb;
2271 >                        @SuppressWarnings("unchecked")
2272 >                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2273 >                        table = tab = nt;
2274                          sc = n - (n >>> 2);
2275                      }
2276                  } finally {
# Line 1819 | Line 2293 | public class ConcurrentHashMap<K,V>
2293       * @param check if <0, don't check resize, if <= 1 only check if uncontended
2294       */
2295      private final void addCount(long x, int check) {
2296 <        Cell[] as; long b, s;
2297 <        if ((as = counterCells) != null ||
2298 <            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2299 <            Cell a; long v; int m;
2296 >        CounterCell[] cs; long b, s;
2297 >        if ((cs = counterCells) != null ||
2298 >            !U.compareAndSetLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2299 >            CounterCell c; long v; int m;
2300              boolean uncontended = true;
2301 <            if (as == null || (m = as.length - 1) < 0 ||
2302 <                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
2301 >            if (cs == null || (m = cs.length - 1) < 0 ||
2302 >                (c = cs[ThreadLocalRandom.getProbe() & m]) == null ||
2303                  !(uncontended =
2304 <                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2304 >                  U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))) {
2305                  fullAddCount(x, uncontended);
2306                  return;
2307              }
# Line 1836 | Line 2310 | public class ConcurrentHashMap<K,V>
2310              s = sumCount();
2311          }
2312          if (check >= 0) {
2313 <            Node<V>[] tab, nt; int sc;
2313 >            Node<K,V>[] tab, nt; int n, sc;
2314              while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2315 <                   tab.length < MAXIMUM_CAPACITY) {
2315 >                   (n = tab.length) < MAXIMUM_CAPACITY) {
2316 >                int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;
2317                  if (sc < 0) {
2318 <                    if (sc == -1 || transferIndex <= transferOrigin ||
2319 <                        (nt = nextTable) == null)
2318 >                    if (sc == rs + MAX_RESIZERS || sc == rs + 1 ||
2319 >                        (nt = nextTable) == null || transferIndex <= 0)
2320                          break;
2321 <                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2321 >                    if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1))
2322                          transfer(tab, nt);
2323                  }
2324 <                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2324 >                else if (U.compareAndSetInt(this, SIZECTL, sc, rs + 2))
2325                      transfer(tab, null);
2326                  s = sumCount();
2327              }
# Line 1854 | Line 2329 | public class ConcurrentHashMap<K,V>
2329      }
2330  
2331      /**
2332 +     * Helps transfer if a resize is in progress.
2333 +     */
2334 +    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2335 +        Node<K,V>[] nextTab; int sc;
2336 +        if (tab != null && (f instanceof ForwardingNode) &&
2337 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2338 +            int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT;
2339 +            while (nextTab == nextTable && table == tab &&
2340 +                   (sc = sizeCtl) < 0) {
2341 +                if (sc == rs + MAX_RESIZERS || sc == rs + 1 ||
2342 +                    transferIndex <= 0)
2343 +                    break;
2344 +                if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) {
2345 +                    transfer(tab, nextTab);
2346 +                    break;
2347 +                }
2348 +            }
2349 +            return nextTab;
2350 +        }
2351 +        return table;
2352 +    }
2353 +
2354 +    /**
2355       * Tries to presize table to accommodate the given number of elements.
2356       *
2357       * @param size number of elements (doesn't need to be perfectly accurate)
2358       */
2359 <    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
2359 >    private final void tryPresize(int size) {
2360          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2361              tableSizeFor(size + (size >>> 1) + 1);
2362          int sc;
2363          while ((sc = sizeCtl) >= 0) {
2364 <            Node<V>[] tab = table; int n;
2364 >            Node<K,V>[] tab = table; int n;
2365              if (tab == null || (n = tab.length) == 0) {
2366                  n = (sc > c) ? sc : c;
2367 <                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2367 >                if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {
2368                      try {
2369                          if (table == tab) {
2370 <                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2371 <                            table = (Node<V>[])tb;
2370 >                            @SuppressWarnings("unchecked")
2371 >                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2372 >                            table = nt;
2373                              sc = n - (n >>> 2);
2374                          }
2375                      } finally {
# Line 1880 | Line 2379 | public class ConcurrentHashMap<K,V>
2379              }
2380              else if (c <= sc || n >= MAXIMUM_CAPACITY)
2381                  break;
2382 <            else if (tab == table &&
2383 <                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2384 <                transfer(tab, null);
2382 >            else if (tab == table) {
2383 >                int rs = resizeStamp(n);
2384 >                if (U.compareAndSetInt(this, SIZECTL, sc,
2385 >                                        (rs << RESIZE_STAMP_SHIFT) + 2))
2386 >                    transfer(tab, null);
2387 >            }
2388          }
2389      }
2390  
# Line 1890 | Line 2392 | public class ConcurrentHashMap<K,V>
2392       * Moves and/or copies the nodes in each bin to new table. See
2393       * above for explanation.
2394       */
2395 <    @SuppressWarnings("unchecked") private final void transfer
1894 <        (Node<V>[] tab, Node<V>[] nextTab) {
2395 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2396          int n = tab.length, stride;
2397          if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2398              stride = MIN_TRANSFER_STRIDE; // subdivide range
2399          if (nextTab == null) {            // initiating
2400              try {
2401 <                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
2402 <                nextTab = (Node<V>[])tb;
2401 >                @SuppressWarnings("unchecked")
2402 >                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
2403 >                nextTab = nt;
2404              } catch (Throwable ex) {      // try to cope with OOME
2405                  sizeCtl = Integer.MAX_VALUE;
2406                  return;
2407              }
2408              nextTable = nextTab;
1907            transferOrigin = n;
2409              transferIndex = n;
1909            Node<V> rev = new Node<V>(MOVED, tab, null, null);
1910            for (int k = n; k > 0;) {    // progressively reveal ready slots
1911                int nextk = (k > stride) ? k - stride : 0;
1912                for (int m = nextk; m < k; ++m)
1913                    nextTab[m] = rev;
1914                for (int m = n + nextk; m < n + k; ++m)
1915                    nextTab[m] = rev;
1916                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
1917            }
2410          }
2411          int nextn = nextTab.length;
2412 <        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2412 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2413          boolean advance = true;
2414 +        boolean finishing = false; // to ensure sweep before committing nextTab
2415          for (int i = 0, bound = 0;;) {
2416 <            int nextIndex, nextBound; Node<V> f; Object fk;
2416 >            Node<K,V> f; int fh;
2417              while (advance) {
2418 <                if (--i >= bound)
2418 >                int nextIndex, nextBound;
2419 >                if (--i >= bound || finishing)
2420                      advance = false;
2421 <                else if ((nextIndex = transferIndex) <= transferOrigin) {
2421 >                else if ((nextIndex = transferIndex) <= 0) {
2422                      i = -1;
2423                      advance = false;
2424                  }
2425 <                else if (U.compareAndSwapInt
2425 >                else if (U.compareAndSetInt
2426                           (this, TRANSFERINDEX, nextIndex,
2427                            nextBound = (nextIndex > stride ?
2428                                         nextIndex - stride : 0))) {
# Line 1938 | Line 2432 | public class ConcurrentHashMap<K,V>
2432                  }
2433              }
2434              if (i < 0 || i >= n || i + n >= nextn) {
2435 <                for (int sc;;) {
2436 <                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2437 <                        if (sc == -1) {
2438 <                            nextTable = null;
2439 <                            table = nextTab;
2440 <                            sizeCtl = (n << 1) - (n >>> 1);
1947 <                        }
1948 <                        return;
1949 <                    }
2435 >                int sc;
2436 >                if (finishing) {
2437 >                    nextTable = null;
2438 >                    table = nextTab;
2439 >                    sizeCtl = (n << 1) - (n >>> 1);
2440 >                    return;
2441                  }
2442 <            }
2443 <            else if ((f = tabAt(tab, i)) == null) {
2444 <                if (casTabAt(tab, i, null, fwd)) {
2445 <                    setTabAt(nextTab, i, null);
2446 <                    setTabAt(nextTab, i + n, null);
1956 <                    advance = true;
2442 >                if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
2443 >                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
2444 >                        return;
2445 >                    finishing = advance = true;
2446 >                    i = n; // recheck before commit
2447                  }
2448              }
2449 <            else if (f.hash >= 0) {
2449 >            else if ((f = tabAt(tab, i)) == null)
2450 >                advance = casTabAt(tab, i, null, fwd);
2451 >            else if ((fh = f.hash) == MOVED)
2452 >                advance = true; // already processed
2453 >            else {
2454                  synchronized (f) {
2455                      if (tabAt(tab, i) == f) {
2456 <                        int runBit = f.hash & n;
2457 <                        Node<V> lastRun = f, lo = null, hi = null;
2458 <                        for (Node<V> p = f.next; p != null; p = p.next) {
2459 <                            int b = p.hash & n;
2460 <                            if (b != runBit) {
2461 <                                runBit = b;
2462 <                                lastRun = p;
2456 >                        Node<K,V> ln, hn;
2457 >                        if (fh >= 0) {
2458 >                            int runBit = fh & n;
2459 >                            Node<K,V> lastRun = f;
2460 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2461 >                                int b = p.hash & n;
2462 >                                if (b != runBit) {
2463 >                                    runBit = b;
2464 >                                    lastRun = p;
2465 >                                }
2466                              }
2467 <                        }
2468 <                        if (runBit == 0)
2469 <                            lo = lastRun;
1973 <                        else
1974 <                            hi = lastRun;
1975 <                        for (Node<V> p = f; p != lastRun; p = p.next) {
1976 <                            int ph = p.hash;
1977 <                            Object pk = p.key; V pv = p.val;
1978 <                            if ((ph & n) == 0)
1979 <                                lo = new Node<V>(ph, pk, pv, lo);
1980 <                            else
1981 <                                hi = new Node<V>(ph, pk, pv, hi);
1982 <                        }
1983 <                        setTabAt(nextTab, i, lo);
1984 <                        setTabAt(nextTab, i + n, hi);
1985 <                        setTabAt(tab, i, fwd);
1986 <                        advance = true;
1987 <                    }
1988 <                }
1989 <            }
1990 <            else if ((fk = f.key) instanceof TreeBin) {
1991 <                TreeBin<V> t = (TreeBin<V>)fk;
1992 <                t.acquire(0);
1993 <                try {
1994 <                    if (tabAt(tab, i) == f) {
1995 <                        TreeBin<V> lt = new TreeBin<V>();
1996 <                        TreeBin<V> ht = new TreeBin<V>();
1997 <                        int lc = 0, hc = 0;
1998 <                        for (Node<V> e = t.first; e != null; e = e.next) {
1999 <                            int h = e.hash;
2000 <                            Object k = e.key; V v = e.val;
2001 <                            if ((h & n) == 0) {
2002 <                                ++lc;
2003 <                                lt.putTreeNode(h, k, v);
2467 >                            if (runBit == 0) {
2468 >                                ln = lastRun;
2469 >                                hn = null;
2470                              }
2471                              else {
2472 <                                ++hc;
2473 <                                ht.putTreeNode(h, k, v);
2472 >                                hn = lastRun;
2473 >                                ln = null;
2474                              }
2475 +                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2476 +                                int ph = p.hash; K pk = p.key; V pv = p.val;
2477 +                                if ((ph & n) == 0)
2478 +                                    ln = new Node<K,V>(ph, pk, pv, ln);
2479 +                                else
2480 +                                    hn = new Node<K,V>(ph, pk, pv, hn);
2481 +                            }
2482 +                            setTabAt(nextTab, i, ln);
2483 +                            setTabAt(nextTab, i + n, hn);
2484 +                            setTabAt(tab, i, fwd);
2485 +                            advance = true;
2486 +                        }
2487 +                        else if (f instanceof TreeBin) {
2488 +                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2489 +                            TreeNode<K,V> lo = null, loTail = null;
2490 +                            TreeNode<K,V> hi = null, hiTail = null;
2491 +                            int lc = 0, hc = 0;
2492 +                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2493 +                                int h = e.hash;
2494 +                                TreeNode<K,V> p = new TreeNode<K,V>
2495 +                                    (h, e.key, e.val, null, null);
2496 +                                if ((h & n) == 0) {
2497 +                                    if ((p.prev = loTail) == null)
2498 +                                        lo = p;
2499 +                                    else
2500 +                                        loTail.next = p;
2501 +                                    loTail = p;
2502 +                                    ++lc;
2503 +                                }
2504 +                                else {
2505 +                                    if ((p.prev = hiTail) == null)
2506 +                                        hi = p;
2507 +                                    else
2508 +                                        hiTail.next = p;
2509 +                                    hiTail = p;
2510 +                                    ++hc;
2511 +                                }
2512 +                            }
2513 +                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2514 +                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2515 +                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2516 +                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2517 +                            setTabAt(nextTab, i, ln);
2518 +                            setTabAt(nextTab, i + n, hn);
2519 +                            setTabAt(tab, i, fwd);
2520 +                            advance = true;
2521                          }
2522 <                        Node<V> ln, hn; // throw away trees if too small
2523 <                        if (lc < TREE_THRESHOLD) {
2012 <                            ln = null;
2013 <                            for (Node<V> p = lt.first; p != null; p = p.next)
2014 <                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2015 <                        }
2016 <                        else
2017 <                            ln = new Node<V>(MOVED, lt, null, null);
2018 <                        setTabAt(nextTab, i, ln);
2019 <                        if (hc < TREE_THRESHOLD) {
2020 <                            hn = null;
2021 <                            for (Node<V> p = ht.first; p != null; p = p.next)
2022 <                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2023 <                        }
2024 <                        else
2025 <                            hn = new Node<V>(MOVED, ht, null, null);
2026 <                        setTabAt(nextTab, i + n, hn);
2027 <                        setTabAt(tab, i, fwd);
2028 <                        advance = true;
2522 >                        else if (f instanceof ReservationNode)
2523 >                            throw new IllegalStateException("Recursive update");
2524                      }
2030                } finally {
2031                    t.release(0);
2525                  }
2526              }
2034            else
2035                advance = true; // already processed
2527          }
2528      }
2529  
2530      /* ---------------- Counter support -------------- */
2531  
2532 +    /**
2533 +     * A padded cell for distributing counts.  Adapted from LongAdder
2534 +     * and Striped64.  See their internal docs for explanation.
2535 +     */
2536 +    @jdk.internal.vm.annotation.Contended static final class CounterCell {
2537 +        volatile long value;
2538 +        CounterCell(long x) { value = x; }
2539 +    }
2540 +
2541      final long sumCount() {
2542 <        Cell[] as = counterCells; Cell a;
2542 >        CounterCell[] cs = counterCells;
2543          long sum = baseCount;
2544 <        if (as != null) {
2545 <            for (int i = 0; i < as.length; ++i) {
2546 <                if ((a = as[i]) != null)
2547 <                    sum += a.value;
2048 <            }
2544 >        if (cs != null) {
2545 >            for (CounterCell c : cs)
2546 >                if (c != null)
2547 >                    sum += c.value;
2548          }
2549          return sum;
2550      }
# Line 2060 | Line 2559 | public class ConcurrentHashMap<K,V>
2559          }
2560          boolean collide = false;                // True if last slot nonempty
2561          for (;;) {
2562 <            Cell[] as; Cell a; int n; long v;
2563 <            if ((as = counterCells) != null && (n = as.length) > 0) {
2564 <                if ((a = as[(n - 1) & h]) == null) {
2562 >            CounterCell[] cs; CounterCell c; int n; long v;
2563 >            if ((cs = counterCells) != null && (n = cs.length) > 0) {
2564 >                if ((c = cs[(n - 1) & h]) == null) {
2565                      if (cellsBusy == 0) {            // Try to attach new Cell
2566 <                        Cell r = new Cell(x); // Optimistic create
2566 >                        CounterCell r = new CounterCell(x); // Optimistic create
2567                          if (cellsBusy == 0 &&
2568 <                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2568 >                            U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {
2569                              boolean created = false;
2570                              try {               // Recheck under lock
2571 <                                Cell[] rs; int m, j;
2571 >                                CounterCell[] rs; int m, j;
2572                                  if ((rs = counterCells) != null &&
2573                                      (m = rs.length) > 0 &&
2574                                      rs[j = (m - 1) & h] == null) {
# Line 2088 | Line 2587 | public class ConcurrentHashMap<K,V>
2587                  }
2588                  else if (!wasUncontended)       // CAS already known to fail
2589                      wasUncontended = true;      // Continue after rehash
2590 <                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2590 >                else if (U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))
2591                      break;
2592 <                else if (counterCells != as || n >= NCPU)
2592 >                else if (counterCells != cs || n >= NCPU)
2593                      collide = false;            // At max size or stale
2594                  else if (!collide)
2595                      collide = true;
2596                  else if (cellsBusy == 0 &&
2597 <                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2597 >                         U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {
2598                      try {
2599 <                        if (counterCells == as) {// Expand table unless stale
2600 <                            Cell[] rs = new Cell[n << 1];
2102 <                            for (int i = 0; i < n; ++i)
2103 <                                rs[i] = as[i];
2104 <                            counterCells = rs;
2105 <                        }
2599 >                        if (counterCells == cs) // Expand table unless stale
2600 >                            counterCells = Arrays.copyOf(cs, n << 1);
2601                      } finally {
2602                          cellsBusy = 0;
2603                      }
# Line 2111 | Line 2606 | public class ConcurrentHashMap<K,V>
2606                  }
2607                  h = ThreadLocalRandom.advanceProbe(h);
2608              }
2609 <            else if (cellsBusy == 0 && counterCells == as &&
2610 <                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2609 >            else if (cellsBusy == 0 && counterCells == cs &&
2610 >                     U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {
2611                  boolean init = false;
2612                  try {                           // Initialize table
2613 <                    if (counterCells == as) {
2614 <                        Cell[] rs = new Cell[2];
2615 <                        rs[h & 1] = new Cell(x);
2613 >                    if (counterCells == cs) {
2614 >                        CounterCell[] rs = new CounterCell[2];
2615 >                        rs[h & 1] = new CounterCell(x);
2616                          counterCells = rs;
2617                          init = true;
2618                      }
# Line 2127 | Line 2622 | public class ConcurrentHashMap<K,V>
2622                  if (init)
2623                      break;
2624              }
2625 <            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2625 >            else if (U.compareAndSetLong(this, BASECOUNT, v = baseCount, v + x))
2626                  break;                          // Fall back on using base
2627          }
2628      }
2629  
2630 <    /* ----------------Table Traversal -------------- */
2630 >    /* ---------------- Conversion from/to TreeBins -------------- */
2631  
2632      /**
2633 <     * Encapsulates traversal for methods such as containsValue; also
2634 <     * serves as a base class for other iterators and bulk tasks.
2140 <     *
2141 <     * At each step, the iterator snapshots the key ("nextKey") and
2142 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2143 <     * snapshot, has a non-null user value). Because val fields can
2144 <     * change (including to null, indicating deletion), field nextVal
2145 <     * might not be accurate at point of use, but still maintains the
2146 <     * weak consistency property of holding a value that was once
2147 <     * valid. To support iterator.remove, the nextKey field is not
2148 <     * updated (nulled out) when the iterator cannot advance.
2149 <     *
2150 <     * Exported iterators must track whether the iterator has advanced
2151 <     * (in hasNext vs next) (by setting/checking/nulling field
2152 <     * nextVal), and then extract key, value, or key-value pairs as
2153 <     * return values of next().
2154 <     *
2155 <     * Method advance visits once each still-valid node that was
2156 <     * reachable upon iterator construction. It might miss some that
2157 <     * were added to a bin after the bin was visited, which is OK wrt
2158 <     * consistency guarantees. Maintaining this property in the face
2159 <     * of possible ongoing resizes requires a fair amount of
2160 <     * bookkeeping state that is difficult to optimize away amidst
2161 <     * volatile accesses.  Even so, traversal maintains reasonable
2162 <     * throughput.
2163 <     *
2164 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2165 <     * However, if the table has been resized, then all future steps
2166 <     * must traverse both the bin at the current index as well as at
2167 <     * (index + baseSize); and so on for further resizings. To
2168 <     * paranoically cope with potential sharing by users of iterators
2169 <     * across threads, iteration terminates if a bounds checks fails
2170 <     * for a table read.
2171 <     *
2172 <     * Methods advanceKey and advanceValue are specializations of the
2173 <     * common cases of advance, relaying to the full version
2174 <     * otherwise. The forEachKey and forEachValue methods further
2175 <     * specialize, bypassing all incremental field updates in most cases.
2176 <     *
2177 <     * This class supports both Spliterator-based traversal and
2178 <     * CountedCompleter-based bulk tasks. The same "batch" field is
2179 <     * used, but in slightly different ways, in the two cases.  For
2180 <     * Spliterators, it is a saturating (at Integer.MAX_VALUE)
2181 <     * estimate of element coverage. For CHM tasks, it is a pre-scaled
2182 <     * size that halves down to zero for leaf tasks, that is only
2183 <     * computed upon execution of the task. (Tasks can be submitted to
2184 <     * any pool, of any size, so we don't know scale factors until
2185 <     * running.)
2186 <     *
2187 <     * This class extends CountedCompleter to streamline parallel
2188 <     * iteration in bulk operations. This adds only a few fields of
2189 <     * space overhead, which is small enough in cases where it is not
2190 <     * needed to not worry about it.  Because CountedCompleter is
2191 <     * Serializable, but iterators need not be, we need to add warning
2192 <     * suppressions.
2633 >     * Replaces all linked nodes in bin at given index unless table is
2634 >     * too small, in which case resizes instead.
2635       */
2636 <    @SuppressWarnings("serial") static class Traverser<K,V,R>
2637 <        extends CountedCompleter<R> {
2638 <        final ConcurrentHashMap<K,V> map;
2639 <        Node<V> next;        // the next entry to use
2640 <        K nextKey;           // cached key field of next
2641 <        V nextVal;           // cached val field of next
2642 <        Node<V>[] tab;       // current table; updated if resized
2643 <        int index;           // index of bin to use next
2644 <        int baseIndex;       // current index of initial table
2645 <        int baseLimit;       // index bound for initial table
2646 <        final int baseSize;  // initial table size
2647 <        int batch;           // split control
2636 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2637 >        Node<K,V> b; int n;
2638 >        if (tab != null) {
2639 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
2640 >                tryPresize(n << 1);
2641 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2642 >                synchronized (b) {
2643 >                    if (tabAt(tab, index) == b) {
2644 >                        TreeNode<K,V> hd = null, tl = null;
2645 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2646 >                            TreeNode<K,V> p =
2647 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2648 >                                                  null, null);
2649 >                            if ((p.prev = tl) == null)
2650 >                                hd = p;
2651 >                            else
2652 >                                tl.next = p;
2653 >                            tl = p;
2654 >                        }
2655 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2656 >                    }
2657 >                }
2658 >            }
2659 >        }
2660 >    }
2661  
2662 <        /** Creates iterator for all entries in the table. */
2663 <        Traverser(ConcurrentHashMap<K,V> map) {
2664 <            this.map = map;
2665 <            Node<V>[] t = this.tab = map.table;
2666 <            baseLimit = baseSize = (t == null) ? 0 : t.length;
2662 >    /**
2663 >     * Returns a list of non-TreeNodes replacing those in given list.
2664 >     */
2665 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2666 >        Node<K,V> hd = null, tl = null;
2667 >        for (Node<K,V> q = b; q != null; q = q.next) {
2668 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val);
2669 >            if (tl == null)
2670 >                hd = p;
2671 >            else
2672 >                tl.next = p;
2673 >            tl = p;
2674          }
2675 +        return hd;
2676 +    }
2677  
2678 <        /** Task constructor */
2679 <        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it, int batch) {
2680 <            super(it);
2681 <            this.map = map;
2682 <            this.batch = batch; // -1 if unknown
2683 <            if (it == null) {
2684 <                Node<V>[] t = this.tab = map.table;
2685 <                baseLimit = baseSize = (t == null) ? 0 : t.length;
2686 <            }
2687 <            else { // split parent
2688 <                this.tab = it.tab;
2689 <                this.baseSize = it.baseSize;
2690 <                int hi = this.baseLimit = it.baseLimit;
2691 <                it.baseLimit = this.index = this.baseIndex =
2692 <                    (hi + it.baseIndex) >>> 1;
2693 <            }
2678 >    /* ---------------- TreeNodes -------------- */
2679 >
2680 >    /**
2681 >     * Nodes for use in TreeBins.
2682 >     */
2683 >    static final class TreeNode<K,V> extends Node<K,V> {
2684 >        TreeNode<K,V> parent;  // red-black tree links
2685 >        TreeNode<K,V> left;
2686 >        TreeNode<K,V> right;
2687 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2688 >        boolean red;
2689 >
2690 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2691 >                 TreeNode<K,V> parent) {
2692 >            super(hash, key, val, next);
2693 >            this.parent = parent;
2694          }
2695  
2696 <        /** Spliterator constructor */
2697 <        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it) {
2234 <            super(it);
2235 <            this.map = map;
2236 <            if (it == null) {
2237 <                Node<V>[] t = this.tab = map.table;
2238 <                baseLimit = baseSize = (t == null) ? 0 : t.length;
2239 <                long n = map.sumCount();
2240 <                batch = ((n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2241 <                         (int)n);
2242 <            }
2243 <            else {
2244 <                this.tab = it.tab;
2245 <                this.baseSize = it.baseSize;
2246 <                int hi = this.baseLimit = it.baseLimit;
2247 <                it.baseLimit = this.index = this.baseIndex =
2248 <                    (hi + it.baseIndex) >>> 1;
2249 <                this.batch = it.batch >>>= 1;
2250 <            }
2696 >        Node<K,V> find(int h, Object k) {
2697 >            return findTreeNode(h, k, null);
2698          }
2699  
2700          /**
2701 <         * Advances if possible, returning next valid value, or null if none.
2701 >         * Returns the TreeNode (or null if not found) for the given key
2702 >         * starting at given root.
2703           */
2704 <        @SuppressWarnings("unchecked") final V advance() {
2705 <            for (Node<V> e = next;;) {
2706 <                if (e != null)                  // advance past used/skipped node
2707 <                    e = next = e.next;
2708 <                while (e == null) {             // get to next non-null bin
2709 <                    Node<V>[] t; int i, n;      // must use locals in checks
2710 <                    if (baseIndex >= baseLimit || (t = tab) == null ||
2711 <                        (n = t.length) <= (i = index) || i < 0)
2712 <                        return nextVal = null;
2713 <                    if ((e = next = tabAt(t, index)) != null && e.hash < 0) {
2714 <                        Object ek;
2715 <                        if ((ek = e.key) instanceof TreeBin)
2716 <                            e = ((TreeBin<V>)ek).first;
2717 <                        else {
2718 <                            tab = (Node<V>[])ek;
2719 <                            continue;           // restarts due to null val
2704 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2705 >            if (k != null) {
2706 >                TreeNode<K,V> p = this;
2707 >                do {
2708 >                    int ph, dir; K pk; TreeNode<K,V> q;
2709 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2710 >                    if ((ph = p.hash) > h)
2711 >                        p = pl;
2712 >                    else if (ph < h)
2713 >                        p = pr;
2714 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2715 >                        return p;
2716 >                    else if (pl == null)
2717 >                        p = pr;
2718 >                    else if (pr == null)
2719 >                        p = pl;
2720 >                    else if ((kc != null ||
2721 >                              (kc = comparableClassFor(k)) != null) &&
2722 >                             (dir = compareComparables(kc, k, pk)) != 0)
2723 >                        p = (dir < 0) ? pl : pr;
2724 >                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
2725 >                        return q;
2726 >                    else
2727 >                        p = pl;
2728 >                } while (p != null);
2729 >            }
2730 >            return null;
2731 >        }
2732 >    }
2733 >
2734 >    /* ---------------- TreeBins -------------- */
2735 >
2736 >    /**
2737 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2738 >     * keys or values, but instead point to list of TreeNodes and
2739 >     * their root. They also maintain a parasitic read-write lock
2740 >     * forcing writers (who hold bin lock) to wait for readers (who do
2741 >     * not) to complete before tree restructuring operations.
2742 >     */
2743 >    static final class TreeBin<K,V> extends Node<K,V> {
2744 >        TreeNode<K,V> root;
2745 >        volatile TreeNode<K,V> first;
2746 >        volatile Thread waiter;
2747 >        volatile int lockState;
2748 >        // values for lockState
2749 >        static final int WRITER = 1; // set while holding write lock
2750 >        static final int WAITER = 2; // set when waiting for write lock
2751 >        static final int READER = 4; // increment value for setting read lock
2752 >
2753 >        /**
2754 >         * Tie-breaking utility for ordering insertions when equal
2755 >         * hashCodes and non-comparable. We don't require a total
2756 >         * order, just a consistent insertion rule to maintain
2757 >         * equivalence across rebalancings. Tie-breaking further than
2758 >         * necessary simplifies testing a bit.
2759 >         */
2760 >        static int tieBreakOrder(Object a, Object b) {
2761 >            int d;
2762 >            if (a == null || b == null ||
2763 >                (d = a.getClass().getName().
2764 >                 compareTo(b.getClass().getName())) == 0)
2765 >                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2766 >                     -1 : 1);
2767 >            return d;
2768 >        }
2769 >
2770 >        /**
2771 >         * Creates bin with initial set of nodes headed by b.
2772 >         */
2773 >        TreeBin(TreeNode<K,V> b) {
2774 >            super(TREEBIN, null, null);
2775 >            this.first = b;
2776 >            TreeNode<K,V> r = null;
2777 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2778 >                next = (TreeNode<K,V>)x.next;
2779 >                x.left = x.right = null;
2780 >                if (r == null) {
2781 >                    x.parent = null;
2782 >                    x.red = false;
2783 >                    r = x;
2784 >                }
2785 >                else {
2786 >                    K k = x.key;
2787 >                    int h = x.hash;
2788 >                    Class<?> kc = null;
2789 >                    for (TreeNode<K,V> p = r;;) {
2790 >                        int dir, ph;
2791 >                        K pk = p.key;
2792 >                        if ((ph = p.hash) > h)
2793 >                            dir = -1;
2794 >                        else if (ph < h)
2795 >                            dir = 1;
2796 >                        else if ((kc == null &&
2797 >                                  (kc = comparableClassFor(k)) == null) ||
2798 >                                 (dir = compareComparables(kc, k, pk)) == 0)
2799 >                            dir = tieBreakOrder(k, pk);
2800 >                        TreeNode<K,V> xp = p;
2801 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2802 >                            x.parent = xp;
2803 >                            if (dir <= 0)
2804 >                                xp.left = x;
2805 >                            else
2806 >                                xp.right = x;
2807 >                            r = balanceInsertion(r, x);
2808 >                            break;
2809                          }
2810                      }
2274                    if ((index += baseSize) >= n)
2275                        index = ++baseIndex;    // visit upper slots if present
2811                  }
2277                nextKey = (K)e.key;
2278                if ((nextVal = e.val) != null) // skip deleted or special nodes
2279                    return nextVal;
2812              }
2813 +            this.root = r;
2814 +            assert checkInvariants(root);
2815          }
2816  
2817          /**
2818 <         * Common case version for value traversal
2818 >         * Acquires write lock for tree restructuring.
2819           */
2820 <        @SuppressWarnings("unchecked") final V advanceValue() {
2821 <            outer: for (Node<V> e = next;;) {
2822 <                if (e == null || (e = e.next) == null) {
2823 <                    Node<V>[] t; int i, len, n; Object ek;
2824 <                    if ((t = tab) == null ||
2825 <                        baseSize != (len = t.length) ||
2826 <                        len < (n = baseLimit) ||
2827 <                        baseIndex != (i = index))
2828 <                        break;
2829 <                    do {
2830 <                        if (i < 0 || i >= n) {
2831 <                            index = baseIndex = n;
2832 <                            next = null;
2833 <                            return nextVal = null;
2834 <                        }
2835 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2836 <                            if ((ek = e.key) instanceof TreeBin)
2837 <                                e = ((TreeBin<V>)ek).first;
2838 <                            else {
2839 <                                index = baseIndex = i;
2840 <                                next = null;
2841 <                                tab = (Node<V>[])ek;
2842 <                                break outer;
2843 <                            }
2310 <                        }
2311 <                        ++i;
2312 <                    } while (e == null);
2313 <                    index = baseIndex = i;
2820 >        private final void lockRoot() {
2821 >            if (!U.compareAndSetInt(this, LOCKSTATE, 0, WRITER))
2822 >                contendedLock(); // offload to separate method
2823 >        }
2824 >
2825 >        /**
2826 >         * Releases write lock for tree restructuring.
2827 >         */
2828 >        private final void unlockRoot() {
2829 >            lockState = 0;
2830 >        }
2831 >
2832 >        /**
2833 >         * Possibly blocks awaiting root lock.
2834 >         */
2835 >        private final void contendedLock() {
2836 >            boolean waiting = false;
2837 >            for (int s;;) {
2838 >                if (((s = lockState) & ~WAITER) == 0) {
2839 >                    if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {
2840 >                        if (waiting)
2841 >                            waiter = null;
2842 >                        return;
2843 >                    }
2844                  }
2845 <                V v;
2846 <                K k = (K)e.key;
2847 <                if ((v = e.val) != null) {
2848 <                    nextVal = v;
2849 <                    nextKey = k;
2320 <                    next = e;
2321 <                    return v;
2845 >                else if ((s & WAITER) == 0) {
2846 >                    if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {
2847 >                        waiting = true;
2848 >                        waiter = Thread.currentThread();
2849 >                    }
2850                  }
2851 +                else if (waiting)
2852 +                    LockSupport.park(this);
2853              }
2324            return advance();
2854          }
2855  
2856          /**
2857 <         * Common case version for key traversal
2857 >         * Returns matching node or null if none. Tries to search
2858 >         * using tree comparisons from root, but continues linear
2859 >         * search when lock not available.
2860           */
2861 <        @SuppressWarnings("unchecked") final K advanceKey() {
2862 <            outer: for (Node<V> e = next;;) {
2863 <                if (e == null || (e = e.next) == null) {
2864 <                    Node<V>[] t; int i, len, n; Object ek;
2865 <                    if ((t = tab) == null ||
2866 <                        baseSize != (len = t.length) ||
2867 <                        len < (n = baseLimit) ||
2868 <                        baseIndex != (i = index))
2869 <                        break;
2870 <                    do {
2871 <                        if (i < 0 || i >= n) {
2872 <                            index = baseIndex = n;
2873 <                            next = null;
2874 <                            nextVal = null;
2875 <                            return null;
2876 <                        }
2877 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2878 <                            if ((ek = e.key) instanceof TreeBin)
2879 <                                e = ((TreeBin<V>)ek).first;
2880 <                            else {
2881 <                                index = baseIndex = i;
2351 <                                next = null;
2352 <                                tab = (Node<V>[])ek;
2353 <                                break outer;
2354 <                            }
2861 >        final Node<K,V> find(int h, Object k) {
2862 >            if (k != null) {
2863 >                for (Node<K,V> e = first; e != null; ) {
2864 >                    int s; K ek;
2865 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2866 >                        if (e.hash == h &&
2867 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2868 >                            return e;
2869 >                        e = e.next;
2870 >                    }
2871 >                    else if (U.compareAndSetInt(this, LOCKSTATE, s,
2872 >                                                 s + READER)) {
2873 >                        TreeNode<K,V> r, p;
2874 >                        try {
2875 >                            p = ((r = root) == null ? null :
2876 >                                 r.findTreeNode(h, k, null));
2877 >                        } finally {
2878 >                            Thread w;
2879 >                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2880 >                                (READER|WAITER) && (w = waiter) != null)
2881 >                                LockSupport.unpark(w);
2882                          }
2883 <                        ++i;
2884 <                    } while (e == null);
2358 <                    index = baseIndex = i;
2359 <                }
2360 <                V v;
2361 <                K k = (K)e.key;
2362 <                if ((v = e.val) != null) {
2363 <                    nextVal = v;
2364 <                    nextKey = k;
2365 <                    next = e;
2366 <                    return k;
2883 >                        return p;
2884 >                    }
2885                  }
2886              }
2887 <            return (advance() == null) ? null : nextKey;
2887 >            return null;
2888          }
2889  
2890 <        @SuppressWarnings("unchecked") final void forEachValue(Consumer<? super V> action) {
2891 <            if (action == null) throw new NullPointerException();
2892 <            Node<V>[] t; int i, len, n;
2893 <            if ((t = tab) != null && baseSize == (len = t.length) &&
2894 <                len >= (n = baseLimit) && baseIndex == (i = index)) {
2895 <                index = baseIndex = n;
2896 <                nextVal = null;
2897 <                Node<V> e = next;
2898 <                next = null;
2899 <                if (e != null)
2900 <                    e = e.next;
2901 <                outer: for (;; e = e.next) {
2902 <                    V v; Object ek;
2903 <                    for (; e == null; ++i) {
2904 <                        if (i < 0 || i >= n)
2905 <                            return;
2906 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2907 <                            if ((ek = e.key) instanceof TreeBin)
2908 <                                e = ((TreeBin<V>)ek).first;
2909 <                            else {
2910 <                                index = baseIndex = i;
2911 <                                tab = (Node<V>[])ek;
2912 <                                break outer;
2913 <                            }
2890 >        /**
2891 >         * Finds or adds a node.
2892 >         * @return null if added
2893 >         */
2894 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2895 >            Class<?> kc = null;
2896 >            boolean searched = false;
2897 >            for (TreeNode<K,V> p = root;;) {
2898 >                int dir, ph; K pk;
2899 >                if (p == null) {
2900 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2901 >                    break;
2902 >                }
2903 >                else if ((ph = p.hash) > h)
2904 >                    dir = -1;
2905 >                else if (ph < h)
2906 >                    dir = 1;
2907 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2908 >                    return p;
2909 >                else if ((kc == null &&
2910 >                          (kc = comparableClassFor(k)) == null) ||
2911 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2912 >                    if (!searched) {
2913 >                        TreeNode<K,V> q, ch;
2914 >                        searched = true;
2915 >                        if (((ch = p.left) != null &&
2916 >                             (q = ch.findTreeNode(h, k, kc)) != null) ||
2917 >                            ((ch = p.right) != null &&
2918 >                             (q = ch.findTreeNode(h, k, kc)) != null))
2919 >                            return q;
2920 >                    }
2921 >                    dir = tieBreakOrder(k, pk);
2922 >                }
2923 >
2924 >                TreeNode<K,V> xp = p;
2925 >                if ((p = (dir <= 0) ? p.left : p.right) == null) {
2926 >                    TreeNode<K,V> x, f = first;
2927 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2928 >                    if (f != null)
2929 >                        f.prev = x;
2930 >                    if (dir <= 0)
2931 >                        xp.left = x;
2932 >                    else
2933 >                        xp.right = x;
2934 >                    if (!xp.red)
2935 >                        x.red = true;
2936 >                    else {
2937 >                        lockRoot();
2938 >                        try {
2939 >                            root = balanceInsertion(root, x);
2940 >                        } finally {
2941 >                            unlockRoot();
2942                          }
2943                      }
2944 <                    if ((v = e.val) != null)
2399 <                        action.accept(v);
2944 >                    break;
2945                  }
2946              }
2947 <            V v;
2948 <            while ((v = advance()) != null)
2404 <                action.accept(v);
2947 >            assert checkInvariants(root);
2948 >            return null;
2949          }
2950  
2951 <        @SuppressWarnings("unchecked") final void forEachKey(Consumer<? super K> action) {
2952 <            if (action == null) throw new NullPointerException();
2953 <            Node<V>[] t; int i, len, n;
2954 <            if ((t = tab) != null && baseSize == (len = t.length) &&
2955 <                len >= (n = baseLimit) && baseIndex == (i = index)) {
2956 <                index = baseIndex = n;
2957 <                nextVal = null;
2958 <                Node<V> e = next;
2959 <                next = null;
2960 <                if (e != null)
2961 <                    e = e.next;
2962 <                outer: for (;; e = e.next) {
2963 <                    for (; e == null; ++i) {
2964 <                        if (i < 0 || i >= n)
2965 <                            return;
2966 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2967 <                            Object ek;
2968 <                            if ((ek = e.key) instanceof TreeBin)
2969 <                                e = ((TreeBin<V>)ek).first;
2970 <                            else {
2971 <                                index = baseIndex = i;
2972 <                                tab = (Node<V>[])ek;
2973 <                                break outer;
2974 <                            }
2951 >        /**
2952 >         * Removes the given node, that must be present before this
2953 >         * call.  This is messier than typical red-black deletion code
2954 >         * because we cannot swap the contents of an interior node
2955 >         * with a leaf successor that is pinned by "next" pointers
2956 >         * that are accessible independently of lock. So instead we
2957 >         * swap the tree linkages.
2958 >         *
2959 >         * @return true if now too small, so should be untreeified
2960 >         */
2961 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2962 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2963 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2964 >            TreeNode<K,V> r, rl;
2965 >            if (pred == null)
2966 >                first = next;
2967 >            else
2968 >                pred.next = next;
2969 >            if (next != null)
2970 >                next.prev = pred;
2971 >            if (first == null) {
2972 >                root = null;
2973 >                return true;
2974 >            }
2975 >            if ((r = root) == null || r.right == null || // too small
2976 >                (rl = r.left) == null || rl.left == null)
2977 >                return true;
2978 >            lockRoot();
2979 >            try {
2980 >                TreeNode<K,V> replacement;
2981 >                TreeNode<K,V> pl = p.left;
2982 >                TreeNode<K,V> pr = p.right;
2983 >                if (pl != null && pr != null) {
2984 >                    TreeNode<K,V> s = pr, sl;
2985 >                    while ((sl = s.left) != null) // find successor
2986 >                        s = sl;
2987 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2988 >                    TreeNode<K,V> sr = s.right;
2989 >                    TreeNode<K,V> pp = p.parent;
2990 >                    if (s == pr) { // p was s's direct parent
2991 >                        p.parent = s;
2992 >                        s.right = p;
2993 >                    }
2994 >                    else {
2995 >                        TreeNode<K,V> sp = s.parent;
2996 >                        if ((p.parent = sp) != null) {
2997 >                            if (s == sp.left)
2998 >                                sp.left = p;
2999 >                            else
3000 >                                sp.right = p;
3001                          }
3002 +                        if ((s.right = pr) != null)
3003 +                            pr.parent = s;
3004                      }
3005 <                    Object k = e.key;
3006 <                    if (e.val != null)
3007 <                        action.accept((K)k);
3005 >                    p.left = null;
3006 >                    if ((p.right = sr) != null)
3007 >                        sr.parent = p;
3008 >                    if ((s.left = pl) != null)
3009 >                        pl.parent = s;
3010 >                    if ((s.parent = pp) == null)
3011 >                        r = s;
3012 >                    else if (p == pp.left)
3013 >                        pp.left = s;
3014 >                    else
3015 >                        pp.right = s;
3016 >                    if (sr != null)
3017 >                        replacement = sr;
3018 >                    else
3019 >                        replacement = p;
3020 >                }
3021 >                else if (pl != null)
3022 >                    replacement = pl;
3023 >                else if (pr != null)
3024 >                    replacement = pr;
3025 >                else
3026 >                    replacement = p;
3027 >                if (replacement != p) {
3028 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
3029 >                    if (pp == null)
3030 >                        r = replacement;
3031 >                    else if (p == pp.left)
3032 >                        pp.left = replacement;
3033 >                    else
3034 >                        pp.right = replacement;
3035 >                    p.left = p.right = p.parent = null;
3036                  }
3037 +
3038 +                root = (p.red) ? r : balanceDeletion(r, replacement);
3039 +
3040 +                if (p == replacement) {  // detach pointers
3041 +                    TreeNode<K,V> pp;
3042 +                    if ((pp = p.parent) != null) {
3043 +                        if (p == pp.left)
3044 +                            pp.left = null;
3045 +                        else if (p == pp.right)
3046 +                            pp.right = null;
3047 +                        p.parent = null;
3048 +                    }
3049 +                }
3050 +            } finally {
3051 +                unlockRoot();
3052              }
3053 <            while (advance() != null)
3054 <                action.accept(nextKey);
3053 >            assert checkInvariants(root);
3054 >            return false;
3055          }
3056  
3057 <        public final void remove() {
3058 <            K k = nextKey;
2444 <            if (k == null && (advanceValue() == null || (k = nextKey) == null))
2445 <                throw new IllegalStateException();
2446 <            map.internalReplace(k, null, null);
2447 <        }
3057 >        /* ------------------------------------------------------------ */
3058 >        // Red-black tree methods, all adapted from CLR
3059  
3060 <        public final boolean hasNext() {
3061 <            return nextVal != null || advanceValue() != null;
3060 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
3061 >                                              TreeNode<K,V> p) {
3062 >            TreeNode<K,V> r, pp, rl;
3063 >            if (p != null && (r = p.right) != null) {
3064 >                if ((rl = p.right = r.left) != null)
3065 >                    rl.parent = p;
3066 >                if ((pp = r.parent = p.parent) == null)
3067 >                    (root = r).red = false;
3068 >                else if (pp.left == p)
3069 >                    pp.left = r;
3070 >                else
3071 >                    pp.right = r;
3072 >                r.left = p;
3073 >                p.parent = r;
3074 >            }
3075 >            return root;
3076          }
3077  
3078 <        public final boolean hasMoreElements() { return hasNext(); }
3078 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
3079 >                                               TreeNode<K,V> p) {
3080 >            TreeNode<K,V> l, pp, lr;
3081 >            if (p != null && (l = p.left) != null) {
3082 >                if ((lr = p.left = l.right) != null)
3083 >                    lr.parent = p;
3084 >                if ((pp = l.parent = p.parent) == null)
3085 >                    (root = l).red = false;
3086 >                else if (pp.right == p)
3087 >                    pp.right = l;
3088 >                else
3089 >                    pp.left = l;
3090 >                l.right = p;
3091 >                p.parent = l;
3092 >            }
3093 >            return root;
3094 >        }
3095  
3096 <        public void compute() { } // default no-op CountedCompleter body
3096 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
3097 >                                                    TreeNode<K,V> x) {
3098 >            x.red = true;
3099 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
3100 >                if ((xp = x.parent) == null) {
3101 >                    x.red = false;
3102 >                    return x;
3103 >                }
3104 >                else if (!xp.red || (xpp = xp.parent) == null)
3105 >                    return root;
3106 >                if (xp == (xppl = xpp.left)) {
3107 >                    if ((xppr = xpp.right) != null && xppr.red) {
3108 >                        xppr.red = false;
3109 >                        xp.red = false;
3110 >                        xpp.red = true;
3111 >                        x = xpp;
3112 >                    }
3113 >                    else {
3114 >                        if (x == xp.right) {
3115 >                            root = rotateLeft(root, x = xp);
3116 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3117 >                        }
3118 >                        if (xp != null) {
3119 >                            xp.red = false;
3120 >                            if (xpp != null) {
3121 >                                xpp.red = true;
3122 >                                root = rotateRight(root, xpp);
3123 >                            }
3124 >                        }
3125 >                    }
3126 >                }
3127 >                else {
3128 >                    if (xppl != null && xppl.red) {
3129 >                        xppl.red = false;
3130 >                        xp.red = false;
3131 >                        xpp.red = true;
3132 >                        x = xpp;
3133 >                    }
3134 >                    else {
3135 >                        if (x == xp.left) {
3136 >                            root = rotateRight(root, x = xp);
3137 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3138 >                        }
3139 >                        if (xp != null) {
3140 >                            xp.red = false;
3141 >                            if (xpp != null) {
3142 >                                xpp.red = true;
3143 >                                root = rotateLeft(root, xpp);
3144 >                            }
3145 >                        }
3146 >                    }
3147 >                }
3148 >            }
3149 >        }
3150  
3151 <        public long estimateSize() { return batch; }
3151 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3152 >                                                   TreeNode<K,V> x) {
3153 >            for (TreeNode<K,V> xp, xpl, xpr;;) {
3154 >                if (x == null || x == root)
3155 >                    return root;
3156 >                else if ((xp = x.parent) == null) {
3157 >                    x.red = false;
3158 >                    return x;
3159 >                }
3160 >                else if (x.red) {
3161 >                    x.red = false;
3162 >                    return root;
3163 >                }
3164 >                else if ((xpl = xp.left) == x) {
3165 >                    if ((xpr = xp.right) != null && xpr.red) {
3166 >                        xpr.red = false;
3167 >                        xp.red = true;
3168 >                        root = rotateLeft(root, xp);
3169 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3170 >                    }
3171 >                    if (xpr == null)
3172 >                        x = xp;
3173 >                    else {
3174 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3175 >                        if ((sr == null || !sr.red) &&
3176 >                            (sl == null || !sl.red)) {
3177 >                            xpr.red = true;
3178 >                            x = xp;
3179 >                        }
3180 >                        else {
3181 >                            if (sr == null || !sr.red) {
3182 >                                if (sl != null)
3183 >                                    sl.red = false;
3184 >                                xpr.red = true;
3185 >                                root = rotateRight(root, xpr);
3186 >                                xpr = (xp = x.parent) == null ?
3187 >                                    null : xp.right;
3188 >                            }
3189 >                            if (xpr != null) {
3190 >                                xpr.red = (xp == null) ? false : xp.red;
3191 >                                if ((sr = xpr.right) != null)
3192 >                                    sr.red = false;
3193 >                            }
3194 >                            if (xp != null) {
3195 >                                xp.red = false;
3196 >                                root = rotateLeft(root, xp);
3197 >                            }
3198 >                            x = root;
3199 >                        }
3200 >                    }
3201 >                }
3202 >                else { // symmetric
3203 >                    if (xpl != null && xpl.red) {
3204 >                        xpl.red = false;
3205 >                        xp.red = true;
3206 >                        root = rotateRight(root, xp);
3207 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3208 >                    }
3209 >                    if (xpl == null)
3210 >                        x = xp;
3211 >                    else {
3212 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3213 >                        if ((sl == null || !sl.red) &&
3214 >                            (sr == null || !sr.red)) {
3215 >                            xpl.red = true;
3216 >                            x = xp;
3217 >                        }
3218 >                        else {
3219 >                            if (sl == null || !sl.red) {
3220 >                                if (sr != null)
3221 >                                    sr.red = false;
3222 >                                xpl.red = true;
3223 >                                root = rotateLeft(root, xpl);
3224 >                                xpl = (xp = x.parent) == null ?
3225 >                                    null : xp.left;
3226 >                            }
3227 >                            if (xpl != null) {
3228 >                                xpl.red = (xp == null) ? false : xp.red;
3229 >                                if ((sl = xpl.left) != null)
3230 >                                    sl.red = false;
3231 >                            }
3232 >                            if (xp != null) {
3233 >                                xp.red = false;
3234 >                                root = rotateRight(root, xp);
3235 >                            }
3236 >                            x = root;
3237 >                        }
3238 >                    }
3239 >                }
3240 >            }
3241 >        }
3242  
3243          /**
3244 <         * Returns a batch value > 0 if this task should (and must) be
2461 <         * split, if so, adding to pending count, and in any case
2462 <         * updating batch value. The initial batch value is approx
2463 <         * exp2 of the number of times (minus one) to split task by
2464 <         * two before executing leaf action. This value is faster to
2465 <         * compute and more convenient to use as a guide to splitting
2466 <         * than is the depth, since it is used while dividing by two
2467 <         * anyway.
3244 >         * Checks invariants recursively for the tree of Nodes rooted at t.
3245           */
3246 <        final int preSplit() {
3247 <            int b;  ForkJoinPool pool;
3248 <            if ((b = batch) < 0) { // force initialization
3249 <                int sp = (((pool = getPool()) == null) ?
3250 <                          ForkJoinPool.getCommonPoolParallelism() :
3251 <                          pool.getParallelism()) << 3; // slack of 8
3252 <                long n = map.sumCount();
3253 <                b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
3254 <            }
3255 <            b = (b <= 1 || baseIndex >= baseLimit) ? 0 : (b >>> 1);
3256 <            if ((batch = b) > 0)
3257 <                addToPendingCount(1);
3258 <            return b;
3246 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3247 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3248 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3249 >            if (tb != null && tb.next != t)
3250 >                return false;
3251 >            if (tn != null && tn.prev != t)
3252 >                return false;
3253 >            if (tp != null && t != tp.left && t != tp.right)
3254 >                return false;
3255 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3256 >                return false;
3257 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3258 >                return false;
3259 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3260 >                return false;
3261 >            if (tl != null && !checkInvariants(tl))
3262 >                return false;
3263 >            if (tr != null && !checkInvariants(tr))
3264 >                return false;
3265 >            return true;
3266          }
2483    }
3267  
3268 <    /* ---------------- Public operations -------------- */
3269 <
2487 <    /**
2488 <     * Creates a new, empty map with the default initial table size (16).
2489 <     */
2490 <    public ConcurrentHashMap() {
3268 >        private static final long LOCKSTATE
3269 >            = U.objectFieldOffset(TreeBin.class, "lockState");
3270      }
3271  
3272 <    /**
2494 <     * Creates a new, empty map with an initial table size
2495 <     * accommodating the specified number of elements without the need
2496 <     * to dynamically resize.
2497 <     *
2498 <     * @param initialCapacity The implementation performs internal
2499 <     * sizing to accommodate this many elements.
2500 <     * @throws IllegalArgumentException if the initial capacity of
2501 <     * elements is negative
2502 <     */
2503 <    public ConcurrentHashMap(int initialCapacity) {
2504 <        if (initialCapacity < 0)
2505 <            throw new IllegalArgumentException();
2506 <        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2507 <                   MAXIMUM_CAPACITY :
2508 <                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2509 <        this.sizeCtl = cap;
2510 <    }
2511 <
2512 <    /**
2513 <     * Creates a new map with the same mappings as the given map.
2514 <     *
2515 <     * @param m the map
2516 <     */
2517 <    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2518 <        this.sizeCtl = DEFAULT_CAPACITY;
2519 <        internalPutAll(m);
2520 <    }
2521 <
2522 <    /**
2523 <     * Creates a new, empty map with an initial table size based on
2524 <     * the given number of elements ({@code initialCapacity}) and
2525 <     * initial table density ({@code loadFactor}).
2526 <     *
2527 <     * @param initialCapacity the initial capacity. The implementation
2528 <     * performs internal sizing to accommodate this many elements,
2529 <     * given the specified load factor.
2530 <     * @param loadFactor the load factor (table density) for
2531 <     * establishing the initial table size
2532 <     * @throws IllegalArgumentException if the initial capacity of
2533 <     * elements is negative or the load factor is nonpositive
2534 <     *
2535 <     * @since 1.6
2536 <     */
2537 <    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
2538 <        this(initialCapacity, loadFactor, 1);
2539 <    }
2540 <
2541 <    /**
2542 <     * Creates a new, empty map with an initial table size based on
2543 <     * the given number of elements ({@code initialCapacity}), table
2544 <     * density ({@code loadFactor}), and number of concurrently
2545 <     * updating threads ({@code concurrencyLevel}).
2546 <     *
2547 <     * @param initialCapacity the initial capacity. The implementation
2548 <     * performs internal sizing to accommodate this many elements,
2549 <     * given the specified load factor.
2550 <     * @param loadFactor the load factor (table density) for
2551 <     * establishing the initial table size
2552 <     * @param concurrencyLevel the estimated number of concurrently
2553 <     * updating threads. The implementation may use this value as
2554 <     * a sizing hint.
2555 <     * @throws IllegalArgumentException if the initial capacity is
2556 <     * negative or the load factor or concurrencyLevel are
2557 <     * nonpositive
2558 <     */
2559 <    public ConcurrentHashMap(int initialCapacity,
2560 <                               float loadFactor, int concurrencyLevel) {
2561 <        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2562 <            throw new IllegalArgumentException();
2563 <        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2564 <            initialCapacity = concurrencyLevel;   // as estimated threads
2565 <        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2566 <        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2567 <            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2568 <        this.sizeCtl = cap;
2569 <    }
2570 <
2571 <    /**
2572 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2573 <     * from the given type to {@code Boolean.TRUE}.
2574 <     *
2575 <     * @return the new set
2576 <     */
2577 <    public static <K> KeySetView<K,Boolean> newKeySet() {
2578 <        return new KeySetView<K,Boolean>
2579 <            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2580 <    }
2581 <
2582 <    /**
2583 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2584 <     * from the given type to {@code Boolean.TRUE}.
2585 <     *
2586 <     * @param initialCapacity The implementation performs internal
2587 <     * sizing to accommodate this many elements.
2588 <     * @throws IllegalArgumentException if the initial capacity of
2589 <     * elements is negative
2590 <     * @return the new set
2591 <     */
2592 <    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2593 <        return new KeySetView<K,Boolean>
2594 <            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2595 <    }
2596 <
2597 <    /**
2598 <     * {@inheritDoc}
2599 <     */
2600 <    public boolean isEmpty() {
2601 <        return sumCount() <= 0L; // ignore transient negative values
2602 <    }
2603 <
2604 <    /**
2605 <     * {@inheritDoc}
2606 <     */
2607 <    public int size() {
2608 <        long n = sumCount();
2609 <        return ((n < 0L) ? 0 :
2610 <                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2611 <                (int)n);
2612 <    }
2613 <
2614 <    /**
2615 <     * Returns the number of mappings. This method should be used
2616 <     * instead of {@link #size} because a ConcurrentHashMap may
2617 <     * contain more mappings than can be represented as an int. The
2618 <     * value returned is an estimate; the actual count may differ if
2619 <     * there are concurrent insertions or removals.
2620 <     *
2621 <     * @return the number of mappings
2622 <     */
2623 <    public long mappingCount() {
2624 <        long n = sumCount();
2625 <        return (n < 0L) ? 0L : n; // ignore transient negative values
2626 <    }
2627 <
2628 <    /**
2629 <     * Returns the value to which the specified key is mapped,
2630 <     * or {@code null} if this map contains no mapping for the key.
2631 <     *
2632 <     * <p>More formally, if this map contains a mapping from a key
2633 <     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2634 <     * then this method returns {@code v}; otherwise it returns
2635 <     * {@code null}.  (There can be at most one such mapping.)
2636 <     *
2637 <     * @throws NullPointerException if the specified key is null
2638 <     */
2639 <    public V get(Object key) {
2640 <        return internalGet(key);
2641 <    }
3272 >    /* ----------------Table Traversal -------------- */
3273  
3274      /**
3275 <     * Returns the value to which the specified key is mapped,
3276 <     * or the given defaultValue if this map contains no mapping for the key.
3277 <     *
3278 <     * @param key the key
3279 <     * @param defaultValue the value to return if this map contains
3280 <     * no mapping for the given key
3281 <     * @return the mapping for the key, if present; else the defaultValue
3282 <     * @throws NullPointerException if the specified key is null
3283 <     */
2653 <    public V getOrDefault(Object key, V defaultValue) {
2654 <        V v;
2655 <        return (v = internalGet(key)) == null ? defaultValue : v;
3275 >     * Records the table, its length, and current traversal index for a
3276 >     * traverser that must process a region of a forwarded table before
3277 >     * proceeding with current table.
3278 >     */
3279 >    static final class TableStack<K,V> {
3280 >        int length;
3281 >        int index;
3282 >        Node<K,V>[] tab;
3283 >        TableStack<K,V> next;
3284      }
3285  
3286      /**
3287 <     * Tests if the specified object is a key in this table.
3287 >     * Encapsulates traversal for methods such as containsValue; also
3288 >     * serves as a base class for other iterators and spliterators.
3289       *
3290 <     * @param  key possible key
3291 <     * @return {@code true} if and only if the specified object
3292 <     *         is a key in this table, as determined by the
3293 <     *         {@code equals} method; {@code false} otherwise
3294 <     * @throws NullPointerException if the specified key is null
3295 <     */
3296 <    public boolean containsKey(Object key) {
3297 <        return internalGet(key) != null;
2669 <    }
2670 <
2671 <    /**
2672 <     * Returns {@code true} if this map maps one or more keys to the
2673 <     * specified value. Note: This method may require a full traversal
2674 <     * of the map, and is much slower than method {@code containsKey}.
3290 >     * Method advance visits once each still-valid node that was
3291 >     * reachable upon iterator construction. It might miss some that
3292 >     * were added to a bin after the bin was visited, which is OK wrt
3293 >     * consistency guarantees. Maintaining this property in the face
3294 >     * of possible ongoing resizes requires a fair amount of
3295 >     * bookkeeping state that is difficult to optimize away amidst
3296 >     * volatile accesses.  Even so, traversal maintains reasonable
3297 >     * throughput.
3298       *
3299 <     * @param value value whose presence in this map is to be tested
3300 <     * @return {@code true} if this map maps one or more keys to the
3301 <     *         specified value
3302 <     * @throws NullPointerException if the specified value is null
3299 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3300 >     * However, if the table has been resized, then all future steps
3301 >     * must traverse both the bin at the current index as well as at
3302 >     * (index + baseSize); and so on for further resizings. To
3303 >     * paranoically cope with potential sharing by users of iterators
3304 >     * across threads, iteration terminates if a bounds checks fails
3305 >     * for a table read.
3306       */
3307 <    public boolean containsValue(Object value) {
3308 <        if (value == null)
3309 <            throw new NullPointerException();
3310 <        V v;
3311 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3312 <        while ((v = it.advanceValue()) != null) {
3313 <            if (v == value || value.equals(v))
3314 <                return true;
3307 >    static class Traverser<K,V> {
3308 >        Node<K,V>[] tab;        // current table; updated if resized
3309 >        Node<K,V> next;         // the next entry to use
3310 >        TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3311 >        int index;              // index of bin to use next
3312 >        int baseIndex;          // current index of initial table
3313 >        int baseLimit;          // index bound for initial table
3314 >        final int baseSize;     // initial table size
3315 >
3316 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3317 >            this.tab = tab;
3318 >            this.baseSize = size;
3319 >            this.baseIndex = this.index = index;
3320 >            this.baseLimit = limit;
3321 >            this.next = null;
3322          }
2690        return false;
2691    }
2692
2693    /**
2694     * Legacy method testing if some key maps into the specified value
2695     * in this table.  This method is identical in functionality to
2696     * {@link #containsValue(Object)}, and exists solely to ensure
2697     * full compatibility with class {@link java.util.Hashtable},
2698     * which supported this method prior to introduction of the
2699     * Java Collections framework.
2700     *
2701     * @param  value a value to search for
2702     * @return {@code true} if and only if some key maps to the
2703     *         {@code value} argument in this table as
2704     *         determined by the {@code equals} method;
2705     *         {@code false} otherwise
2706     * @throws NullPointerException if the specified value is null
2707     */
2708    @Deprecated public boolean contains(Object value) {
2709        return containsValue(value);
2710    }
2711
2712    /**
2713     * Maps the specified key to the specified value in this table.
2714     * Neither the key nor the value can be null.
2715     *
2716     * <p>The value can be retrieved by calling the {@code get} method
2717     * with a key that is equal to the original key.
2718     *
2719     * @param key key with which the specified value is to be associated
2720     * @param value value to be associated with the specified key
2721     * @return the previous value associated with {@code key}, or
2722     *         {@code null} if there was no mapping for {@code key}
2723     * @throws NullPointerException if the specified key or value is null
2724     */
2725    public V put(K key, V value) {
2726        return internalPut(key, value, false);
2727    }
2728
2729    /**
2730     * {@inheritDoc}
2731     *
2732     * @return the previous value associated with the specified key,
2733     *         or {@code null} if there was no mapping for the key
2734     * @throws NullPointerException if the specified key or value is null
2735     */
2736    public V putIfAbsent(K key, V value) {
2737        return internalPut(key, value, true);
2738    }
2739
2740    /**
2741     * Copies all of the mappings from the specified map to this one.
2742     * These mappings replace any mappings that this map had for any of the
2743     * keys currently in the specified map.
2744     *
2745     * @param m mappings to be stored in this map
2746     */
2747    public void putAll(Map<? extends K, ? extends V> m) {
2748        internalPutAll(m);
2749    }
2750
2751    /**
2752     * If the specified key is not already associated with a value (or
2753     * is mapped to {@code null}), attempts to compute its value using
2754     * the given mapping function and enters it into this map unless
2755     * {@code null}. The entire method invocation is performed
2756     * atomically, so the function is applied at most once per key.
2757     * Some attempted update operations on this map by other threads
2758     * may be blocked while computation is in progress, so the
2759     * computation should be short and simple, and must not attempt to
2760     * update any other mappings of this Map.
2761     *
2762     * @param key key with which the specified value is to be associated
2763     * @param mappingFunction the function to compute a value
2764     * @return the current (existing or computed) value associated with
2765     *         the specified key, or null if the computed value is null
2766     * @throws NullPointerException if the specified key or mappingFunction
2767     *         is null
2768     * @throws IllegalStateException if the computation detectably
2769     *         attempts a recursive update to this map that would
2770     *         otherwise never complete
2771     * @throws RuntimeException or Error if the mappingFunction does so,
2772     *         in which case the mapping is left unestablished
2773     */
2774    public V computeIfAbsent
2775        (K key, Function<? super K, ? extends V> mappingFunction) {
2776        return internalComputeIfAbsent(key, mappingFunction);
2777    }
2778
2779    /**
2780     * If the value for the specified key is present and non-null,
2781     * attempts to compute a new mapping given the key and its current
2782     * mapped value.  The entire method invocation is performed
2783     * atomically.  Some attempted update operations on this map by
2784     * other threads may be blocked while computation is in progress,
2785     * so the computation should be short and simple, and must not
2786     * attempt to update any other mappings of this Map.
2787     *
2788     * @param key key with which a value may be associated
2789     * @param remappingFunction the function to compute a value
2790     * @return the new value associated with the specified key, or null if none
2791     * @throws NullPointerException if the specified key or remappingFunction
2792     *         is null
2793     * @throws IllegalStateException if the computation detectably
2794     *         attempts a recursive update to this map that would
2795     *         otherwise never complete
2796     * @throws RuntimeException or Error if the remappingFunction does so,
2797     *         in which case the mapping is unchanged
2798     */
2799    public V computeIfPresent
2800        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2801        return internalCompute(key, true, remappingFunction);
2802    }
2803
2804    /**
2805     * Attempts to compute a mapping for the specified key and its
2806     * current mapped value (or {@code null} if there is no current
2807     * mapping). The entire method invocation is performed atomically.
2808     * Some attempted update operations on this map by other threads
2809     * may be blocked while computation is in progress, so the
2810     * computation should be short and simple, and must not attempt to
2811     * update any other mappings of this Map.
2812     *
2813     * @param key key with which the specified value is to be associated
2814     * @param remappingFunction the function to compute a value
2815     * @return the new value associated with the specified key, or null if none
2816     * @throws NullPointerException if the specified key or remappingFunction
2817     *         is null
2818     * @throws IllegalStateException if the computation detectably
2819     *         attempts a recursive update to this map that would
2820     *         otherwise never complete
2821     * @throws RuntimeException or Error if the remappingFunction does so,
2822     *         in which case the mapping is unchanged
2823     */
2824    public V compute
2825        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2826        return internalCompute(key, false, remappingFunction);
2827    }
2828
2829    /**
2830     * If the specified key is not already associated with a
2831     * (non-null) value, associates it with the given value.
2832     * Otherwise, replaces the value with the results of the given
2833     * remapping function, or removes if {@code null}. The entire
2834     * method invocation is performed atomically.  Some attempted
2835     * update operations on this map by other threads may be blocked
2836     * while computation is in progress, so the computation should be
2837     * short and simple, and must not attempt to update any other
2838     * mappings of this Map.
2839     *
2840     * @param key key with which the specified value is to be associated
2841     * @param value the value to use if absent
2842     * @param remappingFunction the function to recompute a value if present
2843     * @return the new value associated with the specified key, or null if none
2844     * @throws NullPointerException if the specified key or the
2845     *         remappingFunction is null
2846     * @throws RuntimeException or Error if the remappingFunction does so,
2847     *         in which case the mapping is unchanged
2848     */
2849    public V merge
2850        (K key, V value,
2851         BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2852        return internalMerge(key, value, remappingFunction);
2853    }
2854
2855    /**
2856     * Removes the key (and its corresponding value) from this map.
2857     * This method does nothing if the key is not in the map.
2858     *
2859     * @param  key the key that needs to be removed
2860     * @return the previous value associated with {@code key}, or
2861     *         {@code null} if there was no mapping for {@code key}
2862     * @throws NullPointerException if the specified key is null
2863     */
2864    public V remove(Object key) {
2865        return internalReplace(key, null, null);
2866    }
2867
2868    /**
2869     * {@inheritDoc}
2870     *
2871     * @throws NullPointerException if the specified key is null
2872     */
2873    public boolean remove(Object key, Object value) {
2874        if (key == null)
2875            throw new NullPointerException();
2876        return value != null && internalReplace(key, null, value) != null;
2877    }
2878
2879    /**
2880     * {@inheritDoc}
2881     *
2882     * @throws NullPointerException if any of the arguments are null
2883     */
2884    public boolean replace(K key, V oldValue, V newValue) {
2885        if (key == null || oldValue == null || newValue == null)
2886            throw new NullPointerException();
2887        return internalReplace(key, newValue, oldValue) != null;
2888    }
2889
2890    /**
2891     * {@inheritDoc}
2892     *
2893     * @return the previous value associated with the specified key,
2894     *         or {@code null} if there was no mapping for the key
2895     * @throws NullPointerException if the specified key or value is null
2896     */
2897    public V replace(K key, V value) {
2898        if (key == null || value == null)
2899            throw new NullPointerException();
2900        return internalReplace(key, value, null);
2901    }
2902
2903    /**
2904     * Removes all of the mappings from this map.
2905     */
2906    public void clear() {
2907        internalClear();
2908    }
2909
2910    /**
2911     * Returns a {@link Set} view of the keys contained in this map.
2912     * The set is backed by the map, so changes to the map are
2913     * reflected in the set, and vice-versa.
2914     *
2915     * @return the set view
2916     */
2917    public KeySetView<K,V> keySet() {
2918        KeySetView<K,V> ks = keySet;
2919        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2920    }
2921
2922    /**
2923     * Returns a {@link Set} view of the keys in this map, using the
2924     * given common mapped value for any additions (i.e., {@link
2925     * Collection#add} and {@link Collection#addAll(Collection)}).
2926     * This is of course only appropriate if it is acceptable to use
2927     * the same value for all additions from this view.
2928     *
2929     * @param mappedValue the mapped value to use for any additions
2930     * @return the set view
2931     * @throws NullPointerException if the mappedValue is null
2932     */
2933    public KeySetView<K,V> keySet(V mappedValue) {
2934        if (mappedValue == null)
2935            throw new NullPointerException();
2936        return new KeySetView<K,V>(this, mappedValue);
2937    }
2938
2939    /**
2940     * Returns a {@link Collection} view of the values contained in this map.
2941     * The collection is backed by the map, so changes to the map are
2942     * reflected in the collection, and vice-versa.
2943     *
2944     * @return the collection view
2945     */
2946    public ValuesView<K,V> values() {
2947        ValuesView<K,V> vs = values;
2948        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2949    }
2950
2951    /**
2952     * Returns a {@link Set} view of the mappings contained in this map.
2953     * The set is backed by the map, so changes to the map are
2954     * reflected in the set, and vice-versa.  The set supports element
2955     * removal, which removes the corresponding mapping from the map,
2956     * via the {@code Iterator.remove}, {@code Set.remove},
2957     * {@code removeAll}, {@code retainAll}, and {@code clear}
2958     * operations.  It does not support the {@code add} or
2959     * {@code addAll} operations.
2960     *
2961     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2962     * that will never throw {@link ConcurrentModificationException},
2963     * and guarantees to traverse elements as they existed upon
2964     * construction of the iterator, and may (but is not guaranteed to)
2965     * reflect any modifications subsequent to construction.
2966     *
2967     * @return the set view
2968     */
2969    public Set<Map.Entry<K,V>> entrySet() {
2970        EntrySetView<K,V> es = entrySet;
2971        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2972    }
3323  
3324 <    /**
3325 <     * Returns an enumeration of the keys in this table.
3326 <     *
3327 <     * @return an enumeration of the keys in this table
3328 <     * @see #keySet()
3329 <     */
3330 <    public Enumeration<K> keys() {
3331 <        return new KeyIterator<K,V>(this);
3332 <    }
3333 <
3334 <    /**
3335 <     * Returns an enumeration of the values in this table.
3336 <     *
3337 <     * @return an enumeration of the values in this table
3338 <     * @see #values()
3339 <     */
3340 <    public Enumeration<V> elements() {
3341 <        return new ValueIterator<K,V>(this);
3342 <    }
3324 >        /**
3325 >         * Advances if possible, returning next valid node, or null if none.
3326 >         */
3327 >        final Node<K,V> advance() {
3328 >            Node<K,V> e;
3329 >            if ((e = next) != null)
3330 >                e = e.next;
3331 >            for (;;) {
3332 >                Node<K,V>[] t; int i, n;  // must use locals in checks
3333 >                if (e != null)
3334 >                    return next = e;
3335 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3336 >                    (n = t.length) <= (i = index) || i < 0)
3337 >                    return next = null;
3338 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
3339 >                    if (e instanceof ForwardingNode) {
3340 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3341 >                        e = null;
3342 >                        pushState(t, i, n);
3343 >                        continue;
3344 >                    }
3345 >                    else if (e instanceof TreeBin)
3346 >                        e = ((TreeBin<K,V>)e).first;
3347 >                    else
3348 >                        e = null;
3349 >                }
3350 >                if (stack != null)
3351 >                    recoverState(n);
3352 >                else if ((index = i + baseSize) >= n)
3353 >                    index = ++baseIndex; // visit upper slots if present
3354 >            }
3355 >        }
3356  
3357 <    /**
3358 <     * Returns the hash code value for this {@link Map}, i.e.,
3359 <     * the sum of, for each key-value pair in the map,
3360 <     * {@code key.hashCode() ^ value.hashCode()}.
3361 <     *
3362 <     * @return the hash code value for this map
3363 <     */
3364 <    public int hashCode() {
3365 <        int h = 0;
3366 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3367 <        V v;
3368 <        while ((v = it.advanceValue()) != null) {
3369 <            h += it.nextKey.hashCode() ^ v.hashCode();
3357 >        /**
3358 >         * Saves traversal state upon encountering a forwarding node.
3359 >         */
3360 >        private void pushState(Node<K,V>[] t, int i, int n) {
3361 >            TableStack<K,V> s = spare;  // reuse if possible
3362 >            if (s != null)
3363 >                spare = s.next;
3364 >            else
3365 >                s = new TableStack<K,V>();
3366 >            s.tab = t;
3367 >            s.length = n;
3368 >            s.index = i;
3369 >            s.next = stack;
3370 >            stack = s;
3371          }
3008        return h;
3009    }
3372  
3373 <    /**
3374 <     * Returns a string representation of this map.  The string
3375 <     * representation consists of a list of key-value mappings (in no
3376 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3377 <     * mappings are separated by the characters {@code ", "} (comma
3378 <     * and space).  Each key-value mapping is rendered as the key
3379 <     * followed by an equals sign ("{@code =}") followed by the
3380 <     * associated value.
3381 <     *
3382 <     * @return a string representation of this map
3383 <     */
3384 <    public String toString() {
3385 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3386 <        StringBuilder sb = new StringBuilder();
3387 <        sb.append('{');
3388 <        V v;
3027 <        if ((v = it.advanceValue()) != null) {
3028 <            for (;;) {
3029 <                K k = it.nextKey;
3030 <                sb.append(k == this ? "(this Map)" : k);
3031 <                sb.append('=');
3032 <                sb.append(v == this ? "(this Map)" : v);
3033 <                if ((v = it.advanceValue()) == null)
3034 <                    break;
3035 <                sb.append(',').append(' ');
3373 >        /**
3374 >         * Possibly pops traversal state.
3375 >         *
3376 >         * @param n length of current table
3377 >         */
3378 >        private void recoverState(int n) {
3379 >            TableStack<K,V> s; int len;
3380 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
3381 >                n = len;
3382 >                index = s.index;
3383 >                tab = s.tab;
3384 >                s.tab = null;
3385 >                TableStack<K,V> next = s.next;
3386 >                s.next = spare; // save for reuse
3387 >                stack = next;
3388 >                spare = s;
3389              }
3390 +            if (s == null && (index += baseSize) >= n)
3391 +                index = ++baseIndex;
3392          }
3038        return sb.append('}').toString();
3393      }
3394  
3395      /**
3396 <     * Compares the specified object with this map for equality.
3397 <     * Returns {@code true} if the given object is a map with the same
3044 <     * mappings as this map.  This operation may return misleading
3045 <     * results if either map is concurrently modified during execution
3046 <     * of this method.
3047 <     *
3048 <     * @param o object to be compared for equality with this map
3049 <     * @return {@code true} if the specified object is equal to this map
3396 >     * Base of key, value, and entry Iterators. Adds fields to
3397 >     * Traverser to support iterator.remove.
3398       */
3399 <    public boolean equals(Object o) {
3400 <        if (o != this) {
3401 <            if (!(o instanceof Map))
3402 <                return false;
3403 <            Map<?,?> m = (Map<?,?>) o;
3404 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3405 <            V val;
3406 <            while ((val = it.advanceValue()) != null) {
3059 <                Object v = m.get(it.nextKey);
3060 <                if (v == null || (v != val && !v.equals(val)))
3061 <                    return false;
3062 <            }
3063 <            for (Map.Entry<?,?> e : m.entrySet()) {
3064 <                Object mk, mv, v;
3065 <                if ((mk = e.getKey()) == null ||
3066 <                    (mv = e.getValue()) == null ||
3067 <                    (v = internalGet(mk)) == null ||
3068 <                    (mv != v && !mv.equals(v)))
3069 <                    return false;
3070 <            }
3399 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3400 >        final ConcurrentHashMap<K,V> map;
3401 >        Node<K,V> lastReturned;
3402 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3403 >                    ConcurrentHashMap<K,V> map) {
3404 >            super(tab, size, index, limit);
3405 >            this.map = map;
3406 >            advance();
3407          }
3072        return true;
3073    }
3408  
3409 <    /* ----------------Iterators -------------- */
3409 >        public final boolean hasNext() { return next != null; }
3410 >        public final boolean hasMoreElements() { return next != null; }
3411  
3412 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3413 <        extends Traverser<K,V,Object>
3414 <        implements Spliterator<K>, Iterator<K>, Enumeration<K> {
3415 <        KeyIterator(ConcurrentHashMap<K,V> map) { super(map); }
3416 <        KeyIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3417 <            super(map, it);
3083 <        }
3084 <        public Spliterator<K> trySplit() {
3085 <            return (baseLimit - baseIndex <= 1) ? null :
3086 <                new KeyIterator<K,V>(map, this);
3412 >        public final void remove() {
3413 >            Node<K,V> p;
3414 >            if ((p = lastReturned) == null)
3415 >                throw new IllegalStateException();
3416 >            lastReturned = null;
3417 >            map.replaceNode(p.key, null, null);
3418          }
3419 +    }
3420 +
3421 +    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3422 +        implements Iterator<K>, Enumeration<K> {
3423 +        KeyIterator(Node<K,V>[] tab, int size, int index, int limit,
3424 +                    ConcurrentHashMap<K,V> map) {
3425 +            super(tab, size, index, limit, map);
3426 +        }
3427 +
3428          public final K next() {
3429 <            K k;
3430 <            if ((k = (nextVal == null) ? advanceKey() : nextKey) == null)
3429 >            Node<K,V> p;
3430 >            if ((p = next) == null)
3431                  throw new NoSuchElementException();
3432 <            nextVal = null;
3432 >            K k = p.key;
3433 >            lastReturned = p;
3434 >            advance();
3435              return k;
3436          }
3437  
3438          public final K nextElement() { return next(); }
3097
3098        public Iterator<K> iterator() { return this; }
3099
3100        public void forEachRemaining(Consumer<? super K> action) {
3101            forEachKey(action);
3102        }
3103
3104        public boolean tryAdvance(Consumer<? super K> block) {
3105            if (block == null) throw new NullPointerException();
3106            K k;
3107            if ((k = advanceKey()) == null)
3108                return false;
3109            block.accept(k);
3110            return true;
3111        }
3112
3113        public int characteristics() {
3114            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3115                Spliterator.NONNULL;
3116        }
3117
3439      }
3440  
3441 <    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3442 <        extends Traverser<K,V,Object>
3443 <        implements Spliterator<V>, Iterator<V>, Enumeration<V> {
3444 <        ValueIterator(ConcurrentHashMap<K,V> map) { super(map); }
3445 <        ValueIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3125 <            super(map, it);
3126 <        }
3127 <        public Spliterator<V> trySplit() {
3128 <            return (baseLimit - baseIndex <= 1) ? null :
3129 <                new ValueIterator<K,V>(map, this);
3441 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3442 >        implements Iterator<V>, Enumeration<V> {
3443 >        ValueIterator(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 V next() {
3449 <            V v;
3450 <            if ((v = nextVal) == null && (v = advanceValue()) == null)
3449 >            Node<K,V> p;
3450 >            if ((p = next) == null)
3451                  throw new NoSuchElementException();
3452 <            nextVal = null;
3452 >            V v = p.val;
3453 >            lastReturned = p;
3454 >            advance();
3455              return v;
3456          }
3457  
3458          public final V nextElement() { return next(); }
3141
3142        public Iterator<V> iterator() { return this; }
3143
3144        public void forEachRemaining(Consumer<? super V> action) {
3145            forEachValue(action);
3146        }
3147
3148        public boolean tryAdvance(Consumer<? super V> block) {
3149            V v;
3150            if (block == null) throw new NullPointerException();
3151            if ((v = advanceValue()) == null)
3152                return false;
3153            block.accept(v);
3154            return true;
3155        }
3156
3157        public int characteristics() {
3158            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3159        }
3459      }
3460  
3461 <    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3462 <        extends Traverser<K,V,Object>
3463 <        implements Spliterator<Map.Entry<K,V>>, Iterator<Map.Entry<K,V>> {
3464 <        EntryIterator(ConcurrentHashMap<K,V> map) { super(map); }
3465 <        EntryIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3167 <            super(map, it);
3168 <        }
3169 <        public Spliterator<Map.Entry<K,V>> trySplit() {
3170 <            return (baseLimit - baseIndex <= 1) ? null :
3171 <                new EntryIterator<K,V>(map, this);
3461 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3462 >        implements Iterator<Map.Entry<K,V>> {
3463 >        EntryIterator(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 Map.Entry<K,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 <            K k = nextKey;
3473 <            nextVal = null;
3472 >            K k = p.key;
3473 >            V v = p.val;
3474 >            lastReturned = p;
3475 >            advance();
3476              return new MapEntry<K,V>(k, v, map);
3477          }
3182
3183        public Iterator<Map.Entry<K,V>> iterator() { return this; }
3184
3185        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3186            if (action == null) throw new NullPointerException();
3187            V v;
3188            while ((v = advanceValue()) != null)
3189                action.accept(entryFor(nextKey, v));
3190        }
3191
3192        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> block) {
3193            V v;
3194            if (block == null) throw new NullPointerException();
3195            if ((v = advanceValue()) == null)
3196                return false;
3197            block.accept(entryFor(nextKey, v));
3198            return true;
3199        }
3200
3201        public int characteristics() {
3202            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3203                Spliterator.NONNULL;
3204        }
3478      }
3479  
3480      /**
3481 <     * Exported Entry for iterators
3481 >     * Exported Entry for EntryIterator.
3482       */
3483      static final class MapEntry<K,V> implements Map.Entry<K,V> {
3484          final K key; // non-null
# Line 3216 | Line 3489 | public class ConcurrentHashMap<K,V>
3489              this.val = val;
3490              this.map = map;
3491          }
3492 <        public final K getKey()       { return key; }
3493 <        public final V getValue()     { return val; }
3494 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3495 <        public final String toString(){ return key + "=" + val; }
3492 >        public K getKey()        { return key; }
3493 >        public V getValue()      { return val; }
3494 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3495 >        public String toString() {
3496 >            return Helpers.mapEntryToString(key, val);
3497 >        }
3498  
3499 <        public final boolean equals(Object o) {
3499 >        public boolean equals(Object o) {
3500              Object k, v; Map.Entry<?,?> e;
3501              return ((o instanceof Map.Entry) &&
3502                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3235 | Line 3510 | public class ConcurrentHashMap<K,V>
3510           * value to return is somewhat arbitrary here. Since we do not
3511           * necessarily track asynchronous changes, the most recent
3512           * "previous" value could be different from what we return (or
3513 <         * could even have been removed in which case the put will
3513 >         * could even have been removed, in which case the put will
3514           * re-establish). We do not and cannot guarantee more.
3515           */
3516 <        public final V setValue(V value) {
3516 >        public V setValue(V value) {
3517              if (value == null) throw new NullPointerException();
3518              V v = val;
3519              val = value;
# Line 3247 | Line 3522 | public class ConcurrentHashMap<K,V>
3522          }
3523      }
3524  
3525 <    /**
3526 <     * Returns exportable snapshot entry for the given key and value
3527 <     * when write-through can't or shouldn't be used.
3528 <     */
3529 <    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3530 <        return new AbstractMap.SimpleEntry<K,V>(k, v);
3531 <    }
3525 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3526 >        implements Spliterator<K> {
3527 >        long est;               // size estimate
3528 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3529 >                       long est) {
3530 >            super(tab, size, index, limit);
3531 >            this.est = est;
3532 >        }
3533  
3534 <    /* ---------------- Serialization Support -------------- */
3534 >        public KeySpliterator<K,V> trySplit() {
3535 >            int i, f, h;
3536 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3537 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3538 >                                        f, est >>>= 1);
3539 >        }
3540  
3541 <    /**
3542 <     * Stripped-down version of helper class used in previous version,
3543 <     * declared for the sake of serialization compatibility
3544 <     */
3545 <    static class Segment<K,V> implements Serializable {
3546 <        private static final long serialVersionUID = 2249069246763182397L;
3547 <        final float loadFactor;
3548 <        Segment(float lf) { this.loadFactor = lf; }
3541 >        public void forEachRemaining(Consumer<? super K> action) {
3542 >            if (action == null) throw new NullPointerException();
3543 >            for (Node<K,V> p; (p = advance()) != null;)
3544 >                action.accept(p.key);
3545 >        }
3546 >
3547 >        public boolean tryAdvance(Consumer<? super K> action) {
3548 >            if (action == null) throw new NullPointerException();
3549 >            Node<K,V> p;
3550 >            if ((p = advance()) == null)
3551 >                return false;
3552 >            action.accept(p.key);
3553 >            return true;
3554 >        }
3555 >
3556 >        public long estimateSize() { return est; }
3557 >
3558 >        public int characteristics() {
3559 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3560 >                Spliterator.NONNULL;
3561 >        }
3562      }
3563  
3564 <    /**
3565 <     * Saves the state of the {@code ConcurrentHashMap} instance to a
3566 <     * stream (i.e., serializes it).
3567 <     * @param s the stream
3568 <     * @serialData
3569 <     * the key (Object) and value (Object)
3570 <     * for each key-value mapping, followed by a null pair.
3277 <     * The key-value mappings are emitted in no particular order.
3278 <     */
3279 <    @SuppressWarnings("unchecked") private void writeObject
3280 <        (java.io.ObjectOutputStream s)
3281 <        throws java.io.IOException {
3282 <        if (segments == null) { // for serialization compatibility
3283 <            segments = (Segment<K,V>[])
3284 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3285 <            for (int i = 0; i < segments.length; ++i)
3286 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3564 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3565 >        implements Spliterator<V> {
3566 >        long est;               // size estimate
3567 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3568 >                         long est) {
3569 >            super(tab, size, index, limit);
3570 >            this.est = est;
3571          }
3572 <        s.defaultWriteObject();
3573 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3574 <        V v;
3575 <        while ((v = it.advanceValue()) != null) {
3576 <            s.writeObject(it.nextKey);
3577 <            s.writeObject(v);
3572 >
3573 >        public ValueSpliterator<K,V> trySplit() {
3574 >            int i, f, h;
3575 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3576 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3577 >                                          f, est >>>= 1);
3578 >        }
3579 >
3580 >        public void forEachRemaining(Consumer<? super V> action) {
3581 >            if (action == null) throw new NullPointerException();
3582 >            for (Node<K,V> p; (p = advance()) != null;)
3583 >                action.accept(p.val);
3584 >        }
3585 >
3586 >        public boolean tryAdvance(Consumer<? super V> action) {
3587 >            if (action == null) throw new NullPointerException();
3588 >            Node<K,V> p;
3589 >            if ((p = advance()) == null)
3590 >                return false;
3591 >            action.accept(p.val);
3592 >            return true;
3593 >        }
3594 >
3595 >        public long estimateSize() { return est; }
3596 >
3597 >        public int characteristics() {
3598 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3599          }
3295        s.writeObject(null);
3296        s.writeObject(null);
3297        segments = null; // throw away
3600      }
3601  
3602 <    /**
3603 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3604 <     * @param s the stream
3605 <     */
3606 <    @SuppressWarnings("unchecked") private void readObject
3607 <        (java.io.ObjectInputStream s)
3608 <        throws java.io.IOException, ClassNotFoundException {
3609 <        s.defaultReadObject();
3610 <        this.segments = null; // unneeded
3602 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3603 >        implements Spliterator<Map.Entry<K,V>> {
3604 >        final ConcurrentHashMap<K,V> map; // To export MapEntry
3605 >        long est;               // size estimate
3606 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3607 >                         long est, ConcurrentHashMap<K,V> map) {
3608 >            super(tab, size, index, limit);
3609 >            this.map = map;
3610 >            this.est = est;
3611 >        }
3612  
3613 <        // Create all nodes, then place in table once size is known
3614 <        long size = 0L;
3615 <        Node<V> p = null;
3616 <        for (;;) {
3617 <            K k = (K) s.readObject();
3315 <            V v = (V) s.readObject();
3316 <            if (k != null && v != null) {
3317 <                int h = spread(k.hashCode());
3318 <                p = new Node<V>(h, k, v, p);
3319 <                ++size;
3320 <            }
3321 <            else
3322 <                break;
3613 >        public EntrySpliterator<K,V> trySplit() {
3614 >            int i, f, h;
3615 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3616 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3617 >                                          f, est >>>= 1, map);
3618          }
3619 <        if (p != null) {
3620 <            boolean init = false;
3621 <            int n;
3622 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3623 <                n = MAXIMUM_CAPACITY;
3624 <            else {
3625 <                int sz = (int)size;
3626 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3627 <            }
3628 <            int sc = sizeCtl;
3629 <            boolean collide = false;
3630 <            if (n > sc &&
3631 <                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3632 <                try {
3633 <                    if (table == null) {
3634 <                        init = true;
3635 <                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3636 <                        Node<V>[] tab = (Node<V>[])rt;
3637 <                        int mask = n - 1;
3638 <                        while (p != null) {
3639 <                            int j = p.hash & mask;
3345 <                            Node<V> next = p.next;
3346 <                            Node<V> q = p.next = tabAt(tab, j);
3347 <                            setTabAt(tab, j, p);
3348 <                            if (!collide && q != null && q.hash == p.hash)
3349 <                                collide = true;
3350 <                            p = next;
3351 <                        }
3352 <                        table = tab;
3353 <                        addCount(size, -1);
3354 <                        sc = n - (n >>> 2);
3355 <                    }
3356 <                } finally {
3357 <                    sizeCtl = sc;
3358 <                }
3359 <                if (collide) { // rescan and convert to TreeBins
3360 <                    Node<V>[] tab = table;
3361 <                    for (int i = 0; i < tab.length; ++i) {
3362 <                        int c = 0;
3363 <                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3364 <                            if (++c > TREE_THRESHOLD &&
3365 <                                (e.key instanceof Comparable)) {
3366 <                                replaceWithTreeBin(tab, i, e.key);
3367 <                                break;
3368 <                            }
3369 <                        }
3370 <                    }
3371 <                }
3372 <            }
3373 <            if (!init) { // Can only happen if unsafely published.
3374 <                while (p != null) {
3375 <                    internalPut((K)p.key, p.val, false);
3376 <                    p = p.next;
3377 <                }
3378 <            }
3619 >
3620 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3621 >            if (action == null) throw new NullPointerException();
3622 >            for (Node<K,V> p; (p = advance()) != null; )
3623 >                action.accept(new MapEntry<K,V>(p.key, p.val, map));
3624 >        }
3625 >
3626 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3627 >            if (action == null) throw new NullPointerException();
3628 >            Node<K,V> p;
3629 >            if ((p = advance()) == null)
3630 >                return false;
3631 >            action.accept(new MapEntry<K,V>(p.key, p.val, map));
3632 >            return true;
3633 >        }
3634 >
3635 >        public long estimateSize() { return est; }
3636 >
3637 >        public int characteristics() {
3638 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3639 >                Spliterator.NONNULL;
3640          }
3641      }
3642  
3643 <    // -------------------------------------------------------
3643 >    // Parallel bulk operations
3644  
3645 <    // Sequential bulk operations
3645 >    /**
3646 >     * Computes initial batch value for bulk tasks. The returned value
3647 >     * is approximately exp2 of the number of times (minus one) to
3648 >     * split task by two before executing leaf action. This value is
3649 >     * faster to compute and more convenient to use as a guide to
3650 >     * splitting than is the depth, since it is used while dividing by
3651 >     * two anyway.
3652 >     */
3653 >    final int batchFor(long b) {
3654 >        long n;
3655 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3656 >            return 0;
3657 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3658 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3659 >    }
3660  
3661      /**
3662       * Performs the given action for each (key, value).
3663       *
3664 +     * @param parallelismThreshold the (estimated) number of elements
3665 +     * needed for this operation to be executed in parallel
3666       * @param action the action
3667 +     * @since 1.8
3668       */
3669 <    public void forEachSequentially
3670 <        (BiConsumer<? super K, ? super V> action) {
3669 >    public void forEach(long parallelismThreshold,
3670 >                        BiConsumer<? super K,? super V> action) {
3671          if (action == null) throw new NullPointerException();
3672 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3673 <        V v;
3674 <        while ((v = it.advanceValue()) != null)
3397 <            action.accept(it.nextKey, v);
3672 >        new ForEachMappingTask<K,V>
3673 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3674 >             action).invoke();
3675      }
3676  
3677      /**
3678       * Performs the given action for each non-null transformation
3679       * of each (key, value).
3680       *
3681 +     * @param parallelismThreshold the (estimated) number of elements
3682 +     * needed for this operation to be executed in parallel
3683       * @param transformer a function returning the transformation
3684       * for an element, or null if there is no transformation (in
3685       * which case the action is not applied)
3686       * @param action the action
3687 +     * @param <U> the return type of the transformer
3688 +     * @since 1.8
3689       */
3690 <    public <U> void forEachSequentially
3691 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3692 <         Consumer<? super U> action) {
3690 >    public <U> void forEach(long parallelismThreshold,
3691 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3692 >                            Consumer<? super U> action) {
3693          if (transformer == null || action == null)
3694              throw new NullPointerException();
3695 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3696 <        V v; U u;
3697 <        while ((v = it.advanceValue()) != null) {
3417 <            if ((u = transformer.apply(it.nextKey, v)) != null)
3418 <                action.accept(u);
3419 <        }
3695 >        new ForEachTransformedMappingTask<K,V,U>
3696 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3697 >             transformer, action).invoke();
3698      }
3699  
3700      /**
3701       * Returns a non-null result from applying the given search
3702 <     * function on each (key, value), or null if none.
3702 >     * function on each (key, value), or null if none.  Upon
3703 >     * success, further element processing is suppressed and the
3704 >     * results of any other parallel invocations of the search
3705 >     * function are ignored.
3706       *
3707 +     * @param parallelismThreshold the (estimated) number of elements
3708 +     * needed for this operation to be executed in parallel
3709       * @param searchFunction a function returning a non-null
3710       * result on success, else null
3711 +     * @param <U> the return type of the search function
3712       * @return a non-null result from applying the given search
3713       * function on each (key, value), or null if none
3714 +     * @since 1.8
3715       */
3716 <    public <U> U searchSequentially
3717 <        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3716 >    public <U> U search(long parallelismThreshold,
3717 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3718          if (searchFunction == null) throw new NullPointerException();
3719 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3720 <        V v; U u;
3721 <        while ((v = it.advanceValue()) != null) {
3437 <            if ((u = searchFunction.apply(it.nextKey, v)) != null)
3438 <                return u;
3439 <        }
3440 <        return null;
3719 >        return new SearchMappingsTask<K,V,U>
3720 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3721 >             searchFunction, new AtomicReference<U>()).invoke();
3722      }
3723  
3724      /**
# Line 3445 | Line 3726 | public class ConcurrentHashMap<K,V>
3726       * of all (key, value) pairs using the given reducer to
3727       * combine values, or null if none.
3728       *
3729 +     * @param parallelismThreshold the (estimated) number of elements
3730 +     * needed for this operation to be executed in parallel
3731       * @param transformer a function returning the transformation
3732       * for an element, or null if there is no transformation (in
3733       * which case it is not combined)
3734       * @param reducer a commutative associative combining function
3735 +     * @param <U> the return type of the transformer
3736       * @return the result of accumulating the given transformation
3737       * of all (key, value) pairs
3738 +     * @since 1.8
3739       */
3740 <    public <U> U reduceSequentially
3741 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3742 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
3740 >    public <U> U reduce(long parallelismThreshold,
3741 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3742 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3743          if (transformer == null || reducer == null)
3744              throw new NullPointerException();
3745 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3746 <        U r = null, u; V v;
3747 <        while ((v = it.advanceValue()) != null) {
3463 <            if ((u = transformer.apply(it.nextKey, v)) != null)
3464 <                r = (r == null) ? u : reducer.apply(r, u);
3465 <        }
3466 <        return r;
3745 >        return new MapReduceMappingsTask<K,V,U>
3746 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3747 >             null, transformer, reducer).invoke();
3748      }
3749  
3750      /**
# Line 3471 | Line 3752 | public class ConcurrentHashMap<K,V>
3752       * of all (key, value) pairs using the given reducer to
3753       * combine values, and the given basis as an identity value.
3754       *
3755 +     * @param parallelismThreshold the (estimated) number of elements
3756 +     * needed for this operation to be executed in parallel
3757       * @param transformer a function returning the transformation
3758       * for an element
3759       * @param basis the identity (initial default value) for the reduction
3760       * @param reducer a commutative associative combining function
3761       * @return the result of accumulating the given transformation
3762       * of all (key, value) pairs
3763 +     * @since 1.8
3764       */
3765 <    public double reduceToDoubleSequentially
3766 <        (ToDoubleBiFunction<? super K, ? super V> transformer,
3767 <         double basis,
3768 <         DoubleBinaryOperator reducer) {
3765 >    public double reduceToDouble(long parallelismThreshold,
3766 >                                 ToDoubleBiFunction<? super K, ? super V> transformer,
3767 >                                 double basis,
3768 >                                 DoubleBinaryOperator reducer) {
3769          if (transformer == null || reducer == null)
3770              throw new NullPointerException();
3771 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3772 <        double r = basis; V v;
3773 <        while ((v = it.advanceValue()) != null)
3490 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey, v));
3491 <        return r;
3771 >        return new MapReduceMappingsToDoubleTask<K,V>
3772 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3773 >             null, transformer, basis, reducer).invoke();
3774      }
3775  
3776      /**
# Line 3496 | Line 3778 | public class ConcurrentHashMap<K,V>
3778       * of all (key, value) pairs using the given reducer to
3779       * combine values, and the given basis as an identity value.
3780       *
3781 +     * @param parallelismThreshold the (estimated) number of elements
3782 +     * needed for this operation to be executed in parallel
3783       * @param transformer a function returning the transformation
3784       * for an element
3785       * @param basis the identity (initial default value) for the reduction
3786       * @param reducer a commutative associative combining function
3787       * @return the result of accumulating the given transformation
3788       * of all (key, value) pairs
3789 +     * @since 1.8
3790       */
3791 <    public long reduceToLongSequentially
3792 <        (ToLongBiFunction<? super K, ? super V> transformer,
3793 <         long basis,
3794 <         LongBinaryOperator reducer) {
3791 >    public long reduceToLong(long parallelismThreshold,
3792 >                             ToLongBiFunction<? super K, ? super V> transformer,
3793 >                             long basis,
3794 >                             LongBinaryOperator reducer) {
3795          if (transformer == null || reducer == null)
3796              throw new NullPointerException();
3797 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3798 <        long r = basis; V v;
3799 <        while ((v = it.advanceValue()) != null)
3515 <            r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey, v));
3516 <        return r;
3797 >        return new MapReduceMappingsToLongTask<K,V>
3798 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3799 >             null, transformer, basis, reducer).invoke();
3800      }
3801  
3802      /**
# Line 3521 | Line 3804 | public class ConcurrentHashMap<K,V>
3804       * of all (key, value) pairs using the given reducer to
3805       * combine values, and the given basis as an identity value.
3806       *
3807 +     * @param parallelismThreshold the (estimated) number of elements
3808 +     * needed for this operation to be executed in parallel
3809       * @param transformer a function returning the transformation
3810       * for an element
3811       * @param basis the identity (initial default value) for the reduction
3812       * @param reducer a commutative associative combining function
3813       * @return the result of accumulating the given transformation
3814       * of all (key, value) pairs
3815 +     * @since 1.8
3816       */
3817 <    public int reduceToIntSequentially
3818 <        (ToIntBiFunction<? super K, ? super V> transformer,
3819 <         int basis,
3820 <         IntBinaryOperator reducer) {
3817 >    public int reduceToInt(long parallelismThreshold,
3818 >                           ToIntBiFunction<? super K, ? super V> transformer,
3819 >                           int basis,
3820 >                           IntBinaryOperator reducer) {
3821          if (transformer == null || reducer == null)
3822              throw new NullPointerException();
3823 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3824 <        int r = basis; V v;
3825 <        while ((v = it.advanceValue()) != null)
3540 <            r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey, v));
3541 <        return r;
3823 >        return new MapReduceMappingsToIntTask<K,V>
3824 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3825 >             null, transformer, basis, reducer).invoke();
3826      }
3827  
3828      /**
3829       * Performs the given action for each key.
3830       *
3831 +     * @param parallelismThreshold the (estimated) number of elements
3832 +     * needed for this operation to be executed in parallel
3833       * @param action the action
3834 +     * @since 1.8
3835       */
3836 <    public void forEachKeySequentially
3837 <        (Consumer<? super K> action) {
3838 <        new Traverser<K,V,Object>(this).forEachKey(action);
3836 >    public void forEachKey(long parallelismThreshold,
3837 >                           Consumer<? super K> action) {
3838 >        if (action == null) throw new NullPointerException();
3839 >        new ForEachKeyTask<K,V>
3840 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3841 >             action).invoke();
3842      }
3843  
3844      /**
3845       * Performs the given action for each non-null transformation
3846       * of each key.
3847       *
3848 +     * @param parallelismThreshold the (estimated) number of elements
3849 +     * needed for this operation to be executed in parallel
3850       * @param transformer a function returning the transformation
3851       * for an element, or null if there is no transformation (in
3852       * which case the action is not applied)
3853       * @param action the action
3854 +     * @param <U> the return type of the transformer
3855 +     * @since 1.8
3856       */
3857 <    public <U> void forEachKeySequentially
3858 <        (Function<? super K, ? extends U> transformer,
3859 <         Consumer<? super U> action) {
3857 >    public <U> void forEachKey(long parallelismThreshold,
3858 >                               Function<? super K, ? extends U> transformer,
3859 >                               Consumer<? super U> action) {
3860          if (transformer == null || action == null)
3861              throw new NullPointerException();
3862 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3863 <        K k; U u;
3864 <        while ((k = it.advanceKey()) != null) {
3571 <            if ((u = transformer.apply(k)) != null)
3572 <                action.accept(u);
3573 <        }
3862 >        new ForEachTransformedKeyTask<K,V,U>
3863 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3864 >             transformer, action).invoke();
3865      }
3866  
3867      /**
3868       * Returns a non-null result from applying the given search
3869 <     * function on each key, or null if none.
3869 >     * function on each key, or null if none. Upon success,
3870 >     * further element processing is suppressed and the results of
3871 >     * any other parallel invocations of the search function are
3872 >     * ignored.
3873       *
3874 +     * @param parallelismThreshold the (estimated) number of elements
3875 +     * needed for this operation to be executed in parallel
3876       * @param searchFunction a function returning a non-null
3877       * result on success, else null
3878 +     * @param <U> the return type of the search function
3879       * @return a non-null result from applying the given search
3880       * function on each key, or null if none
3881 +     * @since 1.8
3882       */
3883 <    public <U> U searchKeysSequentially
3884 <        (Function<? super K, ? extends U> searchFunction) {
3885 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3886 <        K k; U u;
3887 <        while ((k = it.advanceKey()) != null) {
3888 <            if ((u = searchFunction.apply(k)) != null)
3591 <                return u;
3592 <        }
3593 <        return null;
3883 >    public <U> U searchKeys(long parallelismThreshold,
3884 >                            Function<? super K, ? extends U> searchFunction) {
3885 >        if (searchFunction == null) throw new NullPointerException();
3886 >        return new SearchKeysTask<K,V,U>
3887 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3888 >             searchFunction, new AtomicReference<U>()).invoke();
3889      }
3890  
3891      /**
3892       * Returns the result of accumulating all keys using the given
3893       * reducer to combine values, or null if none.
3894       *
3895 +     * @param parallelismThreshold the (estimated) number of elements
3896 +     * needed for this operation to be executed in parallel
3897       * @param reducer a commutative associative combining function
3898       * @return the result of accumulating all keys using the given
3899       * reducer to combine values, or null if none
3900 +     * @since 1.8
3901       */
3902 <    public K reduceKeysSequentially
3903 <        (BiFunction<? super K, ? super K, ? extends K> reducer) {
3902 >    public K reduceKeys(long parallelismThreshold,
3903 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3904          if (reducer == null) throw new NullPointerException();
3905 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3906 <        K u, r = null;
3907 <        while ((u = it.advanceKey()) != null) {
3610 <            r = (r == null) ? u : reducer.apply(r, u);
3611 <        }
3612 <        return r;
3905 >        return new ReduceKeysTask<K,V>
3906 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3907 >             null, reducer).invoke();
3908      }
3909  
3910      /**
# Line 3617 | Line 3912 | public class ConcurrentHashMap<K,V>
3912       * of all keys using the given reducer to combine values, or
3913       * null if none.
3914       *
3915 +     * @param parallelismThreshold the (estimated) number of elements
3916 +     * needed for this operation to be executed in parallel
3917       * @param transformer a function returning the transformation
3918       * for an element, or null if there is no transformation (in
3919       * which case it is not combined)
3920       * @param reducer a commutative associative combining function
3921 +     * @param <U> the return type of the transformer
3922       * @return the result of accumulating the given transformation
3923       * of all keys
3924 +     * @since 1.8
3925       */
3926 <    public <U> U reduceKeysSequentially
3927 <        (Function<? super K, ? extends U> transformer,
3926 >    public <U> U reduceKeys(long parallelismThreshold,
3927 >                            Function<? super K, ? extends U> transformer,
3928           BiFunction<? super U, ? super U, ? extends U> reducer) {
3929          if (transformer == null || reducer == null)
3930              throw new NullPointerException();
3931 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3932 <        K k; U r = null, u;
3933 <        while ((k = it.advanceKey()) != null) {
3635 <            if ((u = transformer.apply(k)) != null)
3636 <                r = (r == null) ? u : reducer.apply(r, u);
3637 <        }
3638 <        return r;
3931 >        return new MapReduceKeysTask<K,V,U>
3932 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3933 >             null, transformer, reducer).invoke();
3934      }
3935  
3936      /**
# Line 3643 | Line 3938 | public class ConcurrentHashMap<K,V>
3938       * of all keys using the given reducer to combine values, and
3939       * the given basis as an identity value.
3940       *
3941 +     * @param parallelismThreshold the (estimated) number of elements
3942 +     * needed for this operation to be executed in parallel
3943       * @param transformer a function returning the transformation
3944       * for an element
3945       * @param basis the identity (initial default value) for the reduction
3946       * @param reducer a commutative associative combining function
3947       * @return the result of accumulating the given transformation
3948       * of all keys
3949 +     * @since 1.8
3950       */
3951 <    public double reduceKeysToDoubleSequentially
3952 <        (ToDoubleFunction<? super K> transformer,
3953 <         double basis,
3954 <         DoubleBinaryOperator reducer) {
3951 >    public double reduceKeysToDouble(long parallelismThreshold,
3952 >                                     ToDoubleFunction<? super K> transformer,
3953 >                                     double basis,
3954 >                                     DoubleBinaryOperator reducer) {
3955          if (transformer == null || reducer == null)
3956              throw new NullPointerException();
3957 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3958 <        double r = basis;
3959 <        K k;
3662 <        while ((k = it.advanceKey()) != null)
3663 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(k));
3664 <        return r;
3957 >        return new MapReduceKeysToDoubleTask<K,V>
3958 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3959 >             null, transformer, basis, reducer).invoke();
3960      }
3961  
3962      /**
# Line 3669 | Line 3964 | public class ConcurrentHashMap<K,V>
3964       * of all keys using the given reducer to combine values, and
3965       * the given basis as an identity value.
3966       *
3967 +     * @param parallelismThreshold the (estimated) number of elements
3968 +     * needed for this operation to be executed in parallel
3969       * @param transformer a function returning the transformation
3970       * for an element
3971       * @param basis the identity (initial default value) for the reduction
3972       * @param reducer a commutative associative combining function
3973       * @return the result of accumulating the given transformation
3974       * of all keys
3975 +     * @since 1.8
3976       */
3977 <    public long reduceKeysToLongSequentially
3978 <        (ToLongFunction<? super K> transformer,
3979 <         long basis,
3980 <         LongBinaryOperator reducer) {
3977 >    public long reduceKeysToLong(long parallelismThreshold,
3978 >                                 ToLongFunction<? super K> transformer,
3979 >                                 long basis,
3980 >                                 LongBinaryOperator reducer) {
3981          if (transformer == null || reducer == null)
3982              throw new NullPointerException();
3983 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3984 <        long r = basis;
3985 <        K k;
3688 <        while ((k = it.advanceKey()) != null)
3689 <            r = reducer.applyAsLong(r, transformer.applyAsLong(k));
3690 <        return r;
3983 >        return new MapReduceKeysToLongTask<K,V>
3984 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3985 >             null, transformer, basis, reducer).invoke();
3986      }
3987  
3988      /**
# Line 3695 | Line 3990 | public class ConcurrentHashMap<K,V>
3990       * of all keys using the given reducer to combine values, and
3991       * the given basis as an identity value.
3992       *
3993 +     * @param parallelismThreshold the (estimated) number of elements
3994 +     * needed for this operation to be executed in parallel
3995       * @param transformer a function returning the transformation
3996       * for an element
3997       * @param basis the identity (initial default value) for the reduction
3998       * @param reducer a commutative associative combining function
3999       * @return the result of accumulating the given transformation
4000       * of all keys
4001 +     * @since 1.8
4002       */
4003 <    public int reduceKeysToIntSequentially
4004 <        (ToIntFunction<? super K> transformer,
4005 <         int basis,
4006 <         IntBinaryOperator reducer) {
4003 >    public int reduceKeysToInt(long parallelismThreshold,
4004 >                               ToIntFunction<? super K> transformer,
4005 >                               int basis,
4006 >                               IntBinaryOperator reducer) {
4007          if (transformer == null || reducer == null)
4008              throw new NullPointerException();
4009 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4010 <        int r = basis;
4011 <        K k;
3714 <        while ((k = it.advanceKey()) != null)
3715 <            r = reducer.applyAsInt(r, transformer.applyAsInt(k));
3716 <        return r;
4009 >        return new MapReduceKeysToIntTask<K,V>
4010 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4011 >             null, transformer, basis, reducer).invoke();
4012      }
4013  
4014      /**
4015       * Performs the given action for each value.
4016       *
4017 +     * @param parallelismThreshold the (estimated) number of elements
4018 +     * needed for this operation to be executed in parallel
4019       * @param action the action
4020 +     * @since 1.8
4021       */
4022 <    public void forEachValueSequentially(Consumer<? super V> action) {
4023 <        new Traverser<K,V,Object>(this).forEachValue(action);
4022 >    public void forEachValue(long parallelismThreshold,
4023 >                             Consumer<? super V> action) {
4024 >        if (action == null)
4025 >            throw new NullPointerException();
4026 >        new ForEachValueTask<K,V>
4027 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4028 >             action).invoke();
4029      }
4030  
4031      /**
4032       * Performs the given action for each non-null transformation
4033       * of each value.
4034       *
4035 +     * @param parallelismThreshold the (estimated) number of elements
4036 +     * needed for this operation to be executed in parallel
4037       * @param transformer a function returning the transformation
4038       * for an element, or null if there is no transformation (in
4039       * which case the action is not applied)
4040       * @param action the action
4041 +     * @param <U> the return type of the transformer
4042 +     * @since 1.8
4043       */
4044 <    public <U> void forEachValueSequentially
4045 <        (Function<? super V, ? extends U> transformer,
4046 <         Consumer<? super U> action) {
4044 >    public <U> void forEachValue(long parallelismThreshold,
4045 >                                 Function<? super V, ? extends U> transformer,
4046 >                                 Consumer<? super U> action) {
4047          if (transformer == null || action == null)
4048              throw new NullPointerException();
4049 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4050 <        V v; U u;
4051 <        while ((v = it.advanceValue()) != null) {
3745 <            if ((u = transformer.apply(v)) != null)
3746 <                action.accept(u);
3747 <        }
4049 >        new ForEachTransformedValueTask<K,V,U>
4050 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4051 >             transformer, action).invoke();
4052      }
4053  
4054      /**
4055       * Returns a non-null result from applying the given search
4056 <     * function on each value, or null if none.
4056 >     * function on each value, or null if none.  Upon success,
4057 >     * further element processing is suppressed and the results of
4058 >     * any other parallel invocations of the search function are
4059 >     * ignored.
4060       *
4061 +     * @param parallelismThreshold the (estimated) number of elements
4062 +     * needed for this operation to be executed in parallel
4063       * @param searchFunction a function returning a non-null
4064       * result on success, else null
4065 +     * @param <U> the return type of the search function
4066       * @return a non-null result from applying the given search
4067       * function on each value, or null if none
4068 +     * @since 1.8
4069       */
4070 <    public <U> U searchValuesSequentially
4071 <        (Function<? super V, ? extends U> searchFunction) {
4070 >    public <U> U searchValues(long parallelismThreshold,
4071 >                              Function<? super V, ? extends U> searchFunction) {
4072          if (searchFunction == null) throw new NullPointerException();
4073 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4074 <        V v; U u;
4075 <        while ((v = it.advanceValue()) != null) {
3765 <            if ((u = searchFunction.apply(v)) != null)
3766 <                return u;
3767 <        }
3768 <        return null;
4073 >        return new SearchValuesTask<K,V,U>
4074 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4075 >             searchFunction, new AtomicReference<U>()).invoke();
4076      }
4077  
4078      /**
4079       * Returns the result of accumulating all values using the
4080       * given reducer to combine values, or null if none.
4081       *
4082 +     * @param parallelismThreshold the (estimated) number of elements
4083 +     * needed for this operation to be executed in parallel
4084       * @param reducer a commutative associative combining function
4085       * @return the result of accumulating all values
4086 +     * @since 1.8
4087       */
4088 <    public V reduceValuesSequentially
4089 <        (BiFunction<? super V, ? super V, ? extends V> reducer) {
4088 >    public V reduceValues(long parallelismThreshold,
4089 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
4090          if (reducer == null) throw new NullPointerException();
4091 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4092 <        V r = null; V v;
4093 <        while ((v = it.advanceValue()) != null)
3784 <            r = (r == null) ? v : reducer.apply(r, v);
3785 <        return r;
4091 >        return new ReduceValuesTask<K,V>
4092 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4093 >             null, reducer).invoke();
4094      }
4095  
4096      /**
# Line 3790 | Line 4098 | public class ConcurrentHashMap<K,V>
4098       * of all values using the given reducer to combine values, or
4099       * null if none.
4100       *
4101 +     * @param parallelismThreshold the (estimated) number of elements
4102 +     * needed for this operation to be executed in parallel
4103       * @param transformer a function returning the transformation
4104       * for an element, or null if there is no transformation (in
4105       * which case it is not combined)
4106       * @param reducer a commutative associative combining function
4107 +     * @param <U> the return type of the transformer
4108       * @return the result of accumulating the given transformation
4109       * of all values
4110 +     * @since 1.8
4111       */
4112 <    public <U> U reduceValuesSequentially
4113 <        (Function<? super V, ? extends U> transformer,
4114 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4112 >    public <U> U reduceValues(long parallelismThreshold,
4113 >                              Function<? super V, ? extends U> transformer,
4114 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
4115          if (transformer == null || reducer == null)
4116              throw new NullPointerException();
4117 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4118 <        U r = null, u; V v;
4119 <        while ((v = it.advanceValue()) != null) {
3808 <            if ((u = transformer.apply(v)) != null)
3809 <                r = (r == null) ? u : reducer.apply(r, u);
3810 <        }
3811 <        return r;
4117 >        return new MapReduceValuesTask<K,V,U>
4118 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4119 >             null, transformer, reducer).invoke();
4120      }
4121  
4122      /**
# Line 3816 | Line 4124 | public class ConcurrentHashMap<K,V>
4124       * of all values using the given reducer to combine values,
4125       * and the given basis as an identity value.
4126       *
4127 +     * @param parallelismThreshold the (estimated) number of elements
4128 +     * needed for this operation to be executed in parallel
4129       * @param transformer a function returning the transformation
4130       * for an element
4131       * @param basis the identity (initial default value) for the reduction
4132       * @param reducer a commutative associative combining function
4133       * @return the result of accumulating the given transformation
4134       * of all values
4135 +     * @since 1.8
4136       */
4137 <    public double reduceValuesToDoubleSequentially
4138 <        (ToDoubleFunction<? super V> transformer,
4139 <         double basis,
4140 <         DoubleBinaryOperator reducer) {
4137 >    public double reduceValuesToDouble(long parallelismThreshold,
4138 >                                       ToDoubleFunction<? super V> transformer,
4139 >                                       double basis,
4140 >                                       DoubleBinaryOperator reducer) {
4141          if (transformer == null || reducer == null)
4142              throw new NullPointerException();
4143 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4144 <        double r = basis; V v;
4145 <        while ((v = it.advanceValue()) != null)
3835 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
3836 <        return r;
4143 >        return new MapReduceValuesToDoubleTask<K,V>
4144 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4145 >             null, transformer, basis, reducer).invoke();
4146      }
4147  
4148      /**
# Line 3841 | Line 4150 | public class ConcurrentHashMap<K,V>
4150       * of all values using the given reducer to combine values,
4151       * and the given basis as an identity value.
4152       *
4153 +     * @param parallelismThreshold the (estimated) number of elements
4154 +     * needed for this operation to be executed in parallel
4155       * @param transformer a function returning the transformation
4156       * for an element
4157       * @param basis the identity (initial default value) for the reduction
4158       * @param reducer a commutative associative combining function
4159       * @return the result of accumulating the given transformation
4160       * of all values
4161 +     * @since 1.8
4162       */
4163 <    public long reduceValuesToLongSequentially
4164 <        (ToLongFunction<? super V> transformer,
4165 <         long basis,
4166 <         LongBinaryOperator reducer) {
4163 >    public long reduceValuesToLong(long parallelismThreshold,
4164 >                                   ToLongFunction<? super V> transformer,
4165 >                                   long basis,
4166 >                                   LongBinaryOperator reducer) {
4167          if (transformer == null || reducer == null)
4168              throw new NullPointerException();
4169 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4170 <        long r = basis; V v;
4171 <        while ((v = it.advanceValue()) != null)
3860 <            r = reducer.applyAsLong(r, transformer.applyAsLong(v));
3861 <        return r;
4169 >        return new MapReduceValuesToLongTask<K,V>
4170 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4171 >             null, transformer, basis, reducer).invoke();
4172      }
4173  
4174      /**
# Line 3866 | Line 4176 | public class ConcurrentHashMap<K,V>
4176       * of all values using the given reducer to combine values,
4177       * and the given basis as an identity value.
4178       *
4179 +     * @param parallelismThreshold the (estimated) number of elements
4180 +     * needed for this operation to be executed in parallel
4181       * @param transformer a function returning the transformation
4182       * for an element
4183       * @param basis the identity (initial default value) for the reduction
4184       * @param reducer a commutative associative combining function
4185       * @return the result of accumulating the given transformation
4186       * of all values
4187 +     * @since 1.8
4188       */
4189 <    public int reduceValuesToIntSequentially
4190 <        (ToIntFunction<? super V> transformer,
4191 <         int basis,
4192 <         IntBinaryOperator reducer) {
4189 >    public int reduceValuesToInt(long parallelismThreshold,
4190 >                                 ToIntFunction<? super V> transformer,
4191 >                                 int basis,
4192 >                                 IntBinaryOperator reducer) {
4193          if (transformer == null || reducer == null)
4194              throw new NullPointerException();
4195 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4196 <        int r = basis; V v;
4197 <        while ((v = it.advanceValue()) != null)
3885 <            r = reducer.applyAsInt(r, transformer.applyAsInt(v));
3886 <        return r;
4195 >        return new MapReduceValuesToIntTask<K,V>
4196 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4197 >             null, transformer, basis, reducer).invoke();
4198      }
4199  
4200      /**
4201       * Performs the given action for each entry.
4202       *
4203 +     * @param parallelismThreshold the (estimated) number of elements
4204 +     * needed for this operation to be executed in parallel
4205       * @param action the action
4206 +     * @since 1.8
4207       */
4208 <    public void forEachEntrySequentially
4209 <        (Consumer<? super Map.Entry<K,V>> action) {
4208 >    public void forEachEntry(long parallelismThreshold,
4209 >                             Consumer<? super Map.Entry<K,V>> action) {
4210          if (action == null) throw new NullPointerException();
4211 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4212 <        V v;
3899 <        while ((v = it.advanceValue()) != null)
3900 <            action.accept(entryFor(it.nextKey, v));
4211 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4212 >                                  action).invoke();
4213      }
4214  
4215      /**
4216       * Performs the given action for each non-null transformation
4217       * of each entry.
4218       *
4219 +     * @param parallelismThreshold the (estimated) number of elements
4220 +     * needed for this operation to be executed in parallel
4221       * @param transformer a function returning the transformation
4222       * for an element, or null if there is no transformation (in
4223       * which case the action is not applied)
4224       * @param action the action
4225 +     * @param <U> the return type of the transformer
4226 +     * @since 1.8
4227       */
4228 <    public <U> void forEachEntrySequentially
4229 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4230 <         Consumer<? super U> action) {
4228 >    public <U> void forEachEntry(long parallelismThreshold,
4229 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
4230 >                                 Consumer<? super U> action) {
4231          if (transformer == null || action == null)
4232              throw new NullPointerException();
4233 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4234 <        V v; U u;
4235 <        while ((v = it.advanceValue()) != null) {
3920 <            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3921 <                action.accept(u);
3922 <        }
4233 >        new ForEachTransformedEntryTask<K,V,U>
4234 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4235 >             transformer, action).invoke();
4236      }
4237  
4238      /**
4239       * Returns a non-null result from applying the given search
4240 <     * function on each entry, or null if none.
4240 >     * function on each entry, or null if none.  Upon success,
4241 >     * further element processing is suppressed and the results of
4242 >     * any other parallel invocations of the search function are
4243 >     * ignored.
4244       *
4245 +     * @param parallelismThreshold the (estimated) number of elements
4246 +     * needed for this operation to be executed in parallel
4247       * @param searchFunction a function returning a non-null
4248       * result on success, else null
4249 +     * @param <U> the return type of the search function
4250       * @return a non-null result from applying the given search
4251       * function on each entry, or null if none
4252 +     * @since 1.8
4253       */
4254 <    public <U> U searchEntriesSequentially
4255 <        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4254 >    public <U> U searchEntries(long parallelismThreshold,
4255 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4256          if (searchFunction == null) throw new NullPointerException();
4257 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4258 <        V v; U u;
4259 <        while ((v = it.advanceValue()) != null) {
3940 <            if ((u = searchFunction.apply(entryFor(it.nextKey, v))) != null)
3941 <                return u;
3942 <        }
3943 <        return null;
4257 >        return new SearchEntriesTask<K,V,U>
4258 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4259 >             searchFunction, new AtomicReference<U>()).invoke();
4260      }
4261  
4262      /**
4263       * Returns the result of accumulating all entries using the
4264       * given reducer to combine values, or null if none.
4265       *
4266 +     * @param parallelismThreshold the (estimated) number of elements
4267 +     * needed for this operation to be executed in parallel
4268       * @param reducer a commutative associative combining function
4269       * @return the result of accumulating all entries
4270 +     * @since 1.8
4271       */
4272 <    public Map.Entry<K,V> reduceEntriesSequentially
4273 <        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4272 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4273 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4274          if (reducer == null) throw new NullPointerException();
4275 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4276 <        Map.Entry<K,V> r = null; V v;
4277 <        while ((v = it.advanceValue()) != null) {
3959 <            Map.Entry<K,V> u = entryFor(it.nextKey, v);
3960 <            r = (r == null) ? u : reducer.apply(r, u);
3961 <        }
3962 <        return r;
4275 >        return new ReduceEntriesTask<K,V>
4276 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4277 >             null, reducer).invoke();
4278      }
4279  
4280      /**
# Line 3967 | Line 4282 | public class ConcurrentHashMap<K,V>
4282       * of all entries using the given reducer to combine values,
4283       * or null if none.
4284       *
4285 +     * @param parallelismThreshold the (estimated) number of elements
4286 +     * needed for this operation to be executed in parallel
4287       * @param transformer a function returning the transformation
4288       * for an element, or null if there is no transformation (in
4289       * which case it is not combined)
4290       * @param reducer a commutative associative combining function
4291 +     * @param <U> the return type of the transformer
4292       * @return the result of accumulating the given transformation
4293       * of all entries
4294 +     * @since 1.8
4295       */
4296 <    public <U> U reduceEntriesSequentially
4297 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4298 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4296 >    public <U> U reduceEntries(long parallelismThreshold,
4297 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
4298 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
4299          if (transformer == null || reducer == null)
4300              throw new NullPointerException();
4301 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4302 <        U r = null, u; V v;
4303 <        while ((v = it.advanceValue()) != null) {
3985 <            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3986 <                r = (r == null) ? u : reducer.apply(r, u);
3987 <        }
3988 <        return r;
4301 >        return new MapReduceEntriesTask<K,V,U>
4302 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4303 >             null, transformer, reducer).invoke();
4304      }
4305  
4306      /**
# Line 3993 | Line 4308 | public class ConcurrentHashMap<K,V>
4308       * of all entries using the given reducer to combine values,
4309       * and the given basis as an identity value.
4310       *
4311 +     * @param parallelismThreshold the (estimated) number of elements
4312 +     * needed for this operation to be executed in parallel
4313       * @param transformer a function returning the transformation
4314       * for an element
4315       * @param basis the identity (initial default value) for the reduction
4316       * @param reducer a commutative associative combining function
4317       * @return the result of accumulating the given transformation
4318       * of all entries
4319 +     * @since 1.8
4320       */
4321 <    public double reduceEntriesToDoubleSequentially
4322 <        (ToDoubleFunction<Map.Entry<K,V>> transformer,
4323 <         double basis,
4324 <         DoubleBinaryOperator reducer) {
4321 >    public double reduceEntriesToDouble(long parallelismThreshold,
4322 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
4323 >                                        double basis,
4324 >                                        DoubleBinaryOperator reducer) {
4325          if (transformer == null || reducer == null)
4326              throw new NullPointerException();
4327 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4328 <        double r = basis; V v;
4329 <        while ((v = it.advanceValue()) != null)
4012 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(it.nextKey, v)));
4013 <        return r;
4327 >        return new MapReduceEntriesToDoubleTask<K,V>
4328 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4329 >             null, transformer, basis, reducer).invoke();
4330      }
4331  
4332      /**
# Line 4018 | Line 4334 | public class ConcurrentHashMap<K,V>
4334       * of all entries using the given reducer to combine values,
4335       * and the given basis as an identity value.
4336       *
4337 +     * @param parallelismThreshold the (estimated) number of elements
4338 +     * needed for this operation to be executed in parallel
4339       * @param transformer a function returning the transformation
4340       * for an element
4341       * @param basis the identity (initial default value) for the reduction
4342       * @param reducer a commutative associative combining function
4343       * @return the result of accumulating the given transformation
4344       * of all entries
4345 +     * @since 1.8
4346       */
4347 <    public long reduceEntriesToLongSequentially
4348 <        (ToLongFunction<Map.Entry<K,V>> transformer,
4349 <         long basis,
4350 <         LongBinaryOperator reducer) {
4347 >    public long reduceEntriesToLong(long parallelismThreshold,
4348 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
4349 >                                    long basis,
4350 >                                    LongBinaryOperator reducer) {
4351          if (transformer == null || reducer == null)
4352              throw new NullPointerException();
4353 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4354 <        long r = basis; V v;
4355 <        while ((v = it.advanceValue()) != null)
4037 <            r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(it.nextKey, v)));
4038 <        return r;
4353 >        return new MapReduceEntriesToLongTask<K,V>
4354 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4355 >             null, transformer, basis, reducer).invoke();
4356      }
4357  
4358      /**
# Line 4043 | Line 4360 | public class ConcurrentHashMap<K,V>
4360       * of all entries using the given reducer to combine values,
4361       * and the given basis as an identity value.
4362       *
4363 +     * @param parallelismThreshold the (estimated) number of elements
4364 +     * needed for this operation to be executed in parallel
4365       * @param transformer a function returning the transformation
4366       * for an element
4367       * @param basis the identity (initial default value) for the reduction
4368       * @param reducer a commutative associative combining function
4369       * @return the result of accumulating the given transformation
4370       * of all entries
4371 +     * @since 1.8
4372       */
4373 <    public int reduceEntriesToIntSequentially
4374 <        (ToIntFunction<Map.Entry<K,V>> transformer,
4375 <         int basis,
4376 <         IntBinaryOperator reducer) {
4373 >    public int reduceEntriesToInt(long parallelismThreshold,
4374 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
4375 >                                  int basis,
4376 >                                  IntBinaryOperator reducer) {
4377          if (transformer == null || reducer == null)
4378              throw new NullPointerException();
4379 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4380 <        int r = basis; V v;
4381 <        while ((v = it.advanceValue()) != null)
4062 <            r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(it.nextKey, v)));
4063 <        return r;
4064 <    }
4065 <
4066 <    // Parallel bulk operations
4067 <
4068 <    /**
4069 <     * Performs the given action for each (key, value).
4070 <     *
4071 <     * @param action the action
4072 <     */
4073 <    public void forEachInParallel(BiConsumer<? super K,? super V> action) {
4074 <        ForkJoinTasks.forEach
4075 <            (this, action).invoke();
4076 <    }
4077 <
4078 <    /**
4079 <     * Performs the given action for each non-null transformation
4080 <     * of each (key, value).
4081 <     *
4082 <     * @param transformer a function returning the transformation
4083 <     * for an element, or null if there is no transformation (in
4084 <     * which case the action is not applied)
4085 <     * @param action the action
4086 <     */
4087 <    public <U> void forEachInParallel
4088 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
4089 <                            Consumer<? super U> action) {
4090 <        ForkJoinTasks.forEach
4091 <            (this, transformer, action).invoke();
4092 <    }
4093 <
4094 <    /**
4095 <     * Returns a non-null result from applying the given search
4096 <     * function on each (key, value), or null if none.  Upon
4097 <     * success, further element processing is suppressed and the
4098 <     * results of any other parallel invocations of the search
4099 <     * function are ignored.
4100 <     *
4101 <     * @param searchFunction a function returning a non-null
4102 <     * result on success, else null
4103 <     * @return a non-null result from applying the given search
4104 <     * function on each (key, value), or null if none
4105 <     */
4106 <    public <U> U searchInParallel
4107 <        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
4108 <        return ForkJoinTasks.search
4109 <            (this, searchFunction).invoke();
4110 <    }
4111 <
4112 <    /**
4113 <     * Returns the result of accumulating the given transformation
4114 <     * of all (key, value) pairs using the given reducer to
4115 <     * combine values, or null if none.
4116 <     *
4117 <     * @param transformer a function returning the transformation
4118 <     * for an element, or null if there is no transformation (in
4119 <     * which case it is not combined)
4120 <     * @param reducer a commutative associative combining function
4121 <     * @return the result of accumulating the given transformation
4122 <     * of all (key, value) pairs
4123 <     */
4124 <    public <U> U reduceInParallel
4125 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
4126 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4127 <        return ForkJoinTasks.reduce
4128 <            (this, transformer, reducer).invoke();
4129 <    }
4130 <
4131 <    /**
4132 <     * Returns the result of accumulating the given transformation
4133 <     * of all (key, value) pairs using the given reducer to
4134 <     * combine values, and the given basis as an identity value.
4135 <     *
4136 <     * @param transformer a function returning the transformation
4137 <     * for an element
4138 <     * @param basis the identity (initial default value) for the reduction
4139 <     * @param reducer a commutative associative combining function
4140 <     * @return the result of accumulating the given transformation
4141 <     * of all (key, value) pairs
4142 <     */
4143 <    public double reduceToDoubleInParallel
4144 <        (ToDoubleBiFunction<? super K, ? super V> transformer,
4145 <         double basis,
4146 <         DoubleBinaryOperator reducer) {
4147 <        return ForkJoinTasks.reduceToDouble
4148 <            (this, transformer, basis, reducer).invoke();
4149 <    }
4150 <
4151 <    /**
4152 <     * Returns the result of accumulating the given transformation
4153 <     * of all (key, value) pairs using the given reducer to
4154 <     * combine values, and the given basis as an identity value.
4155 <     *
4156 <     * @param transformer a function returning the transformation
4157 <     * for an element
4158 <     * @param basis the identity (initial default value) for the reduction
4159 <     * @param reducer a commutative associative combining function
4160 <     * @return the result of accumulating the given transformation
4161 <     * of all (key, value) pairs
4162 <     */
4163 <    public long reduceToLongInParallel
4164 <        (ToLongBiFunction<? super K, ? super V> transformer,
4165 <         long basis,
4166 <         LongBinaryOperator reducer) {
4167 <        return ForkJoinTasks.reduceToLong
4168 <            (this, transformer, basis, reducer).invoke();
4169 <    }
4170 <
4171 <    /**
4172 <     * Returns the result of accumulating the given transformation
4173 <     * of all (key, value) pairs using the given reducer to
4174 <     * combine values, and the given basis as an identity value.
4175 <     *
4176 <     * @param transformer a function returning the transformation
4177 <     * for an element
4178 <     * @param basis the identity (initial default value) for the reduction
4179 <     * @param reducer a commutative associative combining function
4180 <     * @return the result of accumulating the given transformation
4181 <     * of all (key, value) pairs
4182 <     */
4183 <    public int reduceToIntInParallel
4184 <        (ToIntBiFunction<? super K, ? super V> transformer,
4185 <         int basis,
4186 <         IntBinaryOperator reducer) {
4187 <        return ForkJoinTasks.reduceToInt
4188 <            (this, transformer, basis, reducer).invoke();
4189 <    }
4190 <
4191 <    /**
4192 <     * Performs the given action for each key.
4193 <     *
4194 <     * @param action the action
4195 <     */
4196 <    public void forEachKeyInParallel(Consumer<? super K> action) {
4197 <        ForkJoinTasks.forEachKey
4198 <            (this, action).invoke();
4199 <    }
4200 <
4201 <    /**
4202 <     * Performs the given action for each non-null transformation
4203 <     * of each key.
4204 <     *
4205 <     * @param transformer a function returning the transformation
4206 <     * for an element, or null if there is no transformation (in
4207 <     * which case the action is not applied)
4208 <     * @param action the action
4209 <     */
4210 <    public <U> void forEachKeyInParallel
4211 <        (Function<? super K, ? extends U> transformer,
4212 <         Consumer<? super U> action) {
4213 <        ForkJoinTasks.forEachKey
4214 <            (this, transformer, action).invoke();
4215 <    }
4216 <
4217 <    /**
4218 <     * Returns a non-null result from applying the given search
4219 <     * function on each key, or null if none. Upon success,
4220 <     * further element processing is suppressed and the results of
4221 <     * any other parallel invocations of the search function are
4222 <     * ignored.
4223 <     *
4224 <     * @param searchFunction a function returning a non-null
4225 <     * result on success, else null
4226 <     * @return a non-null result from applying the given search
4227 <     * function on each key, or null if none
4228 <     */
4229 <    public <U> U searchKeysInParallel
4230 <        (Function<? super K, ? extends U> searchFunction) {
4231 <        return ForkJoinTasks.searchKeys
4232 <            (this, searchFunction).invoke();
4233 <    }
4234 <
4235 <    /**
4236 <     * Returns the result of accumulating all keys using the given
4237 <     * reducer to combine values, or null if none.
4238 <     *
4239 <     * @param reducer a commutative associative combining function
4240 <     * @return the result of accumulating all keys using the given
4241 <     * reducer to combine values, or null if none
4242 <     */
4243 <    public K reduceKeysInParallel
4244 <        (BiFunction<? super K, ? super K, ? extends K> reducer) {
4245 <        return ForkJoinTasks.reduceKeys
4246 <            (this, reducer).invoke();
4247 <    }
4248 <
4249 <    /**
4250 <     * Returns the result of accumulating the given transformation
4251 <     * of all keys using the given reducer to combine values, or
4252 <     * null if none.
4253 <     *
4254 <     * @param transformer a function returning the transformation
4255 <     * for an element, or null if there is no transformation (in
4256 <     * which case it is not combined)
4257 <     * @param reducer a commutative associative combining function
4258 <     * @return the result of accumulating the given transformation
4259 <     * of all keys
4260 <     */
4261 <    public <U> U reduceKeysInParallel
4262 <        (Function<? super K, ? extends U> transformer,
4263 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4264 <        return ForkJoinTasks.reduceKeys
4265 <            (this, transformer, reducer).invoke();
4266 <    }
4267 <
4268 <    /**
4269 <     * Returns the result of accumulating the given transformation
4270 <     * of all keys using the given reducer to combine values, and
4271 <     * the given basis as an identity value.
4272 <     *
4273 <     * @param transformer a function returning the transformation
4274 <     * for an element
4275 <     * @param basis the identity (initial default value) for the reduction
4276 <     * @param reducer a commutative associative combining function
4277 <     * @return the result of accumulating the given transformation
4278 <     * of all keys
4279 <     */
4280 <    public double reduceKeysToDoubleInParallel
4281 <        (ToDoubleFunction<? super K> transformer,
4282 <         double basis,
4283 <         DoubleBinaryOperator reducer) {
4284 <        return ForkJoinTasks.reduceKeysToDouble
4285 <            (this, transformer, basis, reducer).invoke();
4286 <    }
4287 <
4288 <    /**
4289 <     * Returns the result of accumulating the given transformation
4290 <     * of all keys using the given reducer to combine values, and
4291 <     * the given basis as an identity value.
4292 <     *
4293 <     * @param transformer a function returning the transformation
4294 <     * for an element
4295 <     * @param basis the identity (initial default value) for the reduction
4296 <     * @param reducer a commutative associative combining function
4297 <     * @return the result of accumulating the given transformation
4298 <     * of all keys
4299 <     */
4300 <    public long reduceKeysToLongInParallel
4301 <        (ToLongFunction<? super K> transformer,
4302 <         long basis,
4303 <         LongBinaryOperator reducer) {
4304 <        return ForkJoinTasks.reduceKeysToLong
4305 <            (this, transformer, basis, reducer).invoke();
4306 <    }
4307 <
4308 <    /**
4309 <     * Returns the result of accumulating the given transformation
4310 <     * of all keys using the given reducer to combine values, and
4311 <     * the given basis as an identity value.
4312 <     *
4313 <     * @param transformer a function returning the transformation
4314 <     * for an element
4315 <     * @param basis the identity (initial default value) for the reduction
4316 <     * @param reducer a commutative associative combining function
4317 <     * @return the result of accumulating the given transformation
4318 <     * of all keys
4319 <     */
4320 <    public int reduceKeysToIntInParallel
4321 <        (ToIntFunction<? super K> transformer,
4322 <         int basis,
4323 <         IntBinaryOperator reducer) {
4324 <        return ForkJoinTasks.reduceKeysToInt
4325 <            (this, transformer, basis, reducer).invoke();
4326 <    }
4327 <
4328 <    /**
4329 <     * Performs the given action for each value.
4330 <     *
4331 <     * @param action the action
4332 <     */
4333 <    public void forEachValueInParallel(Consumer<? super V> action) {
4334 <        ForkJoinTasks.forEachValue
4335 <            (this, action).invoke();
4336 <    }
4337 <
4338 <    /**
4339 <     * Performs the given action for each non-null transformation
4340 <     * of each value.
4341 <     *
4342 <     * @param transformer a function returning the transformation
4343 <     * for an element, or null if there is no transformation (in
4344 <     * which case the action is not applied)
4345 <     * @param action the action
4346 <     */
4347 <    public <U> void forEachValueInParallel
4348 <        (Function<? super V, ? extends U> transformer,
4349 <         Consumer<? super U> action) {
4350 <        ForkJoinTasks.forEachValue
4351 <            (this, transformer, action).invoke();
4352 <    }
4353 <
4354 <    /**
4355 <     * Returns a non-null result from applying the given search
4356 <     * function on each value, or null if none.  Upon success,
4357 <     * further element processing is suppressed and the results of
4358 <     * any other parallel invocations of the search function are
4359 <     * ignored.
4360 <     *
4361 <     * @param searchFunction a function returning a non-null
4362 <     * result on success, else null
4363 <     * @return a non-null result from applying the given search
4364 <     * function on each value, or null if none
4365 <     */
4366 <    public <U> U searchValuesInParallel
4367 <        (Function<? super V, ? extends U> searchFunction) {
4368 <        return ForkJoinTasks.searchValues
4369 <            (this, searchFunction).invoke();
4370 <    }
4371 <
4372 <    /**
4373 <     * Returns the result of accumulating all values using the
4374 <     * given reducer to combine values, or null if none.
4375 <     *
4376 <     * @param reducer a commutative associative combining function
4377 <     * @return the result of accumulating all values
4378 <     */
4379 <    public V reduceValuesInParallel
4380 <        (BiFunction<? super V, ? super V, ? extends V> reducer) {
4381 <        return ForkJoinTasks.reduceValues
4382 <            (this, reducer).invoke();
4383 <    }
4384 <
4385 <    /**
4386 <     * Returns the result of accumulating the given transformation
4387 <     * of all values using the given reducer to combine values, or
4388 <     * null if none.
4389 <     *
4390 <     * @param transformer a function returning the transformation
4391 <     * for an element, or null if there is no transformation (in
4392 <     * which case it is not combined)
4393 <     * @param reducer a commutative associative combining function
4394 <     * @return the result of accumulating the given transformation
4395 <     * of all values
4396 <     */
4397 <    public <U> U reduceValuesInParallel
4398 <        (Function<? super V, ? extends U> transformer,
4399 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4400 <        return ForkJoinTasks.reduceValues
4401 <            (this, transformer, reducer).invoke();
4402 <    }
4403 <
4404 <    /**
4405 <     * Returns the result of accumulating the given transformation
4406 <     * of all values using the given reducer to combine values,
4407 <     * and the given basis as an identity value.
4408 <     *
4409 <     * @param transformer a function returning the transformation
4410 <     * for an element
4411 <     * @param basis the identity (initial default value) for the reduction
4412 <     * @param reducer a commutative associative combining function
4413 <     * @return the result of accumulating the given transformation
4414 <     * of all values
4415 <     */
4416 <    public double reduceValuesToDoubleInParallel
4417 <        (ToDoubleFunction<? super V> transformer,
4418 <         double basis,
4419 <         DoubleBinaryOperator reducer) {
4420 <        return ForkJoinTasks.reduceValuesToDouble
4421 <            (this, transformer, basis, reducer).invoke();
4422 <    }
4423 <
4424 <    /**
4425 <     * Returns the result of accumulating the given transformation
4426 <     * of all values using the given reducer to combine values,
4427 <     * and the given basis as an identity value.
4428 <     *
4429 <     * @param transformer a function returning the transformation
4430 <     * for an element
4431 <     * @param basis the identity (initial default value) for the reduction
4432 <     * @param reducer a commutative associative combining function
4433 <     * @return the result of accumulating the given transformation
4434 <     * of all values
4435 <     */
4436 <    public long reduceValuesToLongInParallel
4437 <        (ToLongFunction<? super V> transformer,
4438 <         long basis,
4439 <         LongBinaryOperator reducer) {
4440 <        return ForkJoinTasks.reduceValuesToLong
4441 <            (this, transformer, basis, reducer).invoke();
4442 <    }
4443 <
4444 <    /**
4445 <     * Returns the result of accumulating the given transformation
4446 <     * of all values using the given reducer to combine values,
4447 <     * and the given basis as an identity value.
4448 <     *
4449 <     * @param transformer a function returning the transformation
4450 <     * for an element
4451 <     * @param basis the identity (initial default value) for the reduction
4452 <     * @param reducer a commutative associative combining function
4453 <     * @return the result of accumulating the given transformation
4454 <     * of all values
4455 <     */
4456 <    public int reduceValuesToIntInParallel
4457 <        (ToIntFunction<? super V> transformer,
4458 <         int basis,
4459 <         IntBinaryOperator reducer) {
4460 <        return ForkJoinTasks.reduceValuesToInt
4461 <            (this, transformer, basis, reducer).invoke();
4462 <    }
4463 <
4464 <    /**
4465 <     * Performs the given action for each entry.
4466 <     *
4467 <     * @param action the action
4468 <     */
4469 <    public void forEachEntryInParallel(Consumer<? super Map.Entry<K,V>> action) {
4470 <        ForkJoinTasks.forEachEntry
4471 <            (this, action).invoke();
4472 <    }
4473 <
4474 <    /**
4475 <     * Performs the given action for each non-null transformation
4476 <     * of each entry.
4477 <     *
4478 <     * @param transformer a function returning the transformation
4479 <     * for an element, or null if there is no transformation (in
4480 <     * which case the action is not applied)
4481 <     * @param action the action
4482 <     */
4483 <    public <U> void forEachEntryInParallel
4484 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4485 <         Consumer<? super U> action) {
4486 <        ForkJoinTasks.forEachEntry
4487 <            (this, transformer, action).invoke();
4488 <    }
4489 <
4490 <    /**
4491 <     * Returns a non-null result from applying the given search
4492 <     * function on each entry, or null if none.  Upon success,
4493 <     * further element processing is suppressed and the results of
4494 <     * any other parallel invocations of the search function are
4495 <     * ignored.
4496 <     *
4497 <     * @param searchFunction a function returning a non-null
4498 <     * result on success, else null
4499 <     * @return a non-null result from applying the given search
4500 <     * function on each entry, or null if none
4501 <     */
4502 <    public <U> U searchEntriesInParallel
4503 <        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4504 <        return ForkJoinTasks.searchEntries
4505 <            (this, searchFunction).invoke();
4506 <    }
4507 <
4508 <    /**
4509 <     * Returns the result of accumulating all entries using the
4510 <     * given reducer to combine values, or null if none.
4511 <     *
4512 <     * @param reducer a commutative associative combining function
4513 <     * @return the result of accumulating all entries
4514 <     */
4515 <    public Map.Entry<K,V> reduceEntriesInParallel
4516 <        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4517 <        return ForkJoinTasks.reduceEntries
4518 <            (this, reducer).invoke();
4519 <    }
4520 <
4521 <    /**
4522 <     * Returns the result of accumulating the given transformation
4523 <     * of all entries using the given reducer to combine values,
4524 <     * or null if none.
4525 <     *
4526 <     * @param transformer a function returning the transformation
4527 <     * for an element, or null if there is no transformation (in
4528 <     * which case it is not combined)
4529 <     * @param reducer a commutative associative combining function
4530 <     * @return the result of accumulating the given transformation
4531 <     * of all entries
4532 <     */
4533 <    public <U> U reduceEntriesInParallel
4534 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4535 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4536 <        return ForkJoinTasks.reduceEntries
4537 <            (this, transformer, reducer).invoke();
4538 <    }
4539 <
4540 <    /**
4541 <     * Returns the result of accumulating the given transformation
4542 <     * of all entries using the given reducer to combine values,
4543 <     * and the given basis as an identity value.
4544 <     *
4545 <     * @param transformer a function returning the transformation
4546 <     * for an element
4547 <     * @param basis the identity (initial default value) for the reduction
4548 <     * @param reducer a commutative associative combining function
4549 <     * @return the result of accumulating the given transformation
4550 <     * of all entries
4551 <     */
4552 <    public double reduceEntriesToDoubleInParallel
4553 <        (ToDoubleFunction<Map.Entry<K,V>> transformer,
4554 <         double basis,
4555 <         DoubleBinaryOperator reducer) {
4556 <        return ForkJoinTasks.reduceEntriesToDouble
4557 <            (this, transformer, basis, reducer).invoke();
4558 <    }
4559 <
4560 <    /**
4561 <     * Returns the result of accumulating the given transformation
4562 <     * of all entries using the given reducer to combine values,
4563 <     * and the given basis as an identity value.
4564 <     *
4565 <     * @param transformer a function returning the transformation
4566 <     * for an element
4567 <     * @param basis the identity (initial default value) for the reduction
4568 <     * @param reducer a commutative associative combining function
4569 <     * @return the result of accumulating the given transformation
4570 <     * of all entries
4571 <     */
4572 <    public long reduceEntriesToLongInParallel
4573 <        (ToLongFunction<Map.Entry<K,V>> transformer,
4574 <         long basis,
4575 <         LongBinaryOperator reducer) {
4576 <        return ForkJoinTasks.reduceEntriesToLong
4577 <            (this, transformer, basis, reducer).invoke();
4578 <    }
4579 <
4580 <    /**
4581 <     * Returns the result of accumulating the given transformation
4582 <     * of all entries using the given reducer to combine values,
4583 <     * and the given basis as an identity value.
4584 <     *
4585 <     * @param transformer a function returning the transformation
4586 <     * for an element
4587 <     * @param basis the identity (initial default value) for the reduction
4588 <     * @param reducer a commutative associative combining function
4589 <     * @return the result of accumulating the given transformation
4590 <     * of all entries
4591 <     */
4592 <    public int reduceEntriesToIntInParallel
4593 <        (ToIntFunction<Map.Entry<K,V>> transformer,
4594 <         int basis,
4595 <         IntBinaryOperator reducer) {
4596 <        return ForkJoinTasks.reduceEntriesToInt
4597 <            (this, transformer, basis, reducer).invoke();
4379 >        return new MapReduceEntriesToIntTask<K,V>
4380 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4381 >             null, transformer, basis, reducer).invoke();
4382      }
4383  
4384  
# Line 4603 | Line 4387 | public class ConcurrentHashMap<K,V>
4387      /**
4388       * Base class for views.
4389       */
4390 <    abstract static class CHMCollectionView<K,V,E>
4391 <            implements Collection<E>, java.io.Serializable {
4390 >    abstract static class CollectionView<K,V,E>
4391 >        implements Collection<E>, java.io.Serializable {
4392          private static final long serialVersionUID = 7249069246763182397L;
4393          final ConcurrentHashMap<K,V> map;
4394 <        CHMCollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4394 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4395  
4396          /**
4397           * Returns the map backing this view.
# Line 4627 | Line 4411 | public class ConcurrentHashMap<K,V>
4411          // implementations below rely on concrete classes supplying these
4412          // abstract methods
4413          /**
4414 <         * Returns a "weakly consistent" iterator that will never
4415 <         * throw {@link ConcurrentModificationException}, and
4416 <         * guarantees to traverse elements as they existed upon
4417 <         * construction of the iterator, and may (but is not
4418 <         * guaranteed to) reflect any modifications subsequent to
4419 <         * construction.
4414 >         * Returns an iterator over the elements in this collection.
4415 >         *
4416 >         * <p>The returned iterator is
4417 >         * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
4418 >         *
4419 >         * @return an iterator over the elements in this collection
4420           */
4421          public abstract Iterator<E> iterator();
4422          public abstract boolean contains(Object o);
4423          public abstract boolean remove(Object o);
4424  
4425 <        private static final String oomeMsg = "Required array size too large";
4425 >        private static final String OOME_MSG = "Required array size too large";
4426  
4427          public final Object[] toArray() {
4428              long sz = map.mappingCount();
4429              if (sz > MAX_ARRAY_SIZE)
4430 <                throw new OutOfMemoryError(oomeMsg);
4430 >                throw new OutOfMemoryError(OOME_MSG);
4431              int n = (int)sz;
4432              Object[] r = new Object[n];
4433              int i = 0;
4434              for (E e : this) {
4435                  if (i == n) {
4436                      if (n >= MAX_ARRAY_SIZE)
4437 <                        throw new OutOfMemoryError(oomeMsg);
4437 >                        throw new OutOfMemoryError(OOME_MSG);
4438                      if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4439                          n = MAX_ARRAY_SIZE;
4440                      else
# Line 4666 | Line 4450 | public class ConcurrentHashMap<K,V>
4450          public final <T> T[] toArray(T[] a) {
4451              long sz = map.mappingCount();
4452              if (sz > MAX_ARRAY_SIZE)
4453 <                throw new OutOfMemoryError(oomeMsg);
4453 >                throw new OutOfMemoryError(OOME_MSG);
4454              int m = (int)sz;
4455              T[] r = (a.length >= m) ? a :
4456                  (T[])java.lang.reflect.Array
# Line 4676 | Line 4460 | public class ConcurrentHashMap<K,V>
4460              for (E e : this) {
4461                  if (i == n) {
4462                      if (n >= MAX_ARRAY_SIZE)
4463 <                        throw new OutOfMemoryError(oomeMsg);
4463 >                        throw new OutOfMemoryError(OOME_MSG);
4464                      if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4465                          n = MAX_ARRAY_SIZE;
4466                      else
# Line 4729 | Line 4513 | public class ConcurrentHashMap<K,V>
4513              return true;
4514          }
4515  
4516 <        public final boolean removeAll(Collection<?> c) {
4516 >        public boolean removeAll(Collection<?> c) {
4517 >            if (c == null) throw new NullPointerException();
4518              boolean modified = false;
4519 <            for (Iterator<E> it = iterator(); it.hasNext();) {
4520 <                if (c.contains(it.next())) {
4521 <                    it.remove();
4522 <                    modified = true;
4519 >            // Use (c instanceof Set) as a hint that lookup in c is as
4520 >            // efficient as this view
4521 >            Node<K,V>[] t;
4522 >            if ((t = map.table) == null) {
4523 >                return false;
4524 >            } else if (c instanceof Set<?> && c.size() > t.length) {
4525 >                for (Iterator<?> it = iterator(); it.hasNext(); ) {
4526 >                    if (c.contains(it.next())) {
4527 >                        it.remove();
4528 >                        modified = true;
4529 >                    }
4530                  }
4531 +            } else {
4532 +                for (Object e : c)
4533 +                    modified |= remove(e);
4534              }
4535              return modified;
4536          }
4537  
4538          public final boolean retainAll(Collection<?> c) {
4539 +            if (c == null) throw new NullPointerException();
4540              boolean modified = false;
4541              for (Iterator<E> it = iterator(); it.hasNext();) {
4542                  if (!c.contains(it.next())) {
# Line 4753 | Line 4549 | public class ConcurrentHashMap<K,V>
4549  
4550      }
4551  
4756    abstract static class CHMSetView<K,V,E>
4757            extends CHMCollectionView<K,V,E>
4758            implements Set<E>, java.io.Serializable {
4759        private static final long serialVersionUID = 7249069246763182397L;
4760        CHMSetView(ConcurrentHashMap<K,V> map) { super(map); }
4761
4762        // Implement Set API
4763
4764        /**
4765         * Implements {@link Set#hashCode()}.
4766         * @return the hash code value for this set
4767         */
4768        public final int hashCode() {
4769            int h = 0;
4770            for (E e : this)
4771                h += e.hashCode();
4772            return h;
4773        }
4774
4775        /**
4776         * Implements {@link Set#equals(Object)}.
4777         * @param o object to be compared for equality with this set
4778         * @return {@code true} if the specified object is equal to this set
4779        */
4780        public final boolean equals(Object o) {
4781            Set<?> c;
4782            return ((o instanceof Set) &&
4783                    ((c = (Set<?>)o) == this ||
4784                     (containsAll(c) && c.containsAll(this))));
4785        }
4786    }
4787
4552      /**
4553       * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4554       * which additions may optionally be enabled by mapping to a
# Line 4793 | Line 4557 | public class ConcurrentHashMap<K,V>
4557       * {@link #keySet(Object) keySet(V)},
4558       * {@link #newKeySet() newKeySet()},
4559       * {@link #newKeySet(int) newKeySet(int)}.
4560 +     *
4561 +     * @since 1.8
4562       */
4563 <    public static class KeySetView<K,V>
4564 <            extends CHMSetView<K,V,K>
4799 <            implements Set<K>, java.io.Serializable {
4563 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4564 >        implements Set<K>, java.io.Serializable {
4565          private static final long serialVersionUID = 7249069246763182397L;
4566 +        @SuppressWarnings("serial") // Conditionally serializable
4567          private final V value;
4568          KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4569              super(map);
# Line 4833 | Line 4599 | public class ConcurrentHashMap<K,V>
4599          /**
4600           * @return an iterator over the keys of the backing map
4601           */
4602 <        public Iterator<K> iterator() { return new KeyIterator<K,V>(map); }
4602 >        public Iterator<K> iterator() {
4603 >            Node<K,V>[] t;
4604 >            ConcurrentHashMap<K,V> m = map;
4605 >            int f = (t = m.table) == null ? 0 : t.length;
4606 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4607 >        }
4608  
4609          /**
4610           * Adds the specified key to this set view by mapping the key to
# Line 4849 | Line 4620 | public class ConcurrentHashMap<K,V>
4620              V v;
4621              if ((v = value) == null)
4622                  throw new UnsupportedOperationException();
4623 <            return map.internalPut(e, v, true) == null;
4623 >            return map.putVal(e, v, true) == null;
4624          }
4625  
4626          /**
# Line 4869 | Line 4640 | public class ConcurrentHashMap<K,V>
4640              if ((v = value) == null)
4641                  throw new UnsupportedOperationException();
4642              for (K e : c) {
4643 <                if (map.internalPut(e, v, true) == null)
4643 >                if (map.putVal(e, v, true) == null)
4644                      added = true;
4645              }
4646              return added;
4647          }
4648  
4649 +        public int hashCode() {
4650 +            int h = 0;
4651 +            for (K e : this)
4652 +                h += e.hashCode();
4653 +            return h;
4654 +        }
4655 +
4656 +        public boolean equals(Object o) {
4657 +            Set<?> c;
4658 +            return ((o instanceof Set) &&
4659 +                    ((c = (Set<?>)o) == this ||
4660 +                     (containsAll(c) && c.containsAll(this))));
4661 +        }
4662 +
4663          public Spliterator<K> spliterator() {
4664 <            return new KeyIterator<>(map, null);
4664 >            Node<K,V>[] t;
4665 >            ConcurrentHashMap<K,V> m = map;
4666 >            long n = m.sumCount();
4667 >            int f = (t = m.table) == null ? 0 : t.length;
4668 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4669          }
4670  
4671 +        public void forEach(Consumer<? super K> action) {
4672 +            if (action == null) throw new NullPointerException();
4673 +            Node<K,V>[] t;
4674 +            if ((t = map.table) != null) {
4675 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4676 +                for (Node<K,V> p; (p = it.advance()) != null; )
4677 +                    action.accept(p.key);
4678 +            }
4679 +        }
4680      }
4681  
4682      /**
4683       * A view of a ConcurrentHashMap as a {@link Collection} of
4684       * values, in which additions are disabled. This class cannot be
4685       * directly instantiated. See {@link #values()}.
4686 <     *
4687 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4688 <     * that will never throw {@link ConcurrentModificationException},
4891 <     * and guarantees to traverse elements as they existed upon
4892 <     * construction of the iterator, and may (but is not guaranteed to)
4893 <     * reflect any modifications subsequent to construction.
4894 <     */
4895 <    public static final class ValuesView<K,V>
4896 <            extends CHMCollectionView<K,V,V>
4897 <            implements Collection<V>, java.io.Serializable {
4686 >     */
4687 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4688 >        implements Collection<V>, java.io.Serializable {
4689          private static final long serialVersionUID = 2249069246763182397L;
4690          ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4691          public final boolean contains(Object o) {
4692              return map.containsValue(o);
4693          }
4694 +
4695          public final boolean remove(Object o) {
4696              if (o != null) {
4697                  for (Iterator<V> it = iterator(); it.hasNext();) {
# Line 4912 | Line 4704 | public class ConcurrentHashMap<K,V>
4704              return false;
4705          }
4706  
4915        /**
4916         * @return an iterator over the values of the backing map
4917         */
4707          public final Iterator<V> iterator() {
4708 <            return new ValueIterator<K,V>(map);
4708 >            ConcurrentHashMap<K,V> m = map;
4709 >            Node<K,V>[] t;
4710 >            int f = (t = m.table) == null ? 0 : t.length;
4711 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4712          }
4713  
4922        /** Always throws {@link UnsupportedOperationException}. */
4714          public final boolean add(V e) {
4715              throw new UnsupportedOperationException();
4716          }
4926        /** Always throws {@link UnsupportedOperationException}. */
4717          public final boolean addAll(Collection<? extends V> c) {
4718              throw new UnsupportedOperationException();
4719          }
4720  
4721 +        @Override public boolean removeAll(Collection<?> c) {
4722 +            if (c == null) throw new NullPointerException();
4723 +            boolean modified = false;
4724 +            for (Iterator<V> it = iterator(); it.hasNext();) {
4725 +                if (c.contains(it.next())) {
4726 +                    it.remove();
4727 +                    modified = true;
4728 +                }
4729 +            }
4730 +            return modified;
4731 +        }
4732 +
4733 +        public boolean removeIf(Predicate<? super V> filter) {
4734 +            return map.removeValueIf(filter);
4735 +        }
4736 +
4737          public Spliterator<V> spliterator() {
4738 <            return new ValueIterator<K,V>(map, null);
4738 >            Node<K,V>[] t;
4739 >            ConcurrentHashMap<K,V> m = map;
4740 >            long n = m.sumCount();
4741 >            int f = (t = m.table) == null ? 0 : t.length;
4742 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4743          }
4744  
4745 +        public void forEach(Consumer<? super V> action) {
4746 +            if (action == null) throw new NullPointerException();
4747 +            Node<K,V>[] t;
4748 +            if ((t = map.table) != null) {
4749 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4750 +                for (Node<K,V> p; (p = it.advance()) != null; )
4751 +                    action.accept(p.val);
4752 +            }
4753 +        }
4754      }
4755  
4756      /**
# Line 4939 | Line 4758 | public class ConcurrentHashMap<K,V>
4758       * entries.  This class cannot be directly instantiated. See
4759       * {@link #entrySet()}.
4760       */
4761 <    public static final class EntrySetView<K,V>
4762 <            extends CHMSetView<K,V,Map.Entry<K,V>>
4944 <            implements Set<Map.Entry<K,V>>, java.io.Serializable {
4761 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4762 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4763          private static final long serialVersionUID = 2249069246763182397L;
4764          EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4765  
4766 <        public final boolean contains(Object o) {
4766 >        public boolean contains(Object o) {
4767              Object k, v, r; Map.Entry<?,?> e;
4768              return ((o instanceof Map.Entry) &&
4769                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4953 | Line 4771 | public class ConcurrentHashMap<K,V>
4771                      (v = e.getValue()) != null &&
4772                      (v == r || v.equals(r)));
4773          }
4774 <        public final boolean remove(Object o) {
4774 >
4775 >        public boolean remove(Object o) {
4776              Object k, v; Map.Entry<?,?> e;
4777              return ((o instanceof Map.Entry) &&
4778                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4964 | Line 4783 | public class ConcurrentHashMap<K,V>
4783          /**
4784           * @return an iterator over the entries of the backing map
4785           */
4786 <        public final Iterator<Map.Entry<K,V>> iterator() {
4787 <            return new EntryIterator<K,V>(map);
4786 >        public Iterator<Map.Entry<K,V>> iterator() {
4787 >            ConcurrentHashMap<K,V> m = map;
4788 >            Node<K,V>[] t;
4789 >            int f = (t = m.table) == null ? 0 : t.length;
4790 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4791          }
4792  
4793 <        /**
4794 <         * Adds the specified mapping to this view.
4973 <         *
4974 <         * @param e mapping to be added
4975 <         * @return {@code true} if this set changed as a result of the call
4976 <         * @throws NullPointerException if the entry, its key, or its
4977 <         * value is null
4978 <         */
4979 <        public final boolean add(Entry<K,V> e) {
4980 <            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4793 >        public boolean add(Entry<K,V> e) {
4794 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4795          }
4796 <        /**
4797 <         * Adds all of the mappings in the specified collection to this
4984 <         * set, as if by calling {@link #add(Map.Entry)} on each one.
4985 <         * @param c the mappings to be inserted into this set
4986 <         * @return {@code true} if this set changed as a result of the call
4987 <         * @throws NullPointerException if the collection or any of its
4988 <         * entries, keys, or values are null
4989 <         */
4990 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4796 >
4797 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4798              boolean added = false;
4799              for (Entry<K,V> e : c) {
4800                  if (add(e))
# Line 4996 | Line 4803 | public class ConcurrentHashMap<K,V>
4803              return added;
4804          }
4805  
4806 <        public Spliterator<Map.Entry<K,V>> spliterator() {
4807 <            return new EntryIterator<K,V>(map, null);
5001 <        }
5002 <
5003 <    }
5004 <
5005 <    // ---------------------------------------------------------------------
5006 <
5007 <    /**
5008 <     * Predefined tasks for performing bulk parallel operations on
5009 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
5010 <     * for bulk operations. Each method has the same name, but returns
5011 <     * a task rather than invoking it. These methods may be useful in
5012 <     * custom applications such as submitting a task without waiting
5013 <     * for completion, using a custom pool, or combining with other
5014 <     * tasks.
5015 <     */
5016 <    public static class ForkJoinTasks {
5017 <        private ForkJoinTasks() {}
5018 <
5019 <        /**
5020 <         * Returns a task that when invoked, performs the given
5021 <         * action for each (key, value)
5022 <         *
5023 <         * @param map the map
5024 <         * @param action the action
5025 <         * @return the task
5026 <         */
5027 <        public static <K,V> ForkJoinTask<Void> forEach
5028 <            (ConcurrentHashMap<K,V> map,
5029 <             BiConsumer<? super K, ? super V> action) {
5030 <            if (action == null) throw new NullPointerException();
5031 <            return new ForEachMappingTask<K,V>(map, null, -1, action);
5032 <        }
5033 <
5034 <        /**
5035 <         * Returns a task that when invoked, performs the given
5036 <         * action for each non-null transformation of each (key, value)
5037 <         *
5038 <         * @param map the map
5039 <         * @param transformer a function returning the transformation
5040 <         * for an element, or null if there is no transformation (in
5041 <         * which case the action is not applied)
5042 <         * @param action the action
5043 <         * @return the task
5044 <         */
5045 <        public static <K,V,U> ForkJoinTask<Void> forEach
5046 <            (ConcurrentHashMap<K,V> map,
5047 <             BiFunction<? super K, ? super V, ? extends U> transformer,
5048 <             Consumer<? super U> action) {
5049 <            if (transformer == null || action == null)
5050 <                throw new NullPointerException();
5051 <            return new ForEachTransformedMappingTask<K,V,U>
5052 <                (map, null, -1, transformer, action);
5053 <        }
5054 <
5055 <        /**
5056 <         * Returns a task that when invoked, returns a non-null result
5057 <         * from applying the given search function on each (key,
5058 <         * value), or null if none. Upon success, further element
5059 <         * processing is suppressed and the results of any other
5060 <         * parallel invocations of the search function are ignored.
5061 <         *
5062 <         * @param map the map
5063 <         * @param searchFunction a function returning a non-null
5064 <         * result on success, else null
5065 <         * @return the task
5066 <         */
5067 <        public static <K,V,U> ForkJoinTask<U> search
5068 <            (ConcurrentHashMap<K,V> map,
5069 <             BiFunction<? super K, ? super V, ? extends U> searchFunction) {
5070 <            if (searchFunction == null) throw new NullPointerException();
5071 <            return new SearchMappingsTask<K,V,U>
5072 <                (map, null, -1, searchFunction,
5073 <                 new AtomicReference<U>());
5074 <        }
5075 <
5076 <        /**
5077 <         * Returns a task that when invoked, returns the result of
5078 <         * accumulating the given transformation of all (key, value) pairs
5079 <         * using the given reducer to combine values, or null if none.
5080 <         *
5081 <         * @param map the map
5082 <         * @param transformer a function returning the transformation
5083 <         * for an element, or null if there is no transformation (in
5084 <         * which case it is not combined)
5085 <         * @param reducer a commutative associative combining function
5086 <         * @return the task
5087 <         */
5088 <        public static <K,V,U> ForkJoinTask<U> reduce
5089 <            (ConcurrentHashMap<K,V> map,
5090 <             BiFunction<? super K, ? super V, ? extends U> transformer,
5091 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5092 <            if (transformer == null || reducer == null)
5093 <                throw new NullPointerException();
5094 <            return new MapReduceMappingsTask<K,V,U>
5095 <                (map, null, -1, null, transformer, reducer);
5096 <        }
5097 <
5098 <        /**
5099 <         * Returns a task that when invoked, returns the result of
5100 <         * accumulating the given transformation of all (key, value) pairs
5101 <         * using the given reducer to combine values, and the given
5102 <         * basis as an identity value.
5103 <         *
5104 <         * @param map the map
5105 <         * @param transformer a function returning the transformation
5106 <         * for an element
5107 <         * @param basis the identity (initial default value) for the reduction
5108 <         * @param reducer a commutative associative combining function
5109 <         * @return the task
5110 <         */
5111 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
5112 <            (ConcurrentHashMap<K,V> map,
5113 <             ToDoubleBiFunction<? super K, ? super V> transformer,
5114 <             double basis,
5115 <             DoubleBinaryOperator reducer) {
5116 <            if (transformer == null || reducer == null)
5117 <                throw new NullPointerException();
5118 <            return new MapReduceMappingsToDoubleTask<K,V>
5119 <                (map, null, -1, null, transformer, basis, reducer);
5120 <        }
5121 <
5122 <        /**
5123 <         * Returns a task that when invoked, returns the result of
5124 <         * accumulating the given transformation of all (key, value) pairs
5125 <         * using the given reducer to combine values, and the given
5126 <         * basis as an identity value.
5127 <         *
5128 <         * @param map the map
5129 <         * @param transformer a function returning the transformation
5130 <         * for an element
5131 <         * @param basis the identity (initial default value) for the reduction
5132 <         * @param reducer a commutative associative combining function
5133 <         * @return the task
5134 <         */
5135 <        public static <K,V> ForkJoinTask<Long> reduceToLong
5136 <            (ConcurrentHashMap<K,V> map,
5137 <             ToLongBiFunction<? super K, ? super V> transformer,
5138 <             long basis,
5139 <             LongBinaryOperator reducer) {
5140 <            if (transformer == null || reducer == null)
5141 <                throw new NullPointerException();
5142 <            return new MapReduceMappingsToLongTask<K,V>
5143 <                (map, null, -1, null, transformer, basis, reducer);
5144 <        }
5145 <
5146 <        /**
5147 <         * Returns a task that when invoked, returns the result of
5148 <         * accumulating the given transformation of all (key, value) pairs
5149 <         * using the given reducer to combine values, and the given
5150 <         * basis as an identity value.
5151 <         *
5152 <         * @param map the map
5153 <         * @param transformer a function returning the transformation
5154 <         * for an element
5155 <         * @param basis the identity (initial default value) for the reduction
5156 <         * @param reducer a commutative associative combining function
5157 <         * @return the task
5158 <         */
5159 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
5160 <            (ConcurrentHashMap<K,V> map,
5161 <             ToIntBiFunction<? super K, ? super V> transformer,
5162 <             int basis,
5163 <             IntBinaryOperator reducer) {
5164 <            if (transformer == null || reducer == null)
5165 <                throw new NullPointerException();
5166 <            return new MapReduceMappingsToIntTask<K,V>
5167 <                (map, null, -1, null, transformer, basis, reducer);
5168 <        }
5169 <
5170 <        /**
5171 <         * Returns a task that when invoked, performs the given action
5172 <         * for each key.
5173 <         *
5174 <         * @param map the map
5175 <         * @param action the action
5176 <         * @return the task
5177 <         */
5178 <        public static <K,V> ForkJoinTask<Void> forEachKey
5179 <            (ConcurrentHashMap<K,V> map,
5180 <             Consumer<? super K> action) {
5181 <            if (action == null) throw new NullPointerException();
5182 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
5183 <        }
5184 <
5185 <        /**
5186 <         * Returns a task that when invoked, performs the given action
5187 <         * for each non-null transformation of each key.
5188 <         *
5189 <         * @param map the map
5190 <         * @param transformer a function returning the transformation
5191 <         * for an element, or null if there is no transformation (in
5192 <         * which case the action is not applied)
5193 <         * @param action the action
5194 <         * @return the task
5195 <         */
5196 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
5197 <            (ConcurrentHashMap<K,V> map,
5198 <             Function<? super K, ? extends U> transformer,
5199 <             Consumer<? super U> action) {
5200 <            if (transformer == null || action == null)
5201 <                throw new NullPointerException();
5202 <            return new ForEachTransformedKeyTask<K,V,U>
5203 <                (map, null, -1, transformer, action);
5204 <        }
5205 <
5206 <        /**
5207 <         * Returns a task that when invoked, returns a non-null result
5208 <         * from applying the given search function on each key, or
5209 <         * null if none.  Upon success, further element processing is
5210 <         * suppressed and the results of any other parallel
5211 <         * invocations of the search function are ignored.
5212 <         *
5213 <         * @param map the map
5214 <         * @param searchFunction a function returning a non-null
5215 <         * result on success, else null
5216 <         * @return the task
5217 <         */
5218 <        public static <K,V,U> ForkJoinTask<U> searchKeys
5219 <            (ConcurrentHashMap<K,V> map,
5220 <             Function<? super K, ? extends U> searchFunction) {
5221 <            if (searchFunction == null) throw new NullPointerException();
5222 <            return new SearchKeysTask<K,V,U>
5223 <                (map, null, -1, searchFunction,
5224 <                 new AtomicReference<U>());
5225 <        }
5226 <
5227 <        /**
5228 <         * Returns a task that when invoked, returns the result of
5229 <         * accumulating all keys using the given reducer to combine
5230 <         * values, or null if none.
5231 <         *
5232 <         * @param map the map
5233 <         * @param reducer a commutative associative combining function
5234 <         * @return the task
5235 <         */
5236 <        public static <K,V> ForkJoinTask<K> reduceKeys
5237 <            (ConcurrentHashMap<K,V> map,
5238 <             BiFunction<? super K, ? super K, ? extends K> reducer) {
5239 <            if (reducer == null) throw new NullPointerException();
5240 <            return new ReduceKeysTask<K,V>
5241 <                (map, null, -1, null, reducer);
4806 >        public boolean removeIf(Predicate<? super Entry<K,V>> filter) {
4807 >            return map.removeEntryIf(filter);
4808          }
4809  
4810 <        /**
4811 <         * Returns a task that when invoked, returns the result of
4812 <         * accumulating the given transformation of all keys using the given
4813 <         * reducer to combine values, or null if none.
4814 <         *
4815 <         * @param map the map
4816 <         * @param transformer a function returning the transformation
4817 <         * for an element, or null if there is no transformation (in
4818 <         * which case it is not combined)
4819 <         * @param reducer a commutative associative combining function
5254 <         * @return the task
5255 <         */
5256 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
5257 <            (ConcurrentHashMap<K,V> map,
5258 <             Function<? super K, ? extends U> transformer,
5259 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5260 <            if (transformer == null || reducer == null)
5261 <                throw new NullPointerException();
5262 <            return new MapReduceKeysTask<K,V,U>
5263 <                (map, null, -1, null, transformer, reducer);
5264 <        }
5265 <
5266 <        /**
5267 <         * Returns a task that when invoked, returns the result of
5268 <         * accumulating the given transformation of all keys using the given
5269 <         * reducer to combine values, and the given basis as an
5270 <         * identity value.
5271 <         *
5272 <         * @param map the map
5273 <         * @param transformer a function returning the transformation
5274 <         * for an element
5275 <         * @param basis the identity (initial default value) for the reduction
5276 <         * @param reducer a commutative associative combining function
5277 <         * @return the task
5278 <         */
5279 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5280 <            (ConcurrentHashMap<K,V> map,
5281 <             ToDoubleFunction<? super K> transformer,
5282 <             double basis,
5283 <             DoubleBinaryOperator reducer) {
5284 <            if (transformer == null || reducer == null)
5285 <                throw new NullPointerException();
5286 <            return new MapReduceKeysToDoubleTask<K,V>
5287 <                (map, null, -1, null, transformer, basis, reducer);
5288 <        }
5289 <
5290 <        /**
5291 <         * Returns a task that when invoked, returns the result of
5292 <         * accumulating the given transformation of all keys using the given
5293 <         * reducer to combine values, and the given basis as an
5294 <         * identity value.
5295 <         *
5296 <         * @param map the map
5297 <         * @param transformer a function returning the transformation
5298 <         * for an element
5299 <         * @param basis the identity (initial default value) for the reduction
5300 <         * @param reducer a commutative associative combining function
5301 <         * @return the task
5302 <         */
5303 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5304 <            (ConcurrentHashMap<K,V> map,
5305 <             ToLongFunction<? super K> transformer,
5306 <             long basis,
5307 <             LongBinaryOperator reducer) {
5308 <            if (transformer == null || reducer == null)
5309 <                throw new NullPointerException();
5310 <            return new MapReduceKeysToLongTask<K,V>
5311 <                (map, null, -1, null, transformer, basis, reducer);
5312 <        }
5313 <
5314 <        /**
5315 <         * Returns a task that when invoked, returns the result of
5316 <         * accumulating the given transformation of all keys using the given
5317 <         * reducer to combine values, and the given basis as an
5318 <         * identity value.
5319 <         *
5320 <         * @param map the map
5321 <         * @param transformer a function returning the transformation
5322 <         * for an element
5323 <         * @param basis the identity (initial default value) for the reduction
5324 <         * @param reducer a commutative associative combining function
5325 <         * @return the task
5326 <         */
5327 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5328 <            (ConcurrentHashMap<K,V> map,
5329 <             ToIntFunction<? super K> transformer,
5330 <             int basis,
5331 <             IntBinaryOperator reducer) {
5332 <            if (transformer == null || reducer == null)
5333 <                throw new NullPointerException();
5334 <            return new MapReduceKeysToIntTask<K,V>
5335 <                (map, null, -1, null, transformer, basis, reducer);
5336 <        }
5337 <
5338 <        /**
5339 <         * Returns a task that when invoked, performs the given action
5340 <         * for each value.
5341 <         *
5342 <         * @param map the map
5343 <         * @param action the action
5344 <         * @return the task
5345 <         */
5346 <        public static <K,V> ForkJoinTask<Void> forEachValue
5347 <            (ConcurrentHashMap<K,V> map,
5348 <             Consumer<? super V> action) {
5349 <            if (action == null) throw new NullPointerException();
5350 <            return new ForEachValueTask<K,V>(map, null, -1, action);
5351 <        }
5352 <
5353 <        /**
5354 <         * Returns a task that when invoked, performs the given action
5355 <         * for each non-null transformation of each value.
5356 <         *
5357 <         * @param map the map
5358 <         * @param transformer a function returning the transformation
5359 <         * for an element, or null if there is no transformation (in
5360 <         * which case the action is not applied)
5361 <         * @param action the action
5362 <         * @return the task
5363 <         */
5364 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
5365 <            (ConcurrentHashMap<K,V> map,
5366 <             Function<? super V, ? extends U> transformer,
5367 <             Consumer<? super U> action) {
5368 <            if (transformer == null || action == null)
5369 <                throw new NullPointerException();
5370 <            return new ForEachTransformedValueTask<K,V,U>
5371 <                (map, null, -1, transformer, action);
5372 <        }
5373 <
5374 <        /**
5375 <         * Returns a task that when invoked, returns a non-null result
5376 <         * from applying the given search function on each value, or
5377 <         * null if none.  Upon success, further element processing is
5378 <         * suppressed and the results of any other parallel
5379 <         * invocations of the search function are ignored.
5380 <         *
5381 <         * @param map the map
5382 <         * @param searchFunction a function returning a non-null
5383 <         * result on success, else null
5384 <         * @return the task
5385 <         */
5386 <        public static <K,V,U> ForkJoinTask<U> searchValues
5387 <            (ConcurrentHashMap<K,V> map,
5388 <             Function<? super V, ? extends U> searchFunction) {
5389 <            if (searchFunction == null) throw new NullPointerException();
5390 <            return new SearchValuesTask<K,V,U>
5391 <                (map, null, -1, searchFunction,
5392 <                 new AtomicReference<U>());
5393 <        }
5394 <
5395 <        /**
5396 <         * Returns a task that when invoked, returns the result of
5397 <         * accumulating all values using the given reducer to combine
5398 <         * values, or null if none.
5399 <         *
5400 <         * @param map the map
5401 <         * @param reducer a commutative associative combining function
5402 <         * @return the task
5403 <         */
5404 <        public static <K,V> ForkJoinTask<V> reduceValues
5405 <            (ConcurrentHashMap<K,V> map,
5406 <             BiFunction<? super V, ? super V, ? extends V> reducer) {
5407 <            if (reducer == null) throw new NullPointerException();
5408 <            return new ReduceValuesTask<K,V>
5409 <                (map, null, -1, null, reducer);
5410 <        }
5411 <
5412 <        /**
5413 <         * Returns a task that when invoked, returns the result of
5414 <         * accumulating the given transformation of all values using the
5415 <         * given reducer to combine values, or null if none.
5416 <         *
5417 <         * @param map the map
5418 <         * @param transformer a function returning the transformation
5419 <         * for an element, or null if there is no transformation (in
5420 <         * which case it is not combined)
5421 <         * @param reducer a commutative associative combining function
5422 <         * @return the task
5423 <         */
5424 <        public static <K,V,U> ForkJoinTask<U> reduceValues
5425 <            (ConcurrentHashMap<K,V> map,
5426 <             Function<? super V, ? extends U> transformer,
5427 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5428 <            if (transformer == null || reducer == null)
5429 <                throw new NullPointerException();
5430 <            return new MapReduceValuesTask<K,V,U>
5431 <                (map, null, -1, null, transformer, reducer);
5432 <        }
5433 <
5434 <        /**
5435 <         * Returns a task that when invoked, returns the result of
5436 <         * accumulating the given transformation of all values using the
5437 <         * given reducer to combine values, and the given basis as an
5438 <         * identity value.
5439 <         *
5440 <         * @param map the map
5441 <         * @param transformer a function returning the transformation
5442 <         * for an element
5443 <         * @param basis the identity (initial default value) for the reduction
5444 <         * @param reducer a commutative associative combining function
5445 <         * @return the task
5446 <         */
5447 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5448 <            (ConcurrentHashMap<K,V> map,
5449 <             ToDoubleFunction<? super V> transformer,
5450 <             double basis,
5451 <             DoubleBinaryOperator reducer) {
5452 <            if (transformer == null || reducer == null)
5453 <                throw new NullPointerException();
5454 <            return new MapReduceValuesToDoubleTask<K,V>
5455 <                (map, null, -1, null, transformer, basis, reducer);
4810 >        public final int hashCode() {
4811 >            int h = 0;
4812 >            Node<K,V>[] t;
4813 >            if ((t = map.table) != null) {
4814 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4815 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4816 >                    h += p.hashCode();
4817 >                }
4818 >            }
4819 >            return h;
4820          }
4821  
4822 <        /**
4823 <         * Returns a task that when invoked, returns the result of
4824 <         * accumulating the given transformation of all values using the
4825 <         * given reducer to combine values, and the given basis as an
4826 <         * identity value.
5463 <         *
5464 <         * @param map the map
5465 <         * @param transformer a function returning the transformation
5466 <         * for an element
5467 <         * @param basis the identity (initial default value) for the reduction
5468 <         * @param reducer a commutative associative combining function
5469 <         * @return the task
5470 <         */
5471 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5472 <            (ConcurrentHashMap<K,V> map,
5473 <             ToLongFunction<? super V> transformer,
5474 <             long basis,
5475 <             LongBinaryOperator reducer) {
5476 <            if (transformer == null || reducer == null)
5477 <                throw new NullPointerException();
5478 <            return new MapReduceValuesToLongTask<K,V>
5479 <                (map, null, -1, null, transformer, basis, reducer);
4822 >        public final boolean equals(Object o) {
4823 >            Set<?> c;
4824 >            return ((o instanceof Set) &&
4825 >                    ((c = (Set<?>)o) == this ||
4826 >                     (containsAll(c) && c.containsAll(this))));
4827          }
4828  
4829 <        /**
4830 <         * Returns a task that when invoked, returns the result of
4831 <         * accumulating the given transformation of all values using the
4832 <         * given reducer to combine values, and the given basis as an
4833 <         * identity value.
4834 <         *
5488 <         * @param map the map
5489 <         * @param transformer a function returning the transformation
5490 <         * for an element
5491 <         * @param basis the identity (initial default value) for the reduction
5492 <         * @param reducer a commutative associative combining function
5493 <         * @return the task
5494 <         */
5495 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5496 <            (ConcurrentHashMap<K,V> map,
5497 <             ToIntFunction<? super V> transformer,
5498 <             int basis,
5499 <             IntBinaryOperator reducer) {
5500 <            if (transformer == null || reducer == null)
5501 <                throw new NullPointerException();
5502 <            return new MapReduceValuesToIntTask<K,V>
5503 <                (map, null, -1, null, transformer, basis, reducer);
4829 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4830 >            Node<K,V>[] t;
4831 >            ConcurrentHashMap<K,V> m = map;
4832 >            long n = m.sumCount();
4833 >            int f = (t = m.table) == null ? 0 : t.length;
4834 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4835          }
4836  
4837 <        /**
5507 <         * Returns a task that when invoked, perform the given action
5508 <         * for each entry.
5509 <         *
5510 <         * @param map the map
5511 <         * @param action the action
5512 <         * @return the task
5513 <         */
5514 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5515 <            (ConcurrentHashMap<K,V> map,
5516 <             Consumer<? super Map.Entry<K,V>> action) {
4837 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4838              if (action == null) throw new NullPointerException();
4839 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
4840 <        }
4841 <
4842 <        /**
4843 <         * Returns a task that when invoked, perform the given action
4844 <         * for each non-null transformation of each entry.
5524 <         *
5525 <         * @param map the map
5526 <         * @param transformer a function returning the transformation
5527 <         * for an element, or null if there is no transformation (in
5528 <         * which case the action is not applied)
5529 <         * @param action the action
5530 <         * @return the task
5531 <         */
5532 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5533 <            (ConcurrentHashMap<K,V> map,
5534 <             Function<Map.Entry<K,V>, ? extends U> transformer,
5535 <             Consumer<? super U> action) {
5536 <            if (transformer == null || action == null)
5537 <                throw new NullPointerException();
5538 <            return new ForEachTransformedEntryTask<K,V,U>
5539 <                (map, null, -1, transformer, action);
5540 <        }
5541 <
5542 <        /**
5543 <         * Returns a task that when invoked, returns a non-null result
5544 <         * from applying the given search function on each entry, or
5545 <         * null if none.  Upon success, further element processing is
5546 <         * suppressed and the results of any other parallel
5547 <         * invocations of the search function are ignored.
5548 <         *
5549 <         * @param map the map
5550 <         * @param searchFunction a function returning a non-null
5551 <         * result on success, else null
5552 <         * @return the task
5553 <         */
5554 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5555 <            (ConcurrentHashMap<K,V> map,
5556 <             Function<Map.Entry<K,V>, ? extends U> searchFunction) {
5557 <            if (searchFunction == null) throw new NullPointerException();
5558 <            return new SearchEntriesTask<K,V,U>
5559 <                (map, null, -1, searchFunction,
5560 <                 new AtomicReference<U>());
4839 >            Node<K,V>[] t;
4840 >            if ((t = map.table) != null) {
4841 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4842 >                for (Node<K,V> p; (p = it.advance()) != null; )
4843 >                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
4844 >            }
4845          }
4846  
4847 <        /**
5564 <         * Returns a task that when invoked, returns the result of
5565 <         * accumulating all entries using the given reducer to combine
5566 <         * values, or null if none.
5567 <         *
5568 <         * @param map the map
5569 <         * @param reducer a commutative associative combining function
5570 <         * @return the task
5571 <         */
5572 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5573 <            (ConcurrentHashMap<K,V> map,
5574 <             BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5575 <            if (reducer == null) throw new NullPointerException();
5576 <            return new ReduceEntriesTask<K,V>
5577 <                (map, null, -1, null, reducer);
5578 <        }
4847 >    }
4848  
4849 <        /**
5581 <         * Returns a task that when invoked, returns the result of
5582 <         * accumulating the given transformation of all entries using the
5583 <         * given reducer to combine values, or null if none.
5584 <         *
5585 <         * @param map the map
5586 <         * @param transformer a function returning the transformation
5587 <         * for an element, or null if there is no transformation (in
5588 <         * which case it is not combined)
5589 <         * @param reducer a commutative associative combining function
5590 <         * @return the task
5591 <         */
5592 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5593 <            (ConcurrentHashMap<K,V> map,
5594 <             Function<Map.Entry<K,V>, ? extends U> transformer,
5595 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5596 <            if (transformer == null || reducer == null)
5597 <                throw new NullPointerException();
5598 <            return new MapReduceEntriesTask<K,V,U>
5599 <                (map, null, -1, null, transformer, reducer);
5600 <        }
4849 >    // -------------------------------------------------------
4850  
4851 <        /**
4852 <         * Returns a task that when invoked, returns the result of
4853 <         * accumulating the given transformation of all entries using the
4854 <         * given reducer to combine values, and the given basis as an
4855 <         * identity value.
4856 <         *
4857 <         * @param map the map
4858 <         * @param transformer a function returning the transformation
4859 <         * for an element
4860 <         * @param basis the identity (initial default value) for the reduction
4861 <         * @param reducer a commutative associative combining function
4862 <         * @return the task
4863 <         */
4864 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
4865 <            (ConcurrentHashMap<K,V> map,
4866 <             ToDoubleFunction<Map.Entry<K,V>> transformer,
4867 <             double basis,
4868 <             DoubleBinaryOperator reducer) {
4869 <            if (transformer == null || reducer == null)
4870 <                throw new NullPointerException();
4871 <            return new MapReduceEntriesToDoubleTask<K,V>
4872 <                (map, null, -1, null, transformer, basis, reducer);
4851 >    /**
4852 >     * Base class for bulk tasks. Repeats some fields and code from
4853 >     * class Traverser, because we need to subclass CountedCompleter.
4854 >     */
4855 >    @SuppressWarnings("serial")
4856 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4857 >        Node<K,V>[] tab;        // same as Traverser
4858 >        Node<K,V> next;
4859 >        TableStack<K,V> stack, spare;
4860 >        int index;
4861 >        int baseIndex;
4862 >        int baseLimit;
4863 >        final int baseSize;
4864 >        int batch;              // split control
4865 >
4866 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4867 >            super(par);
4868 >            this.batch = b;
4869 >            this.index = this.baseIndex = i;
4870 >            if ((this.tab = t) == null)
4871 >                this.baseSize = this.baseLimit = 0;
4872 >            else if (par == null)
4873 >                this.baseSize = this.baseLimit = t.length;
4874 >            else {
4875 >                this.baseLimit = f;
4876 >                this.baseSize = par.baseSize;
4877 >            }
4878          }
4879  
4880          /**
4881 <         * Returns a task that when invoked, returns the result of
5628 <         * accumulating the given transformation of all entries using the
5629 <         * given reducer to combine values, and the given basis as an
5630 <         * identity value.
5631 <         *
5632 <         * @param map the map
5633 <         * @param transformer a function returning the transformation
5634 <         * for an element
5635 <         * @param basis the identity (initial default value) for the reduction
5636 <         * @param reducer a commutative associative combining function
5637 <         * @return the task
4881 >         * Same as Traverser version.
4882           */
4883 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4884 <            (ConcurrentHashMap<K,V> map,
4885 <             ToLongFunction<Map.Entry<K,V>> transformer,
4886 <             long basis,
4887 <             LongBinaryOperator reducer) {
4888 <            if (transformer == null || reducer == null)
4889 <                throw new NullPointerException();
4890 <            return new MapReduceEntriesToLongTask<K,V>
4891 <                (map, null, -1, null, transformer, basis, reducer);
4883 >        final Node<K,V> advance() {
4884 >            Node<K,V> e;
4885 >            if ((e = next) != null)
4886 >                e = e.next;
4887 >            for (;;) {
4888 >                Node<K,V>[] t; int i, n;
4889 >                if (e != null)
4890 >                    return next = e;
4891 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4892 >                    (n = t.length) <= (i = index) || i < 0)
4893 >                    return next = null;
4894 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
4895 >                    if (e instanceof ForwardingNode) {
4896 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4897 >                        e = null;
4898 >                        pushState(t, i, n);
4899 >                        continue;
4900 >                    }
4901 >                    else if (e instanceof TreeBin)
4902 >                        e = ((TreeBin<K,V>)e).first;
4903 >                    else
4904 >                        e = null;
4905 >                }
4906 >                if (stack != null)
4907 >                    recoverState(n);
4908 >                else if ((index = i + baseSize) >= n)
4909 >                    index = ++baseIndex;
4910 >            }
4911          }
4912  
4913 <        /**
4914 <         * Returns a task that when invoked, returns the result of
4915 <         * accumulating the given transformation of all entries using the
4916 <         * given reducer to combine values, and the given basis as an
4917 <         * identity value.
4918 <         *
4919 <         * @param map the map
4920 <         * @param transformer a function returning the transformation
4921 <         * for an element
4922 <         * @param basis the identity (initial default value) for the reduction
4923 <         * @param reducer a commutative associative combining function
4924 <         * @return the task
4925 <         */
4926 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4927 <            (ConcurrentHashMap<K,V> map,
4928 <             ToIntFunction<Map.Entry<K,V>> transformer,
4929 <             int basis,
4930 <             IntBinaryOperator reducer) {
4931 <            if (transformer == null || reducer == null)
4932 <                throw new NullPointerException();
4933 <            return new MapReduceEntriesToIntTask<K,V>
4934 <                (map, null, -1, null, transformer, basis, reducer);
4913 >        private void pushState(Node<K,V>[] t, int i, int n) {
4914 >            TableStack<K,V> s = spare;
4915 >            if (s != null)
4916 >                spare = s.next;
4917 >            else
4918 >                s = new TableStack<K,V>();
4919 >            s.tab = t;
4920 >            s.length = n;
4921 >            s.index = i;
4922 >            s.next = stack;
4923 >            stack = s;
4924 >        }
4925 >
4926 >        private void recoverState(int n) {
4927 >            TableStack<K,V> s; int len;
4928 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
4929 >                n = len;
4930 >                index = s.index;
4931 >                tab = s.tab;
4932 >                s.tab = null;
4933 >                TableStack<K,V> next = s.next;
4934 >                s.next = spare; // save for reuse
4935 >                stack = next;
4936 >                spare = s;
4937 >            }
4938 >            if (s == null && (index += baseSize) >= n)
4939 >                index = ++baseIndex;
4940          }
4941      }
4942  
5675    // -------------------------------------------------------
5676
4943      /*
4944       * Task classes. Coded in a regular but ugly format/style to
4945       * simplify checks that each variant differs in the right way from
# Line 5681 | Line 4947 | public class ConcurrentHashMap<K,V>
4947       * that we've already null-checked task arguments, so we force
4948       * simplest hoisted bypass to help avoid convoluted traps.
4949       */
4950 <
4951 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4952 <        extends Traverser<K,V,Void> {
4950 >    @SuppressWarnings("serial")
4951 >    static final class ForEachKeyTask<K,V>
4952 >        extends BulkTask<K,V,Void> {
4953          final Consumer<? super K> action;
4954          ForEachKeyTask
4955 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4955 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4956               Consumer<? super K> action) {
4957 <            super(m, p, b);
4957 >            super(p, b, i, f, t);
4958              this.action = action;
4959          }
4960          public final void compute() {
4961              final Consumer<? super K> action;
4962              if ((action = this.action) != null) {
4963 <                for (int b; (b = preSplit()) > 0;)
4964 <                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
4965 <                forEachKey(action);
4963 >                for (int i = baseIndex, f, h; batch > 0 &&
4964 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4965 >                    addToPendingCount(1);
4966 >                    new ForEachKeyTask<K,V>
4967 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4968 >                         action).fork();
4969 >                }
4970 >                for (Node<K,V> p; (p = advance()) != null;)
4971 >                    action.accept(p.key);
4972                  propagateCompletion();
4973              }
4974          }
4975      }
4976  
4977 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4978 <        extends Traverser<K,V,Void> {
4977 >    @SuppressWarnings("serial")
4978 >    static final class ForEachValueTask<K,V>
4979 >        extends BulkTask<K,V,Void> {
4980          final Consumer<? super V> action;
4981          ForEachValueTask
4982 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4982 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4983               Consumer<? super V> action) {
4984 <            super(m, p, b);
4984 >            super(p, b, i, f, t);
4985              this.action = action;
4986          }
4987          public final void compute() {
4988              final Consumer<? super V> action;
4989              if ((action = this.action) != null) {
4990 <                for (int b; (b = preSplit()) > 0;)
4991 <                    new ForEachValueTask<K,V>(map, this, b, action).fork();
4992 <                forEachValue(action);
4990 >                for (int i = baseIndex, f, h; batch > 0 &&
4991 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4992 >                    addToPendingCount(1);
4993 >                    new ForEachValueTask<K,V>
4994 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4995 >                         action).fork();
4996 >                }
4997 >                for (Node<K,V> p; (p = advance()) != null;)
4998 >                    action.accept(p.val);
4999                  propagateCompletion();
5000              }
5001          }
5002      }
5003  
5004 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
5005 <        extends Traverser<K,V,Void> {
5004 >    @SuppressWarnings("serial")
5005 >    static final class ForEachEntryTask<K,V>
5006 >        extends BulkTask<K,V,Void> {
5007          final Consumer<? super Entry<K,V>> action;
5008          ForEachEntryTask
5009 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5009 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5010               Consumer<? super Entry<K,V>> action) {
5011 <            super(m, p, b);
5011 >            super(p, b, i, f, t);
5012              this.action = action;
5013          }
5014          public final void compute() {
5015              final Consumer<? super Entry<K,V>> action;
5016              if ((action = this.action) != null) {
5017 <                for (int b; (b = preSplit()) > 0;)
5018 <                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
5019 <                V v;
5020 <                while ((v = advanceValue()) != null)
5021 <                    action.accept(entryFor(nextKey, v));
5017 >                for (int i = baseIndex, f, h; batch > 0 &&
5018 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5019 >                    addToPendingCount(1);
5020 >                    new ForEachEntryTask<K,V>
5021 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5022 >                         action).fork();
5023 >                }
5024 >                for (Node<K,V> p; (p = advance()) != null; )
5025 >                    action.accept(p);
5026                  propagateCompletion();
5027              }
5028          }
5029      }
5030  
5031 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5032 <        extends Traverser<K,V,Void> {
5031 >    @SuppressWarnings("serial")
5032 >    static final class ForEachMappingTask<K,V>
5033 >        extends BulkTask<K,V,Void> {
5034          final BiConsumer<? super K, ? super V> action;
5035          ForEachMappingTask
5036 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5036 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5037               BiConsumer<? super K,? super V> action) {
5038 <            super(m, p, b);
5038 >            super(p, b, i, f, t);
5039              this.action = action;
5040          }
5041          public final void compute() {
5042              final BiConsumer<? super K, ? super V> action;
5043              if ((action = this.action) != null) {
5044 <                for (int b; (b = preSplit()) > 0;)
5045 <                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
5046 <                V v;
5047 <                while ((v = advanceValue()) != null)
5048 <                    action.accept(nextKey, v);
5044 >                for (int i = baseIndex, f, h; batch > 0 &&
5045 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5046 >                    addToPendingCount(1);
5047 >                    new ForEachMappingTask<K,V>
5048 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5049 >                         action).fork();
5050 >                }
5051 >                for (Node<K,V> p; (p = advance()) != null; )
5052 >                    action.accept(p.key, p.val);
5053                  propagateCompletion();
5054              }
5055          }
5056      }
5057  
5058 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5059 <        extends Traverser<K,V,Void> {
5058 >    @SuppressWarnings("serial")
5059 >    static final class ForEachTransformedKeyTask<K,V,U>
5060 >        extends BulkTask<K,V,Void> {
5061          final Function<? super K, ? extends U> transformer;
5062          final Consumer<? super U> action;
5063          ForEachTransformedKeyTask
5064 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5064 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5065               Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5066 <            super(m, p, b);
5066 >            super(p, b, i, f, t);
5067              this.transformer = transformer; this.action = action;
5068          }
5069          public final void compute() {
# Line 5781 | Line 5071 | public class ConcurrentHashMap<K,V>
5071              final Consumer<? super U> action;
5072              if ((transformer = this.transformer) != null &&
5073                  (action = this.action) != null) {
5074 <                for (int b; (b = preSplit()) > 0;)
5074 >                for (int i = baseIndex, f, h; batch > 0 &&
5075 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5076 >                    addToPendingCount(1);
5077                      new ForEachTransformedKeyTask<K,V,U>
5078 <                        (map, this, b, transformer, action).fork();
5079 <                K k; U u;
5080 <                while ((k = advanceKey()) != null) {
5081 <                    if ((u = transformer.apply(k)) != null)
5078 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5079 >                         transformer, action).fork();
5080 >                }
5081 >                for (Node<K,V> p; (p = advance()) != null; ) {
5082 >                    U u;
5083 >                    if ((u = transformer.apply(p.key)) != null)
5084                          action.accept(u);
5085                  }
5086                  propagateCompletion();
# Line 5794 | Line 5088 | public class ConcurrentHashMap<K,V>
5088          }
5089      }
5090  
5091 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5092 <        extends Traverser<K,V,Void> {
5091 >    @SuppressWarnings("serial")
5092 >    static final class ForEachTransformedValueTask<K,V,U>
5093 >        extends BulkTask<K,V,Void> {
5094          final Function<? super V, ? extends U> transformer;
5095          final Consumer<? super U> action;
5096          ForEachTransformedValueTask
5097 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5097 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5098               Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5099 <            super(m, p, b);
5099 >            super(p, b, i, f, t);
5100              this.transformer = transformer; this.action = action;
5101          }
5102          public final void compute() {
# Line 5809 | Line 5104 | public class ConcurrentHashMap<K,V>
5104              final Consumer<? super U> action;
5105              if ((transformer = this.transformer) != null &&
5106                  (action = this.action) != null) {
5107 <                for (int b; (b = preSplit()) > 0;)
5107 >                for (int i = baseIndex, f, h; batch > 0 &&
5108 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5109 >                    addToPendingCount(1);
5110                      new ForEachTransformedValueTask<K,V,U>
5111 <                        (map, this, b, transformer, action).fork();
5112 <                V v; U u;
5113 <                while ((v = advanceValue()) != null) {
5114 <                    if ((u = transformer.apply(v)) != null)
5111 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5112 >                         transformer, action).fork();
5113 >                }
5114 >                for (Node<K,V> p; (p = advance()) != null; ) {
5115 >                    U u;
5116 >                    if ((u = transformer.apply(p.val)) != null)
5117                          action.accept(u);
5118                  }
5119                  propagateCompletion();
# Line 5822 | Line 5121 | public class ConcurrentHashMap<K,V>
5121          }
5122      }
5123  
5124 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5125 <        extends Traverser<K,V,Void> {
5124 >    @SuppressWarnings("serial")
5125 >    static final class ForEachTransformedEntryTask<K,V,U>
5126 >        extends BulkTask<K,V,Void> {
5127          final Function<Map.Entry<K,V>, ? extends U> transformer;
5128          final Consumer<? super U> action;
5129          ForEachTransformedEntryTask
5130 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5130 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5131               Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5132 <            super(m, p, b);
5132 >            super(p, b, i, f, t);
5133              this.transformer = transformer; this.action = action;
5134          }
5135          public final void compute() {
# Line 5837 | Line 5137 | public class ConcurrentHashMap<K,V>
5137              final Consumer<? super U> action;
5138              if ((transformer = this.transformer) != null &&
5139                  (action = this.action) != null) {
5140 <                for (int b; (b = preSplit()) > 0;)
5140 >                for (int i = baseIndex, f, h; batch > 0 &&
5141 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5142 >                    addToPendingCount(1);
5143                      new ForEachTransformedEntryTask<K,V,U>
5144 <                        (map, this, b, transformer, action).fork();
5145 <                V v; U u;
5146 <                while ((v = advanceValue()) != null) {
5147 <                    if ((u = transformer.apply(entryFor(nextKey,
5148 <                                                        v))) != null)
5144 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5145 >                         transformer, action).fork();
5146 >                }
5147 >                for (Node<K,V> p; (p = advance()) != null; ) {
5148 >                    U u;
5149 >                    if ((u = transformer.apply(p)) != null)
5150                          action.accept(u);
5151                  }
5152                  propagateCompletion();
# Line 5851 | Line 5154 | public class ConcurrentHashMap<K,V>
5154          }
5155      }
5156  
5157 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5158 <        extends Traverser<K,V,Void> {
5157 >    @SuppressWarnings("serial")
5158 >    static final class ForEachTransformedMappingTask<K,V,U>
5159 >        extends BulkTask<K,V,Void> {
5160          final BiFunction<? super K, ? super V, ? extends U> transformer;
5161          final Consumer<? super U> action;
5162          ForEachTransformedMappingTask
5163 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5163 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5164               BiFunction<? super K, ? super V, ? extends U> transformer,
5165               Consumer<? super U> action) {
5166 <            super(m, p, b);
5166 >            super(p, b, i, f, t);
5167              this.transformer = transformer; this.action = action;
5168          }
5169          public final void compute() {
# Line 5867 | Line 5171 | public class ConcurrentHashMap<K,V>
5171              final Consumer<? super U> action;
5172              if ((transformer = this.transformer) != null &&
5173                  (action = this.action) != null) {
5174 <                for (int b; (b = preSplit()) > 0;)
5174 >                for (int i = baseIndex, f, h; batch > 0 &&
5175 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5176 >                    addToPendingCount(1);
5177                      new ForEachTransformedMappingTask<K,V,U>
5178 <                        (map, this, b, transformer, action).fork();
5179 <                V v; U u;
5180 <                while ((v = advanceValue()) != null) {
5181 <                    if ((u = transformer.apply(nextKey, v)) != null)
5178 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5179 >                         transformer, action).fork();
5180 >                }
5181 >                for (Node<K,V> p; (p = advance()) != null; ) {
5182 >                    U u;
5183 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5184                          action.accept(u);
5185                  }
5186                  propagateCompletion();
# Line 5880 | Line 5188 | public class ConcurrentHashMap<K,V>
5188          }
5189      }
5190  
5191 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5192 <        extends Traverser<K,V,U> {
5191 >    @SuppressWarnings("serial")
5192 >    static final class SearchKeysTask<K,V,U>
5193 >        extends BulkTask<K,V,U> {
5194          final Function<? super K, ? extends U> searchFunction;
5195          final AtomicReference<U> result;
5196          SearchKeysTask
5197 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5197 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5198               Function<? super K, ? extends U> searchFunction,
5199               AtomicReference<U> result) {
5200 <            super(m, p, b);
5200 >            super(p, b, i, f, t);
5201              this.searchFunction = searchFunction; this.result = result;
5202          }
5203          public final U getRawResult() { return result.get(); }
# Line 5897 | Line 5206 | public class ConcurrentHashMap<K,V>
5206              final AtomicReference<U> result;
5207              if ((searchFunction = this.searchFunction) != null &&
5208                  (result = this.result) != null) {
5209 <                for (int b;;) {
5209 >                for (int i = baseIndex, f, h; batch > 0 &&
5210 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5211                      if (result.get() != null)
5212                          return;
5213 <                    if ((b = preSplit()) <= 0)
5904 <                        break;
5213 >                    addToPendingCount(1);
5214                      new SearchKeysTask<K,V,U>
5215 <                        (map, this, b, searchFunction, result).fork();
5215 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5216 >                         searchFunction, result).fork();
5217                  }
5218                  while (result.get() == null) {
5219 <                    K k; U u;
5220 <                    if ((k = advanceKey()) == null) {
5219 >                    U u;
5220 >                    Node<K,V> p;
5221 >                    if ((p = advance()) == null) {
5222                          propagateCompletion();
5223                          break;
5224                      }
5225 <                    if ((u = searchFunction.apply(k)) != null) {
5225 >                    if ((u = searchFunction.apply(p.key)) != null) {
5226                          if (result.compareAndSet(null, u))
5227                              quietlyCompleteRoot();
5228                          break;
# Line 5921 | Line 5232 | public class ConcurrentHashMap<K,V>
5232          }
5233      }
5234  
5235 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5236 <        extends Traverser<K,V,U> {
5235 >    @SuppressWarnings("serial")
5236 >    static final class SearchValuesTask<K,V,U>
5237 >        extends BulkTask<K,V,U> {
5238          final Function<? super V, ? extends U> searchFunction;
5239          final AtomicReference<U> result;
5240          SearchValuesTask
5241 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5241 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5242               Function<? super V, ? extends U> searchFunction,
5243               AtomicReference<U> result) {
5244 <            super(m, p, b);
5244 >            super(p, b, i, f, t);
5245              this.searchFunction = searchFunction; this.result = result;
5246          }
5247          public final U getRawResult() { return result.get(); }
# Line 5938 | Line 5250 | public class ConcurrentHashMap<K,V>
5250              final AtomicReference<U> result;
5251              if ((searchFunction = this.searchFunction) != null &&
5252                  (result = this.result) != null) {
5253 <                for (int b;;) {
5253 >                for (int i = baseIndex, f, h; batch > 0 &&
5254 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5255                      if (result.get() != null)
5256                          return;
5257 <                    if ((b = preSplit()) <= 0)
5945 <                        break;
5257 >                    addToPendingCount(1);
5258                      new SearchValuesTask<K,V,U>
5259 <                        (map, this, b, searchFunction, result).fork();
5259 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5260 >                         searchFunction, result).fork();
5261                  }
5262                  while (result.get() == null) {
5263 <                    V v; U u;
5264 <                    if ((v = advanceValue()) == null) {
5263 >                    U u;
5264 >                    Node<K,V> p;
5265 >                    if ((p = advance()) == null) {
5266                          propagateCompletion();
5267                          break;
5268                      }
5269 <                    if ((u = searchFunction.apply(v)) != null) {
5269 >                    if ((u = searchFunction.apply(p.val)) != null) {
5270                          if (result.compareAndSet(null, u))
5271                              quietlyCompleteRoot();
5272                          break;
# Line 5962 | Line 5276 | public class ConcurrentHashMap<K,V>
5276          }
5277      }
5278  
5279 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5280 <        extends Traverser<K,V,U> {
5279 >    @SuppressWarnings("serial")
5280 >    static final class SearchEntriesTask<K,V,U>
5281 >        extends BulkTask<K,V,U> {
5282          final Function<Entry<K,V>, ? extends U> searchFunction;
5283          final AtomicReference<U> result;
5284          SearchEntriesTask
5285 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5285 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5286               Function<Entry<K,V>, ? extends U> searchFunction,
5287               AtomicReference<U> result) {
5288 <            super(m, p, b);
5288 >            super(p, b, i, f, t);
5289              this.searchFunction = searchFunction; this.result = result;
5290          }
5291          public final U getRawResult() { return result.get(); }
# Line 5979 | Line 5294 | public class ConcurrentHashMap<K,V>
5294              final AtomicReference<U> result;
5295              if ((searchFunction = this.searchFunction) != null &&
5296                  (result = this.result) != null) {
5297 <                for (int b;;) {
5297 >                for (int i = baseIndex, f, h; batch > 0 &&
5298 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5299                      if (result.get() != null)
5300                          return;
5301 <                    if ((b = preSplit()) <= 0)
5986 <                        break;
5301 >                    addToPendingCount(1);
5302                      new SearchEntriesTask<K,V,U>
5303 <                        (map, this, b, searchFunction, result).fork();
5303 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5304 >                         searchFunction, result).fork();
5305                  }
5306                  while (result.get() == null) {
5307 <                    V v; U u;
5308 <                    if ((v = advanceValue()) == null) {
5307 >                    U u;
5308 >                    Node<K,V> p;
5309 >                    if ((p = advance()) == null) {
5310                          propagateCompletion();
5311                          break;
5312                      }
5313 <                    if ((u = searchFunction.apply(entryFor(nextKey,
5997 <                                                           v))) != null) {
5313 >                    if ((u = searchFunction.apply(p)) != null) {
5314                          if (result.compareAndSet(null, u))
5315                              quietlyCompleteRoot();
5316                          return;
# Line 6004 | Line 5320 | public class ConcurrentHashMap<K,V>
5320          }
5321      }
5322  
5323 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5324 <        extends Traverser<K,V,U> {
5323 >    @SuppressWarnings("serial")
5324 >    static final class SearchMappingsTask<K,V,U>
5325 >        extends BulkTask<K,V,U> {
5326          final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5327          final AtomicReference<U> result;
5328          SearchMappingsTask
5329 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5329 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5330               BiFunction<? super K, ? super V, ? extends U> searchFunction,
5331               AtomicReference<U> result) {
5332 <            super(m, p, b);
5332 >            super(p, b, i, f, t);
5333              this.searchFunction = searchFunction; this.result = result;
5334          }
5335          public final U getRawResult() { return result.get(); }
# Line 6021 | Line 5338 | public class ConcurrentHashMap<K,V>
5338              final AtomicReference<U> result;
5339              if ((searchFunction = this.searchFunction) != null &&
5340                  (result = this.result) != null) {
5341 <                for (int b;;) {
5341 >                for (int i = baseIndex, f, h; batch > 0 &&
5342 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5343                      if (result.get() != null)
5344                          return;
5345 <                    if ((b = preSplit()) <= 0)
6028 <                        break;
5345 >                    addToPendingCount(1);
5346                      new SearchMappingsTask<K,V,U>
5347 <                        (map, this, b, searchFunction, result).fork();
5347 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5348 >                         searchFunction, result).fork();
5349                  }
5350                  while (result.get() == null) {
5351 <                    V v; U u;
5352 <                    if ((v = advanceValue()) == null) {
5351 >                    U u;
5352 >                    Node<K,V> p;
5353 >                    if ((p = advance()) == null) {
5354                          propagateCompletion();
5355                          break;
5356                      }
5357 <                    if ((u = searchFunction.apply(nextKey, v)) != null) {
5357 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5358                          if (result.compareAndSet(null, u))
5359                              quietlyCompleteRoot();
5360                          break;
# Line 6045 | Line 5364 | public class ConcurrentHashMap<K,V>
5364          }
5365      }
5366  
5367 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5368 <        extends Traverser<K,V,K> {
5367 >    @SuppressWarnings("serial")
5368 >    static final class ReduceKeysTask<K,V>
5369 >        extends BulkTask<K,V,K> {
5370          final BiFunction<? super K, ? super K, ? extends K> reducer;
5371          K result;
5372          ReduceKeysTask<K,V> rights, nextRight;
5373          ReduceKeysTask
5374 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5374 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5375               ReduceKeysTask<K,V> nextRight,
5376               BiFunction<? super K, ? super K, ? extends K> reducer) {
5377 <            super(m, p, b); this.nextRight = nextRight;
5377 >            super(p, b, i, f, t); this.nextRight = nextRight;
5378              this.reducer = reducer;
5379          }
5380          public final K getRawResult() { return result; }
5381 <        @SuppressWarnings("unchecked") public final void compute() {
5381 >        public final void compute() {
5382              final BiFunction<? super K, ? super K, ? extends K> reducer;
5383              if ((reducer = this.reducer) != null) {
5384 <                for (int b; (b = preSplit()) > 0;)
5384 >                for (int i = baseIndex, f, h; batch > 0 &&
5385 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5386 >                    addToPendingCount(1);
5387                      (rights = new ReduceKeysTask<K,V>
5388 <                     (map, this, b, rights, reducer)).fork();
5389 <                K u, r = null;
5390 <                while ((u = advanceKey()) != null) {
5388 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5389 >                      rights, reducer)).fork();
5390 >                }
5391 >                K r = null;
5392 >                for (Node<K,V> p; (p = advance()) != null; ) {
5393 >                    K u = p.key;
5394                      r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5395                  }
5396                  result = r;
5397                  CountedCompleter<?> c;
5398                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5399 +                    @SuppressWarnings("unchecked")
5400                      ReduceKeysTask<K,V>
5401                          t = (ReduceKeysTask<K,V>)c,
5402                          s = t.rights;
# Line 6086 | Line 5412 | public class ConcurrentHashMap<K,V>
5412          }
5413      }
5414  
5415 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5416 <        extends Traverser<K,V,V> {
5415 >    @SuppressWarnings("serial")
5416 >    static final class ReduceValuesTask<K,V>
5417 >        extends BulkTask<K,V,V> {
5418          final BiFunction<? super V, ? super V, ? extends V> reducer;
5419          V result;
5420          ReduceValuesTask<K,V> rights, nextRight;
5421          ReduceValuesTask
5422 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5422 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5423               ReduceValuesTask<K,V> nextRight,
5424               BiFunction<? super V, ? super V, ? extends V> reducer) {
5425 <            super(m, p, b); this.nextRight = nextRight;
5425 >            super(p, b, i, f, t); this.nextRight = nextRight;
5426              this.reducer = reducer;
5427          }
5428          public final V getRawResult() { return result; }
5429 <        @SuppressWarnings("unchecked") public final void compute() {
5429 >        public final void compute() {
5430              final BiFunction<? super V, ? super V, ? extends V> reducer;
5431              if ((reducer = this.reducer) != null) {
5432 <                for (int b; (b = preSplit()) > 0;)
5432 >                for (int i = baseIndex, f, h; batch > 0 &&
5433 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5434 >                    addToPendingCount(1);
5435                      (rights = new ReduceValuesTask<K,V>
5436 <                     (map, this, b, rights, reducer)).fork();
5437 <                V r = null, v;
5438 <                while ((v = advanceValue()) != null)
5436 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5437 >                      rights, reducer)).fork();
5438 >                }
5439 >                V r = null;
5440 >                for (Node<K,V> p; (p = advance()) != null; ) {
5441 >                    V v = p.val;
5442                      r = (r == null) ? v : reducer.apply(r, v);
5443 +                }
5444                  result = r;
5445                  CountedCompleter<?> c;
5446                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5447 +                    @SuppressWarnings("unchecked")
5448                      ReduceValuesTask<K,V>
5449                          t = (ReduceValuesTask<K,V>)c,
5450                          s = t.rights;
# Line 6126 | Line 5460 | public class ConcurrentHashMap<K,V>
5460          }
5461      }
5462  
5463 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5464 <        extends Traverser<K,V,Map.Entry<K,V>> {
5463 >    @SuppressWarnings("serial")
5464 >    static final class ReduceEntriesTask<K,V>
5465 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5466          final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5467          Map.Entry<K,V> result;
5468          ReduceEntriesTask<K,V> rights, nextRight;
5469          ReduceEntriesTask
5470 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5470 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5471               ReduceEntriesTask<K,V> nextRight,
5472               BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5473 <            super(m, p, b); this.nextRight = nextRight;
5473 >            super(p, b, i, f, t); this.nextRight = nextRight;
5474              this.reducer = reducer;
5475          }
5476          public final Map.Entry<K,V> getRawResult() { return result; }
5477 <        @SuppressWarnings("unchecked") public final void compute() {
5477 >        public final void compute() {
5478              final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5479              if ((reducer = this.reducer) != null) {
5480 <                for (int b; (b = preSplit()) > 0;)
5480 >                for (int i = baseIndex, f, h; batch > 0 &&
5481 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5482 >                    addToPendingCount(1);
5483                      (rights = new ReduceEntriesTask<K,V>
5484 <                     (map, this, b, rights, reducer)).fork();
5485 <                Map.Entry<K,V> r = null;
6149 <                V v;
6150 <                while ((v = advanceValue()) != null) {
6151 <                    Map.Entry<K,V> u = entryFor(nextKey, v);
6152 <                    r = (r == null) ? u : reducer.apply(r, u);
5484 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5485 >                      rights, reducer)).fork();
5486                  }
5487 +                Map.Entry<K,V> r = null;
5488 +                for (Node<K,V> p; (p = advance()) != null; )
5489 +                    r = (r == null) ? p : reducer.apply(r, p);
5490                  result = r;
5491                  CountedCompleter<?> c;
5492                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5493 +                    @SuppressWarnings("unchecked")
5494                      ReduceEntriesTask<K,V>
5495                          t = (ReduceEntriesTask<K,V>)c,
5496                          s = t.rights;
# Line 6169 | Line 5506 | public class ConcurrentHashMap<K,V>
5506          }
5507      }
5508  
5509 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5510 <        extends Traverser<K,V,U> {
5509 >    @SuppressWarnings("serial")
5510 >    static final class MapReduceKeysTask<K,V,U>
5511 >        extends BulkTask<K,V,U> {
5512          final Function<? super K, ? extends U> transformer;
5513          final BiFunction<? super U, ? super U, ? extends U> reducer;
5514          U result;
5515          MapReduceKeysTask<K,V,U> rights, nextRight;
5516          MapReduceKeysTask
5517 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5517 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5518               MapReduceKeysTask<K,V,U> nextRight,
5519               Function<? super K, ? extends U> transformer,
5520               BiFunction<? super U, ? super U, ? extends U> reducer) {
5521 <            super(m, p, b); this.nextRight = nextRight;
5521 >            super(p, b, i, f, t); this.nextRight = nextRight;
5522              this.transformer = transformer;
5523              this.reducer = reducer;
5524          }
5525          public final U getRawResult() { return result; }
5526 <        @SuppressWarnings("unchecked") public final void compute() {
5526 >        public final void compute() {
5527              final Function<? super K, ? extends U> transformer;
5528              final BiFunction<? super U, ? super U, ? extends U> reducer;
5529              if ((transformer = this.transformer) != null &&
5530                  (reducer = this.reducer) != null) {
5531 <                for (int b; (b = preSplit()) > 0;)
5531 >                for (int i = baseIndex, f, h; batch > 0 &&
5532 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5533 >                    addToPendingCount(1);
5534                      (rights = new MapReduceKeysTask<K,V,U>
5535 <                     (map, this, b, rights, transformer, reducer)).fork();
5536 <                K k; U r = null, u;
5537 <                while ((k = advanceKey()) != null) {
5538 <                    if ((u = transformer.apply(k)) != null)
5535 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5536 >                      rights, transformer, reducer)).fork();
5537 >                }
5538 >                U r = null;
5539 >                for (Node<K,V> p; (p = advance()) != null; ) {
5540 >                    U u;
5541 >                    if ((u = transformer.apply(p.key)) != null)
5542                          r = (r == null) ? u : reducer.apply(r, u);
5543                  }
5544                  result = r;
5545                  CountedCompleter<?> c;
5546                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5547 +                    @SuppressWarnings("unchecked")
5548                      MapReduceKeysTask<K,V,U>
5549                          t = (MapReduceKeysTask<K,V,U>)c,
5550                          s = t.rights;
# Line 6216 | Line 5560 | public class ConcurrentHashMap<K,V>
5560          }
5561      }
5562  
5563 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5564 <        extends Traverser<K,V,U> {
5563 >    @SuppressWarnings("serial")
5564 >    static final class MapReduceValuesTask<K,V,U>
5565 >        extends BulkTask<K,V,U> {
5566          final Function<? super V, ? extends U> transformer;
5567          final BiFunction<? super U, ? super U, ? extends U> reducer;
5568          U result;
5569          MapReduceValuesTask<K,V,U> rights, nextRight;
5570          MapReduceValuesTask
5571 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5571 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5572               MapReduceValuesTask<K,V,U> nextRight,
5573               Function<? super V, ? extends U> transformer,
5574               BiFunction<? super U, ? super U, ? extends U> reducer) {
5575 <            super(m, p, b); this.nextRight = nextRight;
5575 >            super(p, b, i, f, t); this.nextRight = nextRight;
5576              this.transformer = transformer;
5577              this.reducer = reducer;
5578          }
5579          public final U getRawResult() { return result; }
5580 <        @SuppressWarnings("unchecked") public final void compute() {
5580 >        public final void compute() {
5581              final Function<? super V, ? extends U> transformer;
5582              final BiFunction<? super U, ? super U, ? extends U> reducer;
5583              if ((transformer = this.transformer) != null &&
5584                  (reducer = this.reducer) != null) {
5585 <                for (int b; (b = preSplit()) > 0;)
5585 >                for (int i = baseIndex, f, h; batch > 0 &&
5586 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5587 >                    addToPendingCount(1);
5588                      (rights = new MapReduceValuesTask<K,V,U>
5589 <                     (map, this, b, rights, transformer, reducer)).fork();
5590 <                U r = null, u;
5591 <                V v;
5592 <                while ((v = advanceValue()) != null) {
5593 <                    if ((u = transformer.apply(v)) != null)
5589 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5590 >                      rights, transformer, reducer)).fork();
5591 >                }
5592 >                U r = null;
5593 >                for (Node<K,V> p; (p = advance()) != null; ) {
5594 >                    U u;
5595 >                    if ((u = transformer.apply(p.val)) != null)
5596                          r = (r == null) ? u : reducer.apply(r, u);
5597                  }
5598                  result = r;
5599                  CountedCompleter<?> c;
5600                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5601 +                    @SuppressWarnings("unchecked")
5602                      MapReduceValuesTask<K,V,U>
5603                          t = (MapReduceValuesTask<K,V,U>)c,
5604                          s = t.rights;
# Line 6264 | Line 5614 | public class ConcurrentHashMap<K,V>
5614          }
5615      }
5616  
5617 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5618 <        extends Traverser<K,V,U> {
5617 >    @SuppressWarnings("serial")
5618 >    static final class MapReduceEntriesTask<K,V,U>
5619 >        extends BulkTask<K,V,U> {
5620          final Function<Map.Entry<K,V>, ? extends U> transformer;
5621          final BiFunction<? super U, ? super U, ? extends U> reducer;
5622          U result;
5623          MapReduceEntriesTask<K,V,U> rights, nextRight;
5624          MapReduceEntriesTask
5625 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5625 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5626               MapReduceEntriesTask<K,V,U> nextRight,
5627               Function<Map.Entry<K,V>, ? extends U> transformer,
5628               BiFunction<? super U, ? super U, ? extends U> reducer) {
5629 <            super(m, p, b); this.nextRight = nextRight;
5629 >            super(p, b, i, f, t); this.nextRight = nextRight;
5630              this.transformer = transformer;
5631              this.reducer = reducer;
5632          }
5633          public final U getRawResult() { return result; }
5634 <        @SuppressWarnings("unchecked") public final void compute() {
5634 >        public final void compute() {
5635              final Function<Map.Entry<K,V>, ? extends U> transformer;
5636              final BiFunction<? super U, ? super U, ? extends U> reducer;
5637              if ((transformer = this.transformer) != null &&
5638                  (reducer = this.reducer) != null) {
5639 <                for (int b; (b = preSplit()) > 0;)
5639 >                for (int i = baseIndex, f, h; batch > 0 &&
5640 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5641 >                    addToPendingCount(1);
5642                      (rights = new MapReduceEntriesTask<K,V,U>
5643 <                     (map, this, b, rights, transformer, reducer)).fork();
5644 <                U r = null, u;
5645 <                V v;
5646 <                while ((v = advanceValue()) != null) {
5647 <                    if ((u = transformer.apply(entryFor(nextKey,
5648 <                                                        v))) != null)
5643 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5644 >                      rights, transformer, reducer)).fork();
5645 >                }
5646 >                U r = null;
5647 >                for (Node<K,V> p; (p = advance()) != null; ) {
5648 >                    U u;
5649 >                    if ((u = transformer.apply(p)) != null)
5650                          r = (r == null) ? u : reducer.apply(r, u);
5651                  }
5652                  result = r;
5653                  CountedCompleter<?> c;
5654                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5655 +                    @SuppressWarnings("unchecked")
5656                      MapReduceEntriesTask<K,V,U>
5657                          t = (MapReduceEntriesTask<K,V,U>)c,
5658                          s = t.rights;
# Line 6313 | Line 5668 | public class ConcurrentHashMap<K,V>
5668          }
5669      }
5670  
5671 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5672 <        extends Traverser<K,V,U> {
5671 >    @SuppressWarnings("serial")
5672 >    static final class MapReduceMappingsTask<K,V,U>
5673 >        extends BulkTask<K,V,U> {
5674          final BiFunction<? super K, ? super V, ? extends U> transformer;
5675          final BiFunction<? super U, ? super U, ? extends U> reducer;
5676          U result;
5677          MapReduceMappingsTask<K,V,U> rights, nextRight;
5678          MapReduceMappingsTask
5679 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5679 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5680               MapReduceMappingsTask<K,V,U> nextRight,
5681               BiFunction<? super K, ? super V, ? extends U> transformer,
5682               BiFunction<? super U, ? super U, ? extends U> reducer) {
5683 <            super(m, p, b); this.nextRight = nextRight;
5683 >            super(p, b, i, f, t); this.nextRight = nextRight;
5684              this.transformer = transformer;
5685              this.reducer = reducer;
5686          }
5687          public final U getRawResult() { return result; }
5688 <        @SuppressWarnings("unchecked") public final void compute() {
5688 >        public final void compute() {
5689              final BiFunction<? super K, ? super V, ? extends U> transformer;
5690              final BiFunction<? super U, ? super U, ? extends U> reducer;
5691              if ((transformer = this.transformer) != null &&
5692                  (reducer = this.reducer) != null) {
5693 <                for (int b; (b = preSplit()) > 0;)
5693 >                for (int i = baseIndex, f, h; batch > 0 &&
5694 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5695 >                    addToPendingCount(1);
5696                      (rights = new MapReduceMappingsTask<K,V,U>
5697 <                     (map, this, b, rights, transformer, reducer)).fork();
5698 <                U r = null, u;
5699 <                V v;
5700 <                while ((v = advanceValue()) != null) {
5701 <                    if ((u = transformer.apply(nextKey, v)) != null)
5697 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5698 >                      rights, transformer, reducer)).fork();
5699 >                }
5700 >                U r = null;
5701 >                for (Node<K,V> p; (p = advance()) != null; ) {
5702 >                    U u;
5703 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5704                          r = (r == null) ? u : reducer.apply(r, u);
5705                  }
5706                  result = r;
5707                  CountedCompleter<?> c;
5708                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5709 +                    @SuppressWarnings("unchecked")
5710                      MapReduceMappingsTask<K,V,U>
5711                          t = (MapReduceMappingsTask<K,V,U>)c,
5712                          s = t.rights;
# Line 6361 | Line 5722 | public class ConcurrentHashMap<K,V>
5722          }
5723      }
5724  
5725 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5726 <        extends Traverser<K,V,Double> {
5725 >    @SuppressWarnings("serial")
5726 >    static final class MapReduceKeysToDoubleTask<K,V>
5727 >        extends BulkTask<K,V,Double> {
5728          final ToDoubleFunction<? super K> transformer;
5729          final DoubleBinaryOperator reducer;
5730          final double basis;
5731          double result;
5732          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5733          MapReduceKeysToDoubleTask
5734 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5734 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5735               MapReduceKeysToDoubleTask<K,V> nextRight,
5736               ToDoubleFunction<? super K> transformer,
5737               double basis,
5738               DoubleBinaryOperator reducer) {
5739 <            super(m, p, b); this.nextRight = nextRight;
5739 >            super(p, b, i, f, t); this.nextRight = nextRight;
5740              this.transformer = transformer;
5741              this.basis = basis; this.reducer = reducer;
5742          }
5743          public final Double getRawResult() { return result; }
5744 <        @SuppressWarnings("unchecked") public final void compute() {
5744 >        public final void compute() {
5745              final ToDoubleFunction<? super K> transformer;
5746              final DoubleBinaryOperator reducer;
5747              if ((transformer = this.transformer) != null &&
5748                  (reducer = this.reducer) != null) {
5749                  double r = this.basis;
5750 <                for (int b; (b = preSplit()) > 0;)
5750 >                for (int i = baseIndex, f, h; batch > 0 &&
5751 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5752 >                    addToPendingCount(1);
5753                      (rights = new MapReduceKeysToDoubleTask<K,V>
5754 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5755 <                K k;
5756 <                while ((k = advanceKey()) != null)
5757 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(k));
5754 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5755 >                      rights, transformer, r, reducer)).fork();
5756 >                }
5757 >                for (Node<K,V> p; (p = advance()) != null; )
5758 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5759                  result = r;
5760                  CountedCompleter<?> c;
5761                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5762 +                    @SuppressWarnings("unchecked")
5763                      MapReduceKeysToDoubleTask<K,V>
5764                          t = (MapReduceKeysToDoubleTask<K,V>)c,
5765                          s = t.rights;
# Line 6406 | Line 5772 | public class ConcurrentHashMap<K,V>
5772          }
5773      }
5774  
5775 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5776 <        extends Traverser<K,V,Double> {
5775 >    @SuppressWarnings("serial")
5776 >    static final class MapReduceValuesToDoubleTask<K,V>
5777 >        extends BulkTask<K,V,Double> {
5778          final ToDoubleFunction<? super V> transformer;
5779          final DoubleBinaryOperator reducer;
5780          final double basis;
5781          double result;
5782          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5783          MapReduceValuesToDoubleTask
5784 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5784 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5785               MapReduceValuesToDoubleTask<K,V> nextRight,
5786               ToDoubleFunction<? super V> transformer,
5787               double basis,
5788               DoubleBinaryOperator reducer) {
5789 <            super(m, p, b); this.nextRight = nextRight;
5789 >            super(p, b, i, f, t); this.nextRight = nextRight;
5790              this.transformer = transformer;
5791              this.basis = basis; this.reducer = reducer;
5792          }
5793          public final Double getRawResult() { return result; }
5794 <        @SuppressWarnings("unchecked") public final void compute() {
5794 >        public final void compute() {
5795              final ToDoubleFunction<? super V> transformer;
5796              final DoubleBinaryOperator reducer;
5797              if ((transformer = this.transformer) != null &&
5798                  (reducer = this.reducer) != null) {
5799                  double r = this.basis;
5800 <                for (int b; (b = preSplit()) > 0;)
5800 >                for (int i = baseIndex, f, h; batch > 0 &&
5801 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5802 >                    addToPendingCount(1);
5803                      (rights = new MapReduceValuesToDoubleTask<K,V>
5804 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5805 <                V v;
5806 <                while ((v = advanceValue()) != null)
5807 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
5804 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5805 >                      rights, transformer, r, reducer)).fork();
5806 >                }
5807 >                for (Node<K,V> p; (p = advance()) != null; )
5808 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5809                  result = r;
5810                  CountedCompleter<?> c;
5811                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5812 +                    @SuppressWarnings("unchecked")
5813                      MapReduceValuesToDoubleTask<K,V>
5814                          t = (MapReduceValuesToDoubleTask<K,V>)c,
5815                          s = t.rights;
# Line 6451 | Line 5822 | public class ConcurrentHashMap<K,V>
5822          }
5823      }
5824  
5825 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5826 <        extends Traverser<K,V,Double> {
5825 >    @SuppressWarnings("serial")
5826 >    static final class MapReduceEntriesToDoubleTask<K,V>
5827 >        extends BulkTask<K,V,Double> {
5828          final ToDoubleFunction<Map.Entry<K,V>> transformer;
5829          final DoubleBinaryOperator reducer;
5830          final double basis;
5831          double result;
5832          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5833          MapReduceEntriesToDoubleTask
5834 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5834 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5835               MapReduceEntriesToDoubleTask<K,V> nextRight,
5836               ToDoubleFunction<Map.Entry<K,V>> transformer,
5837               double basis,
5838               DoubleBinaryOperator reducer) {
5839 <            super(m, p, b); this.nextRight = nextRight;
5839 >            super(p, b, i, f, t); this.nextRight = nextRight;
5840              this.transformer = transformer;
5841              this.basis = basis; this.reducer = reducer;
5842          }
5843          public final Double getRawResult() { return result; }
5844 <        @SuppressWarnings("unchecked") public final void compute() {
5844 >        public final void compute() {
5845              final ToDoubleFunction<Map.Entry<K,V>> transformer;
5846              final DoubleBinaryOperator reducer;
5847              if ((transformer = this.transformer) != null &&
5848                  (reducer = this.reducer) != null) {
5849                  double r = this.basis;
5850 <                for (int b; (b = preSplit()) > 0;)
5850 >                for (int i = baseIndex, f, h; batch > 0 &&
5851 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5852 >                    addToPendingCount(1);
5853                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5854 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5855 <                V v;
5856 <                while ((v = advanceValue()) != null)
5857 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(nextKey,
5858 <                                                                    v)));
5854 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5855 >                      rights, transformer, r, reducer)).fork();
5856 >                }
5857 >                for (Node<K,V> p; (p = advance()) != null; )
5858 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5859                  result = r;
5860                  CountedCompleter<?> c;
5861                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5862 +                    @SuppressWarnings("unchecked")
5863                      MapReduceEntriesToDoubleTask<K,V>
5864                          t = (MapReduceEntriesToDoubleTask<K,V>)c,
5865                          s = t.rights;
# Line 6497 | Line 5872 | public class ConcurrentHashMap<K,V>
5872          }
5873      }
5874  
5875 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5876 <        extends Traverser<K,V,Double> {
5875 >    @SuppressWarnings("serial")
5876 >    static final class MapReduceMappingsToDoubleTask<K,V>
5877 >        extends BulkTask<K,V,Double> {
5878          final ToDoubleBiFunction<? super K, ? super V> transformer;
5879          final DoubleBinaryOperator reducer;
5880          final double basis;
5881          double result;
5882          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5883          MapReduceMappingsToDoubleTask
5884 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5884 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5885               MapReduceMappingsToDoubleTask<K,V> nextRight,
5886               ToDoubleBiFunction<? super K, ? super V> transformer,
5887               double basis,
5888               DoubleBinaryOperator reducer) {
5889 <            super(m, p, b); this.nextRight = nextRight;
5889 >            super(p, b, i, f, t); this.nextRight = nextRight;
5890              this.transformer = transformer;
5891              this.basis = basis; this.reducer = reducer;
5892          }
5893          public final Double getRawResult() { return result; }
5894 <        @SuppressWarnings("unchecked") public final void compute() {
5894 >        public final void compute() {
5895              final ToDoubleBiFunction<? super K, ? super V> transformer;
5896              final DoubleBinaryOperator reducer;
5897              if ((transformer = this.transformer) != null &&
5898                  (reducer = this.reducer) != null) {
5899                  double r = this.basis;
5900 <                for (int b; (b = preSplit()) > 0;)
5900 >                for (int i = baseIndex, f, h; batch > 0 &&
5901 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5902 >                    addToPendingCount(1);
5903                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5904 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5905 <                V v;
5906 <                while ((v = advanceValue()) != null)
5907 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey, v));
5904 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5905 >                      rights, transformer, r, reducer)).fork();
5906 >                }
5907 >                for (Node<K,V> p; (p = advance()) != null; )
5908 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5909                  result = r;
5910                  CountedCompleter<?> c;
5911                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5912 +                    @SuppressWarnings("unchecked")
5913                      MapReduceMappingsToDoubleTask<K,V>
5914                          t = (MapReduceMappingsToDoubleTask<K,V>)c,
5915                          s = t.rights;
# Line 6542 | Line 5922 | public class ConcurrentHashMap<K,V>
5922          }
5923      }
5924  
5925 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5926 <        extends Traverser<K,V,Long> {
5925 >    @SuppressWarnings("serial")
5926 >    static final class MapReduceKeysToLongTask<K,V>
5927 >        extends BulkTask<K,V,Long> {
5928          final ToLongFunction<? super K> transformer;
5929          final LongBinaryOperator reducer;
5930          final long basis;
5931          long result;
5932          MapReduceKeysToLongTask<K,V> rights, nextRight;
5933          MapReduceKeysToLongTask
5934 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5934 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5935               MapReduceKeysToLongTask<K,V> nextRight,
5936               ToLongFunction<? super K> transformer,
5937               long basis,
5938               LongBinaryOperator reducer) {
5939 <            super(m, p, b); this.nextRight = nextRight;
5939 >            super(p, b, i, f, t); this.nextRight = nextRight;
5940              this.transformer = transformer;
5941              this.basis = basis; this.reducer = reducer;
5942          }
5943          public final Long getRawResult() { return result; }
5944 <        @SuppressWarnings("unchecked") public final void compute() {
5944 >        public final void compute() {
5945              final ToLongFunction<? super K> transformer;
5946              final LongBinaryOperator reducer;
5947              if ((transformer = this.transformer) != null &&
5948                  (reducer = this.reducer) != null) {
5949                  long r = this.basis;
5950 <                for (int b; (b = preSplit()) > 0;)
5950 >                for (int i = baseIndex, f, h; batch > 0 &&
5951 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5952 >                    addToPendingCount(1);
5953                      (rights = new MapReduceKeysToLongTask<K,V>
5954 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5955 <                K k;
5956 <                while ((k = advanceKey()) != null)
5957 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(k));
5954 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5955 >                      rights, transformer, r, reducer)).fork();
5956 >                }
5957 >                for (Node<K,V> p; (p = advance()) != null; )
5958 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5959                  result = r;
5960                  CountedCompleter<?> c;
5961                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5962 +                    @SuppressWarnings("unchecked")
5963                      MapReduceKeysToLongTask<K,V>
5964                          t = (MapReduceKeysToLongTask<K,V>)c,
5965                          s = t.rights;
# Line 6587 | Line 5972 | public class ConcurrentHashMap<K,V>
5972          }
5973      }
5974  
5975 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5976 <        extends Traverser<K,V,Long> {
5975 >    @SuppressWarnings("serial")
5976 >    static final class MapReduceValuesToLongTask<K,V>
5977 >        extends BulkTask<K,V,Long> {
5978          final ToLongFunction<? super V> transformer;
5979          final LongBinaryOperator reducer;
5980          final long basis;
5981          long result;
5982          MapReduceValuesToLongTask<K,V> rights, nextRight;
5983          MapReduceValuesToLongTask
5984 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5984 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5985               MapReduceValuesToLongTask<K,V> nextRight,
5986               ToLongFunction<? super V> transformer,
5987               long basis,
5988               LongBinaryOperator reducer) {
5989 <            super(m, p, b); this.nextRight = nextRight;
5989 >            super(p, b, i, f, t); this.nextRight = nextRight;
5990              this.transformer = transformer;
5991              this.basis = basis; this.reducer = reducer;
5992          }
5993          public final Long getRawResult() { return result; }
5994 <        @SuppressWarnings("unchecked") public final void compute() {
5994 >        public final void compute() {
5995              final ToLongFunction<? super V> transformer;
5996              final LongBinaryOperator reducer;
5997              if ((transformer = this.transformer) != null &&
5998                  (reducer = this.reducer) != null) {
5999                  long r = this.basis;
6000 <                for (int b; (b = preSplit()) > 0;)
6000 >                for (int i = baseIndex, f, h; batch > 0 &&
6001 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6002 >                    addToPendingCount(1);
6003                      (rights = new MapReduceValuesToLongTask<K,V>
6004 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6005 <                V v;
6006 <                while ((v = advanceValue()) != null)
6007 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(v));
6004 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6005 >                      rights, transformer, r, reducer)).fork();
6006 >                }
6007 >                for (Node<K,V> p; (p = advance()) != null; )
6008 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
6009                  result = r;
6010                  CountedCompleter<?> c;
6011                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6012 +                    @SuppressWarnings("unchecked")
6013                      MapReduceValuesToLongTask<K,V>
6014                          t = (MapReduceValuesToLongTask<K,V>)c,
6015                          s = t.rights;
# Line 6632 | Line 6022 | public class ConcurrentHashMap<K,V>
6022          }
6023      }
6024  
6025 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6026 <        extends Traverser<K,V,Long> {
6025 >    @SuppressWarnings("serial")
6026 >    static final class MapReduceEntriesToLongTask<K,V>
6027 >        extends BulkTask<K,V,Long> {
6028          final ToLongFunction<Map.Entry<K,V>> transformer;
6029          final LongBinaryOperator reducer;
6030          final long basis;
6031          long result;
6032          MapReduceEntriesToLongTask<K,V> rights, nextRight;
6033          MapReduceEntriesToLongTask
6034 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6034 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6035               MapReduceEntriesToLongTask<K,V> nextRight,
6036               ToLongFunction<Map.Entry<K,V>> transformer,
6037               long basis,
6038               LongBinaryOperator reducer) {
6039 <            super(m, p, b); this.nextRight = nextRight;
6039 >            super(p, b, i, f, t); this.nextRight = nextRight;
6040              this.transformer = transformer;
6041              this.basis = basis; this.reducer = reducer;
6042          }
6043          public final Long getRawResult() { return result; }
6044 <        @SuppressWarnings("unchecked") public final void compute() {
6044 >        public final void compute() {
6045              final ToLongFunction<Map.Entry<K,V>> transformer;
6046              final LongBinaryOperator reducer;
6047              if ((transformer = this.transformer) != null &&
6048                  (reducer = this.reducer) != null) {
6049                  long r = this.basis;
6050 <                for (int b; (b = preSplit()) > 0;)
6050 >                for (int i = baseIndex, f, h; batch > 0 &&
6051 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6052 >                    addToPendingCount(1);
6053                      (rights = new MapReduceEntriesToLongTask<K,V>
6054 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6055 <                V v;
6056 <                while ((v = advanceValue()) != null)
6057 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(nextKey, v)));
6054 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6055 >                      rights, transformer, r, reducer)).fork();
6056 >                }
6057 >                for (Node<K,V> p; (p = advance()) != null; )
6058 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
6059                  result = r;
6060                  CountedCompleter<?> c;
6061                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6062 +                    @SuppressWarnings("unchecked")
6063                      MapReduceEntriesToLongTask<K,V>
6064                          t = (MapReduceEntriesToLongTask<K,V>)c,
6065                          s = t.rights;
# Line 6677 | Line 6072 | public class ConcurrentHashMap<K,V>
6072          }
6073      }
6074  
6075 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6076 <        extends Traverser<K,V,Long> {
6075 >    @SuppressWarnings("serial")
6076 >    static final class MapReduceMappingsToLongTask<K,V>
6077 >        extends BulkTask<K,V,Long> {
6078          final ToLongBiFunction<? super K, ? super V> transformer;
6079          final LongBinaryOperator reducer;
6080          final long basis;
6081          long result;
6082          MapReduceMappingsToLongTask<K,V> rights, nextRight;
6083          MapReduceMappingsToLongTask
6084 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6084 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6085               MapReduceMappingsToLongTask<K,V> nextRight,
6086               ToLongBiFunction<? super K, ? super V> transformer,
6087               long basis,
6088               LongBinaryOperator reducer) {
6089 <            super(m, p, b); this.nextRight = nextRight;
6089 >            super(p, b, i, f, t); this.nextRight = nextRight;
6090              this.transformer = transformer;
6091              this.basis = basis; this.reducer = reducer;
6092          }
6093          public final Long getRawResult() { return result; }
6094 <        @SuppressWarnings("unchecked") public final void compute() {
6094 >        public final void compute() {
6095              final ToLongBiFunction<? super K, ? super V> transformer;
6096              final LongBinaryOperator reducer;
6097              if ((transformer = this.transformer) != null &&
6098                  (reducer = this.reducer) != null) {
6099                  long r = this.basis;
6100 <                for (int b; (b = preSplit()) > 0;)
6100 >                for (int i = baseIndex, f, h; batch > 0 &&
6101 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6102 >                    addToPendingCount(1);
6103                      (rights = new MapReduceMappingsToLongTask<K,V>
6104 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6105 <                V v;
6106 <                while ((v = advanceValue()) != null)
6107 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey, v));
6104 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6105 >                      rights, transformer, r, reducer)).fork();
6106 >                }
6107 >                for (Node<K,V> p; (p = advance()) != null; )
6108 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
6109                  result = r;
6110                  CountedCompleter<?> c;
6111                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6112 +                    @SuppressWarnings("unchecked")
6113                      MapReduceMappingsToLongTask<K,V>
6114                          t = (MapReduceMappingsToLongTask<K,V>)c,
6115                          s = t.rights;
# Line 6722 | Line 6122 | public class ConcurrentHashMap<K,V>
6122          }
6123      }
6124  
6125 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6126 <        extends Traverser<K,V,Integer> {
6125 >    @SuppressWarnings("serial")
6126 >    static final class MapReduceKeysToIntTask<K,V>
6127 >        extends BulkTask<K,V,Integer> {
6128          final ToIntFunction<? super K> transformer;
6129          final IntBinaryOperator reducer;
6130          final int basis;
6131          int result;
6132          MapReduceKeysToIntTask<K,V> rights, nextRight;
6133          MapReduceKeysToIntTask
6134 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6134 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6135               MapReduceKeysToIntTask<K,V> nextRight,
6136               ToIntFunction<? super K> transformer,
6137               int basis,
6138               IntBinaryOperator reducer) {
6139 <            super(m, p, b); this.nextRight = nextRight;
6139 >            super(p, b, i, f, t); this.nextRight = nextRight;
6140              this.transformer = transformer;
6141              this.basis = basis; this.reducer = reducer;
6142          }
6143          public final Integer getRawResult() { return result; }
6144 <        @SuppressWarnings("unchecked") public final void compute() {
6144 >        public final void compute() {
6145              final ToIntFunction<? super K> transformer;
6146              final IntBinaryOperator reducer;
6147              if ((transformer = this.transformer) != null &&
6148                  (reducer = this.reducer) != null) {
6149                  int r = this.basis;
6150 <                for (int b; (b = preSplit()) > 0;)
6150 >                for (int i = baseIndex, f, h; batch > 0 &&
6151 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6152 >                    addToPendingCount(1);
6153                      (rights = new MapReduceKeysToIntTask<K,V>
6154 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6155 <                K k;
6156 <                while ((k = advanceKey()) != null)
6157 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(k));
6154 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6155 >                      rights, transformer, r, reducer)).fork();
6156 >                }
6157 >                for (Node<K,V> p; (p = advance()) != null; )
6158 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
6159                  result = r;
6160                  CountedCompleter<?> c;
6161                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6162 +                    @SuppressWarnings("unchecked")
6163                      MapReduceKeysToIntTask<K,V>
6164                          t = (MapReduceKeysToIntTask<K,V>)c,
6165                          s = t.rights;
# Line 6767 | Line 6172 | public class ConcurrentHashMap<K,V>
6172          }
6173      }
6174  
6175 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6176 <        extends Traverser<K,V,Integer> {
6175 >    @SuppressWarnings("serial")
6176 >    static final class MapReduceValuesToIntTask<K,V>
6177 >        extends BulkTask<K,V,Integer> {
6178          final ToIntFunction<? super V> transformer;
6179          final IntBinaryOperator reducer;
6180          final int basis;
6181          int result;
6182          MapReduceValuesToIntTask<K,V> rights, nextRight;
6183          MapReduceValuesToIntTask
6184 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6184 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6185               MapReduceValuesToIntTask<K,V> nextRight,
6186               ToIntFunction<? super V> transformer,
6187               int basis,
6188               IntBinaryOperator reducer) {
6189 <            super(m, p, b); this.nextRight = nextRight;
6189 >            super(p, b, i, f, t); this.nextRight = nextRight;
6190              this.transformer = transformer;
6191              this.basis = basis; this.reducer = reducer;
6192          }
6193          public final Integer getRawResult() { return result; }
6194 <        @SuppressWarnings("unchecked") public final void compute() {
6194 >        public final void compute() {
6195              final ToIntFunction<? super V> transformer;
6196              final IntBinaryOperator reducer;
6197              if ((transformer = this.transformer) != null &&
6198                  (reducer = this.reducer) != null) {
6199                  int r = this.basis;
6200 <                for (int b; (b = preSplit()) > 0;)
6200 >                for (int i = baseIndex, f, h; batch > 0 &&
6201 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6202 >                    addToPendingCount(1);
6203                      (rights = new MapReduceValuesToIntTask<K,V>
6204 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6205 <                V v;
6206 <                while ((v = advanceValue()) != null)
6207 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(v));
6204 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6205 >                      rights, transformer, r, reducer)).fork();
6206 >                }
6207 >                for (Node<K,V> p; (p = advance()) != null; )
6208 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
6209                  result = r;
6210                  CountedCompleter<?> c;
6211                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6212 +                    @SuppressWarnings("unchecked")
6213                      MapReduceValuesToIntTask<K,V>
6214                          t = (MapReduceValuesToIntTask<K,V>)c,
6215                          s = t.rights;
# Line 6812 | Line 6222 | public class ConcurrentHashMap<K,V>
6222          }
6223      }
6224  
6225 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6226 <        extends Traverser<K,V,Integer> {
6225 >    @SuppressWarnings("serial")
6226 >    static final class MapReduceEntriesToIntTask<K,V>
6227 >        extends BulkTask<K,V,Integer> {
6228          final ToIntFunction<Map.Entry<K,V>> transformer;
6229          final IntBinaryOperator reducer;
6230          final int basis;
6231          int result;
6232          MapReduceEntriesToIntTask<K,V> rights, nextRight;
6233          MapReduceEntriesToIntTask
6234 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6234 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6235               MapReduceEntriesToIntTask<K,V> nextRight,
6236               ToIntFunction<Map.Entry<K,V>> transformer,
6237               int basis,
6238               IntBinaryOperator reducer) {
6239 <            super(m, p, b); this.nextRight = nextRight;
6239 >            super(p, b, i, f, t); this.nextRight = nextRight;
6240              this.transformer = transformer;
6241              this.basis = basis; this.reducer = reducer;
6242          }
6243          public final Integer getRawResult() { return result; }
6244 <        @SuppressWarnings("unchecked") public final void compute() {
6244 >        public final void compute() {
6245              final ToIntFunction<Map.Entry<K,V>> transformer;
6246              final IntBinaryOperator reducer;
6247              if ((transformer = this.transformer) != null &&
6248                  (reducer = this.reducer) != null) {
6249                  int r = this.basis;
6250 <                for (int b; (b = preSplit()) > 0;)
6250 >                for (int i = baseIndex, f, h; batch > 0 &&
6251 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6252 >                    addToPendingCount(1);
6253                      (rights = new MapReduceEntriesToIntTask<K,V>
6254 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6255 <                V v;
6256 <                while ((v = advanceValue()) != null)
6257 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(nextKey,
6258 <                                                                    v)));
6254 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6255 >                      rights, transformer, r, reducer)).fork();
6256 >                }
6257 >                for (Node<K,V> p; (p = advance()) != null; )
6258 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
6259                  result = r;
6260                  CountedCompleter<?> c;
6261                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6262 +                    @SuppressWarnings("unchecked")
6263                      MapReduceEntriesToIntTask<K,V>
6264                          t = (MapReduceEntriesToIntTask<K,V>)c,
6265                          s = t.rights;
# Line 6858 | Line 6272 | public class ConcurrentHashMap<K,V>
6272          }
6273      }
6274  
6275 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6276 <        extends Traverser<K,V,Integer> {
6275 >    @SuppressWarnings("serial")
6276 >    static final class MapReduceMappingsToIntTask<K,V>
6277 >        extends BulkTask<K,V,Integer> {
6278          final ToIntBiFunction<? super K, ? super V> transformer;
6279          final IntBinaryOperator reducer;
6280          final int basis;
6281          int result;
6282          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6283          MapReduceMappingsToIntTask
6284 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6284 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6285               MapReduceMappingsToIntTask<K,V> nextRight,
6286               ToIntBiFunction<? super K, ? super V> transformer,
6287               int basis,
6288               IntBinaryOperator reducer) {
6289 <            super(m, p, b); this.nextRight = nextRight;
6289 >            super(p, b, i, f, t); this.nextRight = nextRight;
6290              this.transformer = transformer;
6291              this.basis = basis; this.reducer = reducer;
6292          }
6293          public final Integer getRawResult() { return result; }
6294 <        @SuppressWarnings("unchecked") public final void compute() {
6294 >        public final void compute() {
6295              final ToIntBiFunction<? super K, ? super V> transformer;
6296              final IntBinaryOperator reducer;
6297              if ((transformer = this.transformer) != null &&
6298                  (reducer = this.reducer) != null) {
6299                  int r = this.basis;
6300 <                for (int b; (b = preSplit()) > 0;)
6300 >                for (int i = baseIndex, f, h; batch > 0 &&
6301 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6302 >                    addToPendingCount(1);
6303                      (rights = new MapReduceMappingsToIntTask<K,V>
6304 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6305 <                V v;
6306 <                while ((v = advanceValue()) != null)
6307 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey, v));
6304 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6305 >                      rights, transformer, r, reducer)).fork();
6306 >                }
6307 >                for (Node<K,V> p; (p = advance()) != null; )
6308 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6309                  result = r;
6310                  CountedCompleter<?> c;
6311                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6312 +                    @SuppressWarnings("unchecked")
6313                      MapReduceMappingsToIntTask<K,V>
6314                          t = (MapReduceMappingsToIntTask<K,V>)c,
6315                          s = t.rights;
# Line 6904 | Line 6323 | public class ConcurrentHashMap<K,V>
6323      }
6324  
6325      // Unsafe mechanics
6326 <    private static final sun.misc.Unsafe U;
6327 <    private static final long SIZECTL;
6328 <    private static final long TRANSFERINDEX;
6329 <    private static final long TRANSFERORIGIN;
6330 <    private static final long BASECOUNT;
6331 <    private static final long CELLSBUSY;
6332 <    private static final long CELLVALUE;
6333 <    private static final long ABASE;
6326 >    private static final Unsafe U = Unsafe.getUnsafe();
6327 >    private static final long SIZECTL
6328 >        = U.objectFieldOffset(ConcurrentHashMap.class, "sizeCtl");
6329 >    private static final long TRANSFERINDEX
6330 >        = U.objectFieldOffset(ConcurrentHashMap.class, "transferIndex");
6331 >    private static final long BASECOUNT
6332 >        = U.objectFieldOffset(ConcurrentHashMap.class, "baseCount");
6333 >    private static final long CELLSBUSY
6334 >        = U.objectFieldOffset(ConcurrentHashMap.class, "cellsBusy");
6335 >    private static final long CELLVALUE
6336 >        = U.objectFieldOffset(CounterCell.class, "value");
6337 >    private static final int ABASE = U.arrayBaseOffset(Node[].class);
6338      private static final int ASHIFT;
6339  
6340      static {
6341 <        try {
6342 <            U = sun.misc.Unsafe.getUnsafe();
6343 <            Class<?> k = ConcurrentHashMap.class;
6344 <            SIZECTL = U.objectFieldOffset
6345 <                (k.getDeclaredField("sizeCtl"));
6346 <            TRANSFERINDEX = U.objectFieldOffset
6347 <                (k.getDeclaredField("transferIndex"));
6348 <            TRANSFERORIGIN = U.objectFieldOffset
6926 <                (k.getDeclaredField("transferOrigin"));
6927 <            BASECOUNT = U.objectFieldOffset
6928 <                (k.getDeclaredField("baseCount"));
6929 <            CELLSBUSY = U.objectFieldOffset
6930 <                (k.getDeclaredField("cellsBusy"));
6931 <            Class<?> ck = Cell.class;
6932 <            CELLVALUE = U.objectFieldOffset
6933 <                (ck.getDeclaredField("value"));
6934 <            Class<?> sc = Node[].class;
6935 <            ABASE = U.arrayBaseOffset(sc);
6936 <            int scale = U.arrayIndexScale(sc);
6937 <            if ((scale & (scale - 1)) != 0)
6938 <                throw new Error("data type scale not a power of two");
6939 <            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6940 <        } catch (Exception e) {
6941 <            throw new Error(e);
6942 <        }
6943 <    }
6341 >        int scale = U.arrayIndexScale(Node[].class);
6342 >        if ((scale & (scale - 1)) != 0)
6343 >            throw new ExceptionInInitializerError("array index scale not a power of two");
6344 >        ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6345 >
6346 >        // Reduce the risk of rare disastrous classloading in first call to
6347 >        // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
6348 >        Class<?> ensureLoaded = LockSupport.class;
6349  
6350 +        // Eager class load observed to help JIT during startup
6351 +        ensureLoaded = ReservationNode.class;
6352 +    }
6353   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines