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.150 by jsr166, Fri Dec 14 16:33:42 2012 UTC vs.
Revision 1.318 by jsr166, Sat Aug 10 16:48:05 2019 UTC

# Line 5 | Line 5
5   */
6  
7   package java.util.concurrent;
8 import java.util.concurrent.ForkJoinPool;
9 import java.util.concurrent.CountedCompleter;
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;
13 import java.util.Map;
14 import java.util.Set;
15   import java.util.Collection;
16 < import java.util.AbstractMap;
17 < import java.util.AbstractSet;
18 < import java.util.AbstractCollection;
19 < 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;
23 < 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;
27 < 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 49 | 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 80 | 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 88 | 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
106 < * form of histogram or multiset) by using {@link LongAdder} values
107 < * and initializing via {@link #computeIfAbsent}. For example, to add
108 < * a count to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you
109 < * can use {@code freqs.computeIfAbsent(k -> new
110 < * LongAdder()).increment();}
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(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 102 | 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 parallel operations using the {@link
120 < * ForkJoinPool#commonPool}. (Tasks that may be used in other contexts
121 < * are available in class {@link ForkJoinTasks}). These operations are
122 < * designed to be safely, and often sensibly, applied even with maps
123 < * that are being concurrently updated by other threads; for example,
124 < * when computing a snapshot summary of the values in a shared
125 < * registry.  There are three kinds of operation, each with four
126 < * forms, accepting functions with Keys, Values, Entries, and (Key,
113 < * Value) arguments and/or return values. (The first three forms are
114 < * also available via the {@link #keySet()}, {@link #values()} and
115 < * {@link #entrySet()} views). Because the elements of a
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.
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   *
148 * </li>
160   * </ul>
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 191 | Line 213 | import java.io.Serializable;
213   * exceptions, or would have done so if the first exception had
214   * not occurred.
215   *
216 < * <p>Parallel speedups for bulk operations compared to sequential
217 < * processing are common but not guaranteed.  Operations involving
218 < * brief functions on small maps may execute more slowly than
219 < * sequential loops if the underlying work to parallelize the
220 < * computation is more expensive than the computation itself.
221 < * Similarly, parallelization may not lead to much actual parallelism
222 < * if all processors are busy performing unrelated tasks.
216 > * <p>Speedups for parallel compared to sequential forms are common
217 > * but not guaranteed.  Parallel operations involving brief functions
218 > * on small maps may execute more slowly than sequential forms if the
219 > * underlying work to parallelize the computation is more expensive
220 > * than the computation itself.  Similarly, parallelization may not
221 > * lead to much actual parallelism if all processors are busy
222 > * performing unrelated tasks.
223   *
224   * <p>All arguments to all task methods must be non-null.
225   *
204 * <p><em>jsr166e note: During transition, this class
205 * uses nested functional interfaces with different names but the
206 * same forms as those expected for JDK8.</em>
207 *
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 214 | 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>
236 <    implements ConcurrentMap<K, V>, Serializable {
235 > public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
236 >    implements ConcurrentMap<K,V>, Serializable {
237      private static final long serialVersionUID = 7249069246763182397L;
238  
221    /**
222     * A partitionable iterator. A Spliterator can be traversed
223     * directly, but can also be partitioned (before traversal) by
224     * creating another Spliterator that covers a non-overlapping
225     * portion of the elements, and so may be amenable to parallel
226     * execution.
227     *
228     * <p>This interface exports a subset of expected JDK8
229     * functionality.
230     *
231     * <p>Sample usage: Here is one (of the several) ways to compute
232     * the sum of the values held in a map using the ForkJoin
233     * framework. As illustrated here, Spliterators are well suited to
234     * designs in which a task repeatedly splits off half its work
235     * into forked subtasks until small enough to process directly,
236     * and then joins these subtasks. Variants of this style can also
237     * be used in completion-based designs.
238     *
239     * <pre>
240     * {@code ConcurrentHashMap<String, Long> m = ...
241     * // split as if have 8 * parallelism, for load balance
242     * int n = m.size();
243     * int p = aForkJoinPool.getParallelism() * 8;
244     * int split = (n < p)? n : p;
245     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
246     * // ...
247     * static class SumValues extends RecursiveTask<Long> {
248     *   final Spliterator<Long> s;
249     *   final int split;             // split while > 1
250     *   final SumValues nextJoin;    // records forked subtasks to join
251     *   SumValues(Spliterator<Long> s, int depth, SumValues nextJoin) {
252     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
253     *   }
254     *   public Long compute() {
255     *     long sum = 0;
256     *     SumValues subtasks = null; // fork subtasks
257     *     for (int s = split >>> 1; s > 0; s >>>= 1)
258     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
259     *     while (s.hasNext())        // directly process remaining elements
260     *       sum += s.next();
261     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
262     *       sum += t.join();         // collect subtask results
263     *     return sum;
264     *   }
265     * }
266     * }</pre>
267     */
268    public static interface Spliterator<T> extends Iterator<T> {
269        /**
270         * Returns a Spliterator covering approximately half of the
271         * elements, guaranteed not to overlap with those subsequently
272         * returned by this Spliterator.  After invoking this method,
273         * the current Spliterator will <em>not</em> produce any of
274         * the elements of the returned Spliterator, but the two
275         * Spliterators together will produce all of the elements that
276         * would have been produced by this Spliterator had this
277         * method not been called. The exact number of elements
278         * produced by the returned Spliterator is not guaranteed, and
279         * may be zero (i.e., with {@code hasNext()} reporting {@code
280         * false}) if this Spliterator cannot be further split.
281         *
282         * @return a Spliterator covering approximately half of the
283         * elements
284         * @throws IllegalStateException if this Spliterator has
285         * already commenced traversing elements
286         */
287        Spliterator<T> split();
288    }
289
239      /*
240       * Overview:
241       *
# Line 297 | 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 fields
250 <     * can contain special values, they are defined using plain Object
251 <     * types. Similarly in turn, all internal methods that use them
252 <     * work off Object types. And similarly, so do the internal
253 <     * methods of auxiliary iterator and view classes. This also
254 <     * allows many of the public methods to be factored into a smaller
255 <     * number of internal methods (although sadly not so for the five
256 <     * variants of put-related operations). The validation-based
257 <     * approach 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 314 | 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
318 <     * are always accurately traversable under volatile reads, so long
319 <     * as lookups check hash code and non-nullness of value before
320 <     * 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
326 <     * of each normal Node's hash field contain a transformation of
327 <     * 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 341 | 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,
345 <     * operations that only conditionally update may inspect nodes
346 <     * until the point of update. This is a converse of sorts to the
347 <     * 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 377 | 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
386 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
387 <     * (a specialized form of red-black trees), bounding search time
388 <     * 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 398 | 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 426 | 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 458 | Line 408 | public class ConcurrentHashMap<K, V>
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 512 | 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 526 | 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.
541 <    // See their internal docs for explanation.
586 >    /* ---------------- Nodes -------------- */
587  
588 <    // A padded cell for distributing counts
589 <    static final class CounterCell {
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 <        CounterCell(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 <     * Holder for the thread-local hash code determining which
653 <     * CounterCell to use. The code is initialized via the
654 <     * counterHashCodeGenerator, but may be moved upon collisions.
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 class CounterHashCode {
668 <        int code;
667 >    static final int spread(int h) {
668 >        return (h ^ (h >>> 16)) & HASH_BITS;
669      }
670  
671      /**
672 <     * Generates initial value for per-thread CounterHashCodes
672 >     * Returns a power of two table size for the given desired capacity.
673 >     * See Hackers Delight, sec 3.2
674       */
675 <    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
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 <     * Increment for counterHashCodeGenerator. See class ThreadLocal
682 <     * for explanation.
681 >     * Returns x's Class if it is of the form "class C implements
682 >     * Comparable<C>", else null.
683       */
684 <    static final int SEED_INCREMENT = 0x61c88647;
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 <     * Per-thread counter hash codes. Shared across all instances
704 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
705 >     * class), else 0.
706       */
707 <    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
708 <        new ThreadLocal<CounterHashCode>();
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.getObjectAcquire(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.compareAndSetObject(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.putObjectRelease(tab, ((long)i << ASHIFT) + ABASE, v);
741 >    }
742  
743      /* ---------------- Fields -------------- */
744  
# Line 580 | 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[] 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[] nextTable;
754 >    private transient volatile Node<K,V>[] nextTable;
755  
756      /**
757       * Base counter value, used mainly when there is no contention,
# Line 610 | 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.
614 <     */
615 <    private transient volatile int transferOrigin;
616 <
617 <    /**
618 <     * 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 counterBusy;
781 >    private transient volatile int cellsBusy;
782  
783      /**
784       * Table of counter cells. When non-null, size is a power of 2.
# Line 629 | Line 790 | public class ConcurrentHashMap<K, V>
790      private transient ValuesView<K,V> values;
791      private transient EntrySetView<K,V> entrySet;
792  
632    /** For serialization compatibility. Null unless serialized; see below */
633    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
639 <     * elements of in-progress next table while resizing.  Uses are
640 <     * null checked by callers, and implicitly bounds-checked, relying
641 <     * on the invariants that tab arrays have non-zero size, and all
642 <     * indices are masked with (tab.length - 1) which is never
643 <     * negative and always less than length. Note that, to be correct
644 <     * wrt arbitrary concurrency errors by users, bounds checks must
645 <     * operate on local variables, which accounts for some odd-looking
646 <     * inline assignments below.
796 >    /**
797 >     * Creates a new, empty map with the default initial table size (16).
798       */
799 <
649 <    static final Node tabAt(Node[] tab, int i) { // used by Traverser
650 <        return (Node)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
799 >    public ConcurrentHashMap() {
800      }
801  
802 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
803 <        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
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 <    private static final void setTabAt(Node[] tab, int i, Node v) {
817 <        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
816 >    /**
817 >     * Creates a new map with the same mappings as the given map.
818 >     *
819 >     * @param m the map
820 >     */
821 >    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
822 >        this.sizeCtl = DEFAULT_CAPACITY;
823 >        putAll(m);
824      }
825  
661    /* ---------------- Nodes -------------- */
662
826      /**
827 <     * Key-value entry. Note that this is never exported out as a
828 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
829 <     * field of MOVED are special, and do not contain user keys or
830 <     * values.  Otherwise, keys are never null, and null val fields
831 <     * indicate that a node is in the process of being deleted or
832 <     * created. For purposes of read-only access, a key may be read
833 <     * before a val, but can only be used after checking val to be
834 <     * non-null.
827 >     * Creates a new, empty map with an initial table size based on
828 >     * the given number of elements ({@code initialCapacity}) and
829 >     * initial table density ({@code loadFactor}).
830 >     *
831 >     * @param initialCapacity the initial capacity. The implementation
832 >     * performs internal sizing to accommodate this many elements,
833 >     * given the specified load factor.
834 >     * @param loadFactor the load factor (table density) for
835 >     * establishing the initial table size
836 >     * @throws IllegalArgumentException if the initial capacity of
837 >     * elements is negative or the load factor is nonpositive
838 >     *
839 >     * @since 1.6
840       */
841 <    static class Node {
842 <        final int hash;
843 <        final Object key;
676 <        volatile Object val;
677 <        volatile Node next;
841 >    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
842 >        this(initialCapacity, loadFactor, 1);
843 >    }
844  
845 <        Node(int hash, Object key, Object val, Node next) {
846 <            this.hash = hash;
847 <            this.key = key;
848 <            this.val = val;
849 <            this.next = next;
850 <        }
845 >    /**
846 >     * Creates a new, empty map with an initial table size based on
847 >     * the given number of elements ({@code initialCapacity}), 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 <    /* ---------------- TreeBins -------------- */
875 >    // Original (since JDK1.2) Map methods
876  
877      /**
878 <     * Nodes for use in TreeBins
878 >     * {@inheritDoc}
879       */
880 <    static final class TreeNode extends Node {
881 <        TreeNode parent;  // red-black tree links
882 <        TreeNode left;
883 <        TreeNode right;
884 <        TreeNode 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, Object val, Node next, TreeNode 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
713 <     * elements that are Comparable but not necessarily Comparable<T>
714 <     * for the same T, so we cannot invoke compareTo among them. To
715 <     * handle this, the tree is ordered primarily by hash value, then
716 <     * by getClass().getName() order, and then by Comparator order
717 <     * among elements of the same class.  On lookup at a node, if
718 <     * elements are not comparable or compare as 0, both left and
719 <     * right children may need to be searched in the case of tied hash
720 <     * values. (This corresponds to the full list search that would be
721 <     * necessary if all elements were non-Comparable and had tied
722 <     * hashes.)  The red-black balancing code is updated from
723 <     * pre-jdk-collections
724 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
725 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
726 <     * 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
729 <     * regular bins. Because they are forwarded via special MOVED
730 <     * nodes at bin heads (which can never change once established),
731 <     * we cannot use those nodes as locks. Instead, TreeBin
732 <     * extends AbstractQueuedSynchronizer to support a simple form of
733 <     * read-write lock. For update operations and table validation,
734 <     * the exclusive form of lock behaves in the same way as bin-head
735 <     * locks. However, lookups use shared read-lock mechanics to allow
736 <     * multiple readers in the absence of writers.  Additionally,
737 <     * these lookups do not ever block: While the lock is not
738 <     * available, they proceed along the slow traversal path (via
739 <     * next-pointers) until the lock becomes available or the list is
740 <     * exhausted, whichever comes first. (These cases are not fast,
741 <     * but maximize aggregate expected throughput.)  The AQS mechanics
742 <     * for doing this are straightforward.  The lock state is held as
743 <     * AQS getState().  Read counts are negative; the write count (1)
744 <     * is positive.  There are no signalling preferences among readers
745 <     * and writers. Since we don't need to export full Lock API, we
746 <     * 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 extends AbstractQueuedSynchronizer {
906 <        private static final long serialVersionUID = 2249069246763182397L;
907 <        transient TreeNode root;  // root of tree
908 <        transient TreeNode 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) {
763 <            setExclusiveOwnerThread(null);
764 <            setState(0);
765 <            return true;
766 <        }
767 <        public final int tryAcquireShared(int ignore) {
768 <            for (int c;;) {
769 <                if ((c = getState()) > 0)
770 <                    return -1;
771 <                if (compareAndSetState(c, c -1))
772 <                    return 1;
773 <            }
774 <        }
775 <        public final boolean tryReleaseShared(int ignore) {
776 <            int c;
777 <            do {} while (!compareAndSetState(c = getState(), c + 1));
778 <            return c == -1;
779 <        }
780 <
781 <        /** From CLR */
782 <        private void rotateLeft(TreeNode p) {
783 <            if (p != null) {
784 <                TreeNode r = p.right, pp, rl;
785 <                if ((rl = p.right = r.left) != null)
786 <                    rl.parent = p;
787 <                if ((pp = r.parent = p.parent) == null)
788 <                    root = r;
789 <                else if (pp.left == p)
790 <                    pp.left = r;
791 <                else
792 <                    pp.right = r;
793 <                r.left = p;
794 <                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 p) {
927 <            if (p != null) {
928 <                TreeNode 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;
810 <                l.right = p;
811 <                p.parent = l;
812 <            }
813 <        }
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 getTreeNode
943 <            (int h, Object k, TreeNode 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 r = null, pl, pr; // check both sides
956 <                            if ((pr = p.right) != null && h >= pr.hash &&
957 <                                (r = getTreeNode(h, k, pr)) != null)
835 <                                return r;
836 <                            else if ((pl = p.left) != null && h <= pl.hash)
837 <                                dir = -1;
838 <                            else // nothing there
839 <                                return null;
840 <                        }
841 <                    }
842 <                }
843 <                else
844 <                    dir = (h < ph) ? -1 : 1;
845 <                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              }
847            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 Object getValue(int h, Object k) {
969 <            Node r = null;
970 <            int c = getState(); // Must read lock state first
971 <            for (Node 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                      }
865                    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                  }
871                else
872                    c = getState();
1044              }
874            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 putTreeNode
1055 <            (int h, Object k, Object v) {
1056 <            Class<?> c = k.getClass();
1057 <            TreeNode 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;
889 <                if ((ph = p.hash) == h) {
890 <                    if ((pk = p.key) == k || k.equals(pk))
891 <                        return p;
892 <                    if (c != (pc = pk.getClass()) ||
893 <                        !(k instanceof Comparable) ||
894 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
895 <                        TreeNode s = null, r = null, pr;
896 <                        if ((dir = (c == pc) ? 0 :
897 <                             c.getName().compareTo(pc.getName())) == 0) {
898 <                            if ((pr = p.right) != null && h >= pr.hash &&
899 <                                (r = getTreeNode(h, k, pr)) != null)
900 <                                return r;
901 <                            else // continue left
902 <                                dir = -1;
903 <                        }
904 <                        else if ((pr = p.right) != null && h >= pr.hash)
905 <                            s = pr;
906 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
907 <                            return r;
908 <                    }
909 <                }
910 <                else
911 <                    dir = (h < ph) ? -1 : 1;
912 <                pp = (dir > 0) ? p.right : p.left;
913 <            }
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 f = first;
1064 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
1065 <            if (p == null)
1066 <                root = x;
1067 <            else { // attach and rebalance; adapted from CLR
1068 <                TreeNode 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 xppl = xpp.left;
1079 <                    if (xp == xppl) {
1080 <                        TreeNode 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 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 <                            }
966 <                            if (xp != null) {
967 <                                xp.red = false;
968 <                                if (xpp != null) {
969 <                                    xpp.red = true;
970 <                                    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 r = root;
1142 <                if (r != null && r.red)
1143 <                    r.red = false;
1144 <            }
1145 <            return null;
981 <        }
982 <
983 <        /**
984 <         * Removes the given node, that must be present before this
985 <         * call.  This is messier than typical red-black deletion code
986 <         * because we cannot swap the contents of an interior node
987 <         * with a leaf successor that is pinned by "next" pointers
988 <         * that are accessible independently of lock. So instead we
989 <         * swap the tree linkages.
990 <         */
991 <        final void deleteTreeNode(TreeNode p) {
992 <            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
993 <            TreeNode pred = p.prev;
994 <            if (pred == null)
995 <                first = next;
996 <            else
997 <                pred.next = next;
998 <            if (next != null)
999 <                next.prev = pred;
1000 <            TreeNode replacement;
1001 <            TreeNode pl = p.left;
1002 <            TreeNode pr = p.right;
1003 <            if (pl != null && pr != null) {
1004 <                TreeNode s = pr, sl;
1005 <                while ((sl = s.left) != null) // find successor
1006 <                    s = sl;
1007 <                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
1008 <                TreeNode sr = s.right;
1009 <                TreeNode pp = p.parent;
1010 <                if (s == pr) { // p was s's direct parent
1011 <                    p.parent = s;
1012 <                    s.right = p;
1013 <                }
1014 <                else {
1015 <                    TreeNode sp = s.parent;
1016 <                    if ((p.parent = sp) != null) {
1017 <                        if (s == sp.left)
1018 <                            sp.left = p;
1019 <                        else
1020 <                            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)
1023 <                        pr.parent = s;
1147 >                    break;
1148                  }
1025                p.left = null;
1026                if ((p.right = sr) != null)
1027                    sr.parent = p;
1028                if ((s.left = pl) != null)
1029                    pl.parent = s;
1030                if ((s.parent = pp) == null)
1031                    root = s;
1032                else if (p == pp.left)
1033                    pp.left = s;
1034                else
1035                    pp.right = s;
1036                replacement = sr;
1149              }
1150 <            else
1151 <                replacement = (pl != null) ? pl : pr;
1152 <            TreeNode 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;
1057 <            }
1058 <            if (!p.red) { // rebalance, from CLR
1059 <                TreeNode x = replacement;
1060 <                while (x != null) {
1061 <                    TreeNode xp, xpl;
1062 <                    if (x.red || (xp = x.parent) == null) {
1063 <                        x.red = false;
1064 <                        break;
1065 <                    }
1066 <                    if (x == (xpl = xp.left)) {
1067 <                        TreeNode sib = xp.right;
1068 <                        if (sib != null && sib.red) {
1069 <                            sib.red = false;
1070 <                            xp.red = true;
1071 <                            rotateLeft(xp);
1072 <                            sib = (xp = x.parent) == null ? null : xp.right;
1073 <                        }
1074 <                        if (sib == null)
1075 <                            x = xp;
1076 <                        else {
1077 <                            TreeNode sl = sib.left, sr = sib.right;
1078 <                            if ((sr == null || !sr.red) &&
1079 <                                (sl == null || !sl.red)) {
1080 <                                sib.red = true;
1081 <                                x = xp;
1082 <                            }
1083 <                            else {
1084 <                                if (sr == null || !sr.red) {
1085 <                                    if (sl != null)
1086 <                                        sl.red = false;
1087 <                                    sib.red = true;
1088 <                                    rotateRight(sib);
1089 <                                    sib = (xp = x.parent) == null ?
1090 <                                        null : xp.right;
1091 <                                }
1092 <                                if (sib != null) {
1093 <                                    sib.red = (xp == null) ? false : xp.red;
1094 <                                    if ((sr = sib.right) != null)
1095 <                                        sr.red = false;
1096 <                                }
1097 <                                if (xp != null) {
1098 <                                    xp.red = false;
1099 <                                    rotateLeft(xp);
1100 <                                }
1101 <                                x = root;
1102 <                            }
1103 <                        }
1104 <                    }
1105 <                    else { // symmetric
1106 <                        TreeNode sib = xpl;
1107 <                        if (sib != null && sib.red) {
1108 <                            sib.red = false;
1109 <                            xp.red = true;
1110 <                            rotateRight(xp);
1111 <                            sib = (xp = x.parent) == null ? null : xp.left;
1112 <                        }
1113 <                        if (sib == null)
1114 <                            x = xp;
1115 <                        else {
1116 <                            TreeNode sl = sib.left, sr = sib.right;
1117 <                            if ((sl == null || !sl.red) &&
1118 <                                (sr == null || !sr.red)) {
1119 <                                sib.red = true;
1120 <                                x = xp;
1121 <                            }
1122 <                            else {
1123 <                                if (sl == null || !sl.red) {
1124 <                                    if (sr != null)
1125 <                                        sr.red = false;
1126 <                                    sib.red = true;
1127 <                                    rotateLeft(sib);
1128 <                                    sib = (xp = x.parent) == null ?
1129 <                                        null : xp.left;
1130 <                                }
1131 <                                if (sib != null) {
1132 <                                    sib.red = (xp == null) ? false : xp.red;
1133 <                                    if ((sl = sib.left) != null)
1134 <                                        sl.red = false;
1135 <                                }
1136 <                                if (xp != null) {
1137 <                                    xp.red = false;
1138 <                                    rotateRight(xp);
1139 <                                }
1140 <                                x = root;
1141 <                            }
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              }
1146            if (p == replacement && (pp = p.parent) != null) {
1147                if (p == pp.left) // detach pointers
1148                    pp.left = null;
1149                else if (p == pp.right)
1150                    pp.right = null;
1151                p.parent = null;
1152            }
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[] tab, int index, Object key) {
1322 <        if (key instanceof Comparable) {
1323 <            TreeBin t = new TreeBin();
1324 <            for (Node e = tabAt(tab, index); e != null; e = e.next)
1325 <                t.putTreeNode(e.hash, e.key, e.val);
1326 <            setTabAt(tab, index, new Node(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[] tab = table; tab != null;) {
1361 <            Node e; Object ek, 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 (V)((TreeBin)ek).getValue(h, k);
1366 <                    else {                        // restart with new table
1367 <                        tab = (Node[])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 (V)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              }
1209            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 <        Object oldVal = null;
1413 <        for (Node[] tab = table;;) {
1414 <            Node 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 t = (TreeBin)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 p = t.getTreeNode(h, k, t.root);
1443 <                            if (p != null) {
1444 <                                Object 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 <                    }
1252 <                    if (validated) {
1253 <                        if (deleted)
1254 <                            addCount(-1L, -1);
1255 <                        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[])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;
1266 <                synchronized (f) {
1267 <                    if (tabAt(tab, i) == f) {
1268 <                        validated = true;
1269 <                        for (Node e = f, pred = null;;) {
1270 <                            Object ek, ev;
1271 <                            if (e.hash == h &&
1272 <                                ((ev = e.val) != null) &&
1273 <                                ((ek = e.key) == k || k.equals(ek))) {
1274 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1275 <                                    oldVal = ev;
1276 <                                    if ((e.val = v) == null) {
1277 <                                        deleted = true;
1278 <                                        Node en = e.next;
1279 <                                        if (pred != null)
1280 <                                            pred.next = en;
1281 <                                        else
1282 <                                            setTabAt(tab, i, en);
1283 <                                    }
1284 <                                }
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          }
1300        return (V)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
1311 <     *
1312 <     * The putAll method differs mainly in attempting to pre-allocate
1313 <     * enough table space, and also more lazily performs count updates
1314 <     * and checks.
1315 <     *
1316 <     * Most of the function-accepting methods can't be factored nicely
1317 <     * because they require different functional forms, so instead
1318 <     * 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[] tab = table;;) {
1522 <            int i, fh; Node f; Object fk, 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(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 t = (TreeBin)fk;
1579 <                    Object oldVal = null;
1580 <                    t.acquire(0);
1581 <                    try {
1582 <                        if (tabAt(tab, i) == f) {
1583 <                            len = 2;
1584 <                            TreeNode 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 {
1351 <                        t.release(0);
1352 <                    }
1353 <                    if (len != 0) {
1354 <                        if (oldVal != null)
1355 <                            return (V)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;
1357                    }
1593                  }
1359                else
1360                    tab = (Node[])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 (V)fv;
1598 <            else {
1599 <                Object oldVal = null;
1600 <                synchronized (f) {
1601 <                    if (tabAt(tab, i) == f) {
1602 <                        len = 1;
1603 <                        for (Node e = f;; ++len) {
1604 <                            Object ek, 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 <                            }
1613 <                            Node last = e;
1614 <                            if ((e = e.next) == null) {
1615 <                                last.next = new Node(h, k, v, null);
1616 <                                if (len >= TREE_THRESHOLD)
1617 <                                    replaceWithTreeBin(tab, i, k);
1618 <                                break;
1619 <                            }
1620 <                        }
1621 <                    }
1622 <                }
1623 <                if (len != 0) {
1624 <                    if (oldVal != null)
1625 <                        return (V)oldVal;
1626 <                    break;
1627 <                }
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 >        return removed;
1616 >    }
1617 >
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 <        addCount(1L, len);
1398 <        return null;
1634 >        return removed;
1635      }
1636  
1637 <    /** Implementation for computeIfAbsent */
1638 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1639 <        (K k, Fun<? super K, ?> mf) {
1640 <        if (k == null || mf == null)
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, so the function is
1642 >     * applied at most once per key.  Some attempted update operations
1643 >     * on this map by other threads may be blocked while computation
1644 >     * is in progress, so the computation should be short and simple,
1645 >     * and must not attempt to update any other mappings of this map.
1646 >     *
1647 >     * @param key key with which the specified value is to be associated
1648 >     * @param mappingFunction the function to compute a value
1649 >     * @return the current (existing or computed) value associated with
1650 >     *         the specified key, or null if the computed value is null
1651 >     * @throws NullPointerException if the specified key or mappingFunction
1652 >     *         is null
1653 >     * @throws IllegalStateException if the computation detectably
1654 >     *         attempts a recursive update to this map that would
1655 >     *         otherwise never complete
1656 >     * @throws RuntimeException or Error if the mappingFunction does so,
1657 >     *         in which case the mapping is left unestablished
1658 >     */
1659 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1660 >        if (key == null || mappingFunction == null)
1661              throw new NullPointerException();
1662 <        int h = spread(k.hashCode());
1663 <        Object val = null;
1664 <        int len = 0;
1665 <        for (Node[] tab = table;;) {
1666 <            Node f; int i; Object fk;
1667 <            if (tab == null)
1662 >        int h = spread(key.hashCode());
1663 >        V val = null;
1664 >        int binCount = 0;
1665 >        for (Node<K,V>[] tab = table;;) {
1666 >            Node<K,V> f; int n, i, fh; K fk; V fv;
1667 >            if (tab == null || (n = tab.length) == 0)
1668                  tab = initTable();
1669 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1670 <                Node node = new Node(h, k, null, null);
1671 <                synchronized (node) {
1672 <                    if (casTabAt(tab, i, null, node)) {
1673 <                        len = 1;
1669 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1670 >                Node<K,V> r = new ReservationNode<K,V>();
1671 >                synchronized (r) {
1672 >                    if (casTabAt(tab, i, null, r)) {
1673 >                        binCount = 1;
1674 >                        Node<K,V> node = null;
1675                          try {
1676 <                            if ((val = mf.apply(k)) != null)
1677 <                                node.val = val;
1676 >                            if ((val = mappingFunction.apply(key)) != null)
1677 >                                node = new Node<K,V>(h, key, val);
1678                          } finally {
1679 <                            if (val == null)
1423 <                                setTabAt(tab, i, null);
1679 >                            setTabAt(tab, i, node);
1680                          }
1681                      }
1682                  }
1683 <                if (len != 0)
1683 >                if (binCount != 0)
1684                      break;
1685              }
1686 <            else if (f.hash < 0) {
1687 <                if ((fk = f.key) instanceof TreeBin) {
1688 <                    TreeBin t = (TreeBin)fk;
1689 <                    boolean added = false;
1690 <                    t.acquire(0);
1691 <                    try {
1692 <                        if (tabAt(tab, i) == f) {
1693 <                            len = 1;
1694 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1695 <                            if (p != null)
1686 >            else if ((fh = f.hash) == MOVED)
1687 >                tab = helpTransfer(tab, f);
1688 >            else if (fh == h    // check first node without acquiring lock
1689 >                     && ((fk = f.key) == key || (fk != null && key.equals(fk)))
1690 >                     && (fv = f.val) != null)
1691 >                return fv;
1692 >            else {
1693 >                boolean added = false;
1694 >                synchronized (f) {
1695 >                    if (tabAt(tab, i) == f) {
1696 >                        if (fh >= 0) {
1697 >                            binCount = 1;
1698 >                            for (Node<K,V> e = f;; ++binCount) {
1699 >                                K ek;
1700 >                                if (e.hash == h &&
1701 >                                    ((ek = e.key) == key ||
1702 >                                     (ek != null && key.equals(ek)))) {
1703 >                                    val = e.val;
1704 >                                    break;
1705 >                                }
1706 >                                Node<K,V> pred = e;
1707 >                                if ((e = e.next) == null) {
1708 >                                    if ((val = mappingFunction.apply(key)) != null) {
1709 >                                        if (pred.next != null)
1710 >                                            throw new IllegalStateException("Recursive update");
1711 >                                        added = true;
1712 >                                        pred.next = new Node<K,V>(h, key, val);
1713 >                                    }
1714 >                                    break;
1715 >                                }
1716 >                            }
1717 >                        }
1718 >                        else if (f instanceof TreeBin) {
1719 >                            binCount = 2;
1720 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1721 >                            TreeNode<K,V> r, p;
1722 >                            if ((r = t.root) != null &&
1723 >                                (p = r.findTreeNode(h, key, null)) != null)
1724                                  val = p.val;
1725 <                            else if ((val = mf.apply(k)) != null) {
1725 >                            else if ((val = mappingFunction.apply(key)) != null) {
1726                                  added = true;
1727 <                                len = 2;
1444 <                                t.putTreeNode(h, k, val);
1727 >                                t.putTreeVal(h, key, val);
1728                              }
1729                          }
1730 <                    } finally {
1731 <                        t.release(0);
1449 <                    }
1450 <                    if (len != 0) {
1451 <                        if (!added)
1452 <                            return (V)val;
1453 <                        break;
1730 >                        else if (f instanceof ReservationNode)
1731 >                            throw new IllegalStateException("Recursive update");
1732                      }
1733                  }
1734 <                else
1735 <                    tab = (Node[])fk;
1734 >                if (binCount != 0) {
1735 >                    if (binCount >= TREEIFY_THRESHOLD)
1736 >                        treeifyBin(tab, i);
1737 >                    if (!added)
1738 >                        return val;
1739 >                    break;
1740 >                }
1741              }
1742 +        }
1743 +        if (val != null)
1744 +            addCount(1L, binCount);
1745 +        return val;
1746 +    }
1747 +
1748 +    /**
1749 +     * If the value for the specified key is present, attempts to
1750 +     * compute a new mapping given the key and its current mapped
1751 +     * value.  The entire method invocation is performed atomically.
1752 +     * Some attempted update operations on this map by other threads
1753 +     * may be blocked while computation is in progress, so the
1754 +     * computation should be short and simple, and must not attempt to
1755 +     * update any other mappings of this map.
1756 +     *
1757 +     * @param key key with which a value may be associated
1758 +     * @param remappingFunction the function to compute a value
1759 +     * @return the new value associated with the specified key, or null if none
1760 +     * @throws NullPointerException if the specified key or remappingFunction
1761 +     *         is null
1762 +     * @throws IllegalStateException if the computation detectably
1763 +     *         attempts a recursive update to this map that would
1764 +     *         otherwise never complete
1765 +     * @throws RuntimeException or Error if the remappingFunction does so,
1766 +     *         in which case the mapping is unchanged
1767 +     */
1768 +    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1769 +        if (key == null || remappingFunction == null)
1770 +            throw new NullPointerException();
1771 +        int h = spread(key.hashCode());
1772 +        V val = null;
1773 +        int delta = 0;
1774 +        int binCount = 0;
1775 +        for (Node<K,V>[] tab = table;;) {
1776 +            Node<K,V> f; int n, i, fh;
1777 +            if (tab == null || (n = tab.length) == 0)
1778 +                tab = initTable();
1779 +            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1780 +                break;
1781 +            else if ((fh = f.hash) == MOVED)
1782 +                tab = helpTransfer(tab, f);
1783              else {
1460                for (Node e = f; e != null; e = e.next) { // prescan
1461                    Object ek, ev;
1462                    if (e.hash == h && (ev = e.val) != null &&
1463                        ((ek = e.key) == k || k.equals(ek)))
1464                        return (V)ev;
1465                }
1466                boolean added = false;
1784                  synchronized (f) {
1785                      if (tabAt(tab, i) == f) {
1786 <                        len = 1;
1787 <                        for (Node e = f;; ++len) {
1788 <                            Object ek, ev;
1789 <                            if (e.hash == h &&
1790 <                                (ev = e.val) != null &&
1791 <                                ((ek = e.key) == k || k.equals(ek))) {
1792 <                                val = ev;
1793 <                                break;
1786 >                        if (fh >= 0) {
1787 >                            binCount = 1;
1788 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1789 >                                K ek;
1790 >                                if (e.hash == h &&
1791 >                                    ((ek = e.key) == key ||
1792 >                                     (ek != null && key.equals(ek)))) {
1793 >                                    val = remappingFunction.apply(key, e.val);
1794 >                                    if (val != null)
1795 >                                        e.val = val;
1796 >                                    else {
1797 >                                        delta = -1;
1798 >                                        Node<K,V> en = e.next;
1799 >                                        if (pred != null)
1800 >                                            pred.next = en;
1801 >                                        else
1802 >                                            setTabAt(tab, i, en);
1803 >                                    }
1804 >                                    break;
1805 >                                }
1806 >                                pred = e;
1807 >                                if ((e = e.next) == null)
1808 >                                    break;
1809                              }
1810 <                            Node last = e;
1811 <                            if ((e = e.next) == null) {
1812 <                                if ((val = mf.apply(k)) != null) {
1813 <                                    added = true;
1814 <                                    last.next = new Node(h, k, val, null);
1815 <                                    if (len >= TREE_THRESHOLD)
1816 <                                        replaceWithTreeBin(tab, i, k);
1810 >                        }
1811 >                        else if (f instanceof TreeBin) {
1812 >                            binCount = 2;
1813 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1814 >                            TreeNode<K,V> r, p;
1815 >                            if ((r = t.root) != null &&
1816 >                                (p = r.findTreeNode(h, key, null)) != null) {
1817 >                                val = remappingFunction.apply(key, p.val);
1818 >                                if (val != null)
1819 >                                    p.val = val;
1820 >                                else {
1821 >                                    delta = -1;
1822 >                                    if (t.removeTreeNode(p))
1823 >                                        setTabAt(tab, i, untreeify(t.first));
1824                                  }
1486                                break;
1825                              }
1826                          }
1827 +                        else if (f instanceof ReservationNode)
1828 +                            throw new IllegalStateException("Recursive update");
1829                      }
1830                  }
1831 <                if (len != 0) {
1492 <                    if (!added)
1493 <                        return (V)val;
1831 >                if (binCount != 0)
1832                      break;
1495                }
1833              }
1834          }
1835 <        if (val != null)
1836 <            addCount(1L, len);
1837 <        return (V)val;
1835 >        if (delta != 0)
1836 >            addCount((long)delta, binCount);
1837 >        return val;
1838      }
1839  
1840 <    /** Implementation for compute */
1841 <    @SuppressWarnings("unchecked") private final V internalCompute
1842 <        (K k, boolean onlyIfPresent,
1843 <         BiFun<? super K, ? super V, ? extends V> mf) {
1844 <        if (k == null || mf == null)
1840 >    /**
1841 >     * Attempts to compute a mapping for the specified key and its
1842 >     * current mapped value (or {@code null} if there is no current
1843 >     * mapping). The entire method invocation is performed atomically.
1844 >     * Some attempted update operations on this map by other threads
1845 >     * may be blocked while computation is in progress, so the
1846 >     * computation should be short and simple, and must not attempt to
1847 >     * update any other mappings of this Map.
1848 >     *
1849 >     * @param key key with which the specified value is to be associated
1850 >     * @param remappingFunction the function to compute a value
1851 >     * @return the new value associated with the specified key, or null if none
1852 >     * @throws NullPointerException if the specified key or remappingFunction
1853 >     *         is null
1854 >     * @throws IllegalStateException if the computation detectably
1855 >     *         attempts a recursive update to this map that would
1856 >     *         otherwise never complete
1857 >     * @throws RuntimeException or Error if the remappingFunction does so,
1858 >     *         in which case the mapping is unchanged
1859 >     */
1860 >    public V compute(K key,
1861 >                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1862 >        if (key == null || remappingFunction == null)
1863              throw new NullPointerException();
1864 <        int h = spread(k.hashCode());
1865 <        Object val = null;
1864 >        int h = spread(key.hashCode());
1865 >        V val = null;
1866          int delta = 0;
1867 <        int len = 0;
1868 <        for (Node[] tab = table;;) {
1869 <            Node f; int i, fh; Object fk;
1870 <            if (tab == null)
1867 >        int binCount = 0;
1868 >        for (Node<K,V>[] tab = table;;) {
1869 >            Node<K,V> f; int n, i, fh;
1870 >            if (tab == null || (n = tab.length) == 0)
1871                  tab = initTable();
1872 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1873 <                if (onlyIfPresent)
1874 <                    break;
1875 <                Node node = new Node(h, k, null, null);
1876 <                synchronized (node) {
1877 <                    if (casTabAt(tab, i, null, node)) {
1872 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1873 >                Node<K,V> r = new ReservationNode<K,V>();
1874 >                synchronized (r) {
1875 >                    if (casTabAt(tab, i, null, r)) {
1876 >                        binCount = 1;
1877 >                        Node<K,V> node = null;
1878                          try {
1879 <                            len = 1;
1525 <                            if ((val = mf.apply(k, null)) != null) {
1526 <                                node.val = val;
1879 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1880                                  delta = 1;
1881 +                                node = new Node<K,V>(h, key, val);
1882                              }
1883                          } finally {
1884 <                            if (delta == 0)
1531 <                                setTabAt(tab, i, null);
1884 >                            setTabAt(tab, i, node);
1885                          }
1886                      }
1887                  }
1888 <                if (len != 0)
1888 >                if (binCount != 0)
1889                      break;
1890              }
1891 <            else if ((fh = f.hash) < 0) {
1892 <                if ((fk = f.key) instanceof TreeBin) {
1893 <                    TreeBin t = (TreeBin)fk;
1894 <                    t.acquire(0);
1895 <                    try {
1896 <                        if (tabAt(tab, i) == f) {
1897 <                            len = 1;
1898 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1899 <                            if (p == null && onlyIfPresent)
1900 <                                break;
1901 <                            Object pv = (p == null) ? null : p.val;
1902 <                            if ((val = mf.apply(k, (V)pv)) != null) {
1891 >            else if ((fh = f.hash) == MOVED)
1892 >                tab = helpTransfer(tab, f);
1893 >            else {
1894 >                synchronized (f) {
1895 >                    if (tabAt(tab, i) == f) {
1896 >                        if (fh >= 0) {
1897 >                            binCount = 1;
1898 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1899 >                                K ek;
1900 >                                if (e.hash == h &&
1901 >                                    ((ek = e.key) == key ||
1902 >                                     (ek != null && key.equals(ek)))) {
1903 >                                    val = remappingFunction.apply(key, e.val);
1904 >                                    if (val != null)
1905 >                                        e.val = val;
1906 >                                    else {
1907 >                                        delta = -1;
1908 >                                        Node<K,V> en = e.next;
1909 >                                        if (pred != null)
1910 >                                            pred.next = en;
1911 >                                        else
1912 >                                            setTabAt(tab, i, en);
1913 >                                    }
1914 >                                    break;
1915 >                                }
1916 >                                pred = e;
1917 >                                if ((e = e.next) == null) {
1918 >                                    val = remappingFunction.apply(key, null);
1919 >                                    if (val != null) {
1920 >                                        if (pred.next != null)
1921 >                                            throw new IllegalStateException("Recursive update");
1922 >                                        delta = 1;
1923 >                                        pred.next = new Node<K,V>(h, key, val);
1924 >                                    }
1925 >                                    break;
1926 >                                }
1927 >                            }
1928 >                        }
1929 >                        else if (f instanceof TreeBin) {
1930 >                            binCount = 1;
1931 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1932 >                            TreeNode<K,V> r, p;
1933 >                            if ((r = t.root) != null)
1934 >                                p = r.findTreeNode(h, key, null);
1935 >                            else
1936 >                                p = null;
1937 >                            V pv = (p == null) ? null : p.val;
1938 >                            val = remappingFunction.apply(key, pv);
1939 >                            if (val != null) {
1940                                  if (p != null)
1941                                      p.val = val;
1942                                  else {
1553                                    len = 2;
1943                                      delta = 1;
1944 <                                    t.putTreeNode(h, k, val);
1944 >                                    t.putTreeVal(h, key, val);
1945                                  }
1946                              }
1947                              else if (p != null) {
1948                                  delta = -1;
1949 <                                t.deleteTreeNode(p);
1950 <                            }
1562 <                        }
1563 <                    } finally {
1564 <                        t.release(0);
1565 <                    }
1566 <                    if (len != 0)
1567 <                        break;
1568 <                }
1569 <                else
1570 <                    tab = (Node[])fk;
1571 <            }
1572 <            else {
1573 <                synchronized (f) {
1574 <                    if (tabAt(tab, i) == f) {
1575 <                        len = 1;
1576 <                        for (Node e = f, pred = null;; ++len) {
1577 <                            Object ek, ev;
1578 <                            if (e.hash == h &&
1579 <                                (ev = e.val) != null &&
1580 <                                ((ek = e.key) == k || k.equals(ek))) {
1581 <                                val = mf.apply(k, (V)ev);
1582 <                                if (val != null)
1583 <                                    e.val = val;
1584 <                                else {
1585 <                                    delta = -1;
1586 <                                    Node en = e.next;
1587 <                                    if (pred != null)
1588 <                                        pred.next = en;
1589 <                                    else
1590 <                                        setTabAt(tab, i, en);
1591 <                                }
1592 <                                break;
1593 <                            }
1594 <                            pred = e;
1595 <                            if ((e = e.next) == null) {
1596 <                                if (!onlyIfPresent &&
1597 <                                    (val = mf.apply(k, null)) != null) {
1598 <                                    pred.next = new Node(h, k, val, null);
1599 <                                    delta = 1;
1600 <                                    if (len >= TREE_THRESHOLD)
1601 <                                        replaceWithTreeBin(tab, i, k);
1602 <                                }
1603 <                                break;
1949 >                                if (t.removeTreeNode(p))
1950 >                                    setTabAt(tab, i, untreeify(t.first));
1951                              }
1952                          }
1953 +                        else if (f instanceof ReservationNode)
1954 +                            throw new IllegalStateException("Recursive update");
1955                      }
1956                  }
1957 <                if (len != 0)
1957 >                if (binCount != 0) {
1958 >                    if (binCount >= TREEIFY_THRESHOLD)
1959 >                        treeifyBin(tab, i);
1960                      break;
1961 +                }
1962              }
1963          }
1964          if (delta != 0)
1965 <            addCount((long)delta, len);
1966 <        return (V)val;
1965 >            addCount((long)delta, binCount);
1966 >        return val;
1967      }
1968  
1969 <    /** Implementation for merge */
1970 <    @SuppressWarnings("unchecked") private final V internalMerge
1971 <        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1972 <        if (k == null || v == null || mf == null)
1969 >    /**
1970 >     * If the specified key is not already associated with a
1971 >     * (non-null) value, associates it with the given value.
1972 >     * Otherwise, replaces the value with the results of the given
1973 >     * remapping function, or removes if {@code null}. The entire
1974 >     * method invocation is performed atomically.  Some attempted
1975 >     * update operations on this map by other threads may be blocked
1976 >     * while computation is in progress, so the computation should be
1977 >     * short and simple, and must not attempt to update any other
1978 >     * mappings of this Map.
1979 >     *
1980 >     * @param key key with which the specified value is to be associated
1981 >     * @param value the value to use if absent
1982 >     * @param remappingFunction the function to recompute a value if present
1983 >     * @return the new value associated with the specified key, or null if none
1984 >     * @throws NullPointerException if the specified key or the
1985 >     *         remappingFunction is null
1986 >     * @throws RuntimeException or Error if the remappingFunction does so,
1987 >     *         in which case the mapping is unchanged
1988 >     */
1989 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1990 >        if (key == null || value == null || remappingFunction == null)
1991              throw new NullPointerException();
1992 <        int h = spread(k.hashCode());
1993 <        Object val = null;
1992 >        int h = spread(key.hashCode());
1993 >        V val = null;
1994          int delta = 0;
1995 <        int len = 0;
1996 <        for (Node[] tab = table;;) {
1997 <            int i; Node f; Object fk, fv;
1998 <            if (tab == null)
1995 >        int binCount = 0;
1996 >        for (Node<K,V>[] tab = table;;) {
1997 >            Node<K,V> f; int n, i, fh;
1998 >            if (tab == null || (n = tab.length) == 0)
1999                  tab = initTable();
2000 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
2001 <                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
2000 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
2001 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value))) {
2002                      delta = 1;
2003 <                    val = v;
2003 >                    val = value;
2004                      break;
2005                  }
2006              }
2007 <            else if (f.hash < 0) {
2008 <                if ((fk = f.key) instanceof TreeBin) {
2009 <                    TreeBin t = (TreeBin)fk;
2010 <                    t.acquire(0);
2011 <                    try {
2012 <                        if (tabAt(tab, i) == f) {
2013 <                            len = 1;
2014 <                            TreeNode p = t.getTreeNode(h, k, t.root);
2015 <                            val = (p == null) ? v : mf.apply((V)p.val, v);
2007 >            else if ((fh = f.hash) == MOVED)
2008 >                tab = helpTransfer(tab, f);
2009 >            else {
2010 >                synchronized (f) {
2011 >                    if (tabAt(tab, i) == f) {
2012 >                        if (fh >= 0) {
2013 >                            binCount = 1;
2014 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
2015 >                                K ek;
2016 >                                if (e.hash == h &&
2017 >                                    ((ek = e.key) == key ||
2018 >                                     (ek != null && key.equals(ek)))) {
2019 >                                    val = remappingFunction.apply(e.val, value);
2020 >                                    if (val != null)
2021 >                                        e.val = val;
2022 >                                    else {
2023 >                                        delta = -1;
2024 >                                        Node<K,V> en = e.next;
2025 >                                        if (pred != null)
2026 >                                            pred.next = en;
2027 >                                        else
2028 >                                            setTabAt(tab, i, en);
2029 >                                    }
2030 >                                    break;
2031 >                                }
2032 >                                pred = e;
2033 >                                if ((e = e.next) == null) {
2034 >                                    delta = 1;
2035 >                                    val = value;
2036 >                                    pred.next = new Node<K,V>(h, key, val);
2037 >                                    break;
2038 >                                }
2039 >                            }
2040 >                        }
2041 >                        else if (f instanceof TreeBin) {
2042 >                            binCount = 2;
2043 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2044 >                            TreeNode<K,V> r = t.root;
2045 >                            TreeNode<K,V> p = (r == null) ? null :
2046 >                                r.findTreeNode(h, key, null);
2047 >                            val = (p == null) ? value :
2048 >                                remappingFunction.apply(p.val, value);
2049                              if (val != null) {
2050                                  if (p != null)
2051                                      p.val = val;
2052                                  else {
1650                                    len = 2;
2053                                      delta = 1;
2054 <                                    t.putTreeNode(h, k, val);
2054 >                                    t.putTreeVal(h, key, val);
2055                                  }
2056                              }
2057                              else if (p != null) {
2058                                  delta = -1;
2059 <                                t.deleteTreeNode(p);
2059 >                                if (t.removeTreeNode(p))
2060 >                                    setTabAt(tab, i, untreeify(t.first));
2061                              }
2062                          }
2063 <                    } finally {
2064 <                        t.release(0);
2063 >                        else if (f instanceof ReservationNode)
2064 >                            throw new IllegalStateException("Recursive update");
2065                      }
1663                    if (len != 0)
1664                        break;
2066                  }
2067 <                else
2068 <                    tab = (Node[])fk;
2069 <            }
1669 <            else {
1670 <                synchronized (f) {
1671 <                    if (tabAt(tab, i) == f) {
1672 <                        len = 1;
1673 <                        for (Node e = f, pred = null;; ++len) {
1674 <                            Object ek, ev;
1675 <                            if (e.hash == h &&
1676 <                                (ev = e.val) != null &&
1677 <                                ((ek = e.key) == k || k.equals(ek))) {
1678 <                                val = mf.apply((V)ev, v);
1679 <                                if (val != null)
1680 <                                    e.val = val;
1681 <                                else {
1682 <                                    delta = -1;
1683 <                                    Node en = e.next;
1684 <                                    if (pred != null)
1685 <                                        pred.next = en;
1686 <                                    else
1687 <                                        setTabAt(tab, i, en);
1688 <                                }
1689 <                                break;
1690 <                            }
1691 <                            pred = e;
1692 <                            if ((e = e.next) == null) {
1693 <                                val = v;
1694 <                                pred.next = new Node(h, k, val, null);
1695 <                                delta = 1;
1696 <                                if (len >= TREE_THRESHOLD)
1697 <                                    replaceWithTreeBin(tab, i, k);
1698 <                                break;
1699 <                            }
1700 <                        }
1701 <                    }
1702 <                }
1703 <                if (len != 0)
2067 >                if (binCount != 0) {
2068 >                    if (binCount >= TREEIFY_THRESHOLD)
2069 >                        treeifyBin(tab, i);
2070                      break;
2071 +                }
2072              }
2073          }
2074          if (delta != 0)
2075 <            addCount((long)delta, len);
2076 <        return (V)val;
2075 >            addCount((long)delta, binCount);
2076 >        return val;
2077      }
2078  
2079 <    /** Implementation for putAll */
2080 <    private final void internalPutAll(Map<?, ?> m) {
2081 <        tryPresize(m.size());
2082 <        long delta = 0L;     // number of uncommitted additions
2083 <        boolean npe = false; // to throw exception on exit for nulls
2084 <        try {                // to clean up counts on other exceptions
2085 <            for (Map.Entry<?, ?> entry : m.entrySet()) {
2086 <                Object k, v;
2087 <                if (entry == null || (k = entry.getKey()) == null ||
2088 <                    (v = entry.getValue()) == null) {
2089 <                    npe = true;
2090 <                    break;
2091 <                }
2092 <                int h = spread(k.hashCode());
2093 <                for (Node[] tab = table;;) {
2094 <                    int i; Node f; int fh; Object fk;
2095 <                    if (tab == null)
2096 <                        tab = initTable();
2097 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
2098 <                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
2099 <                            ++delta;
2100 <                            break;
2101 <                        }
2102 <                    }
2103 <                    else if ((fh = f.hash) < 0) {
2104 <                        if ((fk = f.key) instanceof TreeBin) {
2105 <                            TreeBin t = (TreeBin)fk;
2106 <                            boolean validated = false;
2107 <                            t.acquire(0);
2108 <                            try {
2109 <                                if (tabAt(tab, i) == f) {
2110 <                                    validated = true;
2111 <                                    TreeNode p = t.getTreeNode(h, k, t.root);
2112 <                                    if (p != null)
2113 <                                        p.val = v;
2114 <                                    else {
2115 <                                        t.putTreeNode(h, k, v);
2116 <                                        ++delta;
2117 <                                    }
2118 <                                }
2119 <                            } finally {
2120 <                                t.release(0);
2121 <                            }
2122 <                            if (validated)
2123 <                                break;
2079 >    // Hashtable legacy methods
2080 >
2081 >    /**
2082 >     * Tests if some key maps into the specified value in this table.
2083 >     *
2084 >     * <p>Note that this method is identical in functionality to
2085 >     * {@link #containsValue(Object)}, and exists solely to ensure
2086 >     * full compatibility with class {@link java.util.Hashtable},
2087 >     * which supported this method prior to introduction of the
2088 >     * Java Collections Framework.
2089 >     *
2090 >     * @param  value a value to search for
2091 >     * @return {@code true} if and only if some key maps to the
2092 >     *         {@code value} argument in this table as
2093 >     *         determined by the {@code equals} method;
2094 >     *         {@code false} otherwise
2095 >     * @throws NullPointerException if the specified value is null
2096 >     */
2097 >    public boolean contains(Object value) {
2098 >        return containsValue(value);
2099 >    }
2100 >
2101 >    /**
2102 >     * Returns an enumeration of the keys in this table.
2103 >     *
2104 >     * @return an enumeration of the keys in this table
2105 >     * @see #keySet()
2106 >     */
2107 >    public Enumeration<K> keys() {
2108 >        Node<K,V>[] t;
2109 >        int f = (t = table) == null ? 0 : t.length;
2110 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2111 >    }
2112 >
2113 >    /**
2114 >     * Returns an enumeration of the values in this table.
2115 >     *
2116 >     * @return an enumeration of the values in this table
2117 >     * @see #values()
2118 >     */
2119 >    public Enumeration<V> elements() {
2120 >        Node<K,V>[] t;
2121 >        int f = (t = table) == null ? 0 : t.length;
2122 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2123 >    }
2124 >
2125 >    // ConcurrentHashMap-only methods
2126 >
2127 >    /**
2128 >     * Returns the number of mappings. This method should be used
2129 >     * instead of {@link #size} because a ConcurrentHashMap may
2130 >     * contain more mappings than can be represented as an int. The
2131 >     * value returned is an estimate; the actual count may differ if
2132 >     * there are concurrent insertions or removals.
2133 >     *
2134 >     * @return the number of mappings
2135 >     * @since 1.8
2136 >     */
2137 >    public long mappingCount() {
2138 >        long n = sumCount();
2139 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2140 >    }
2141 >
2142 >    /**
2143 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2144 >     * from the given type to {@code Boolean.TRUE}.
2145 >     *
2146 >     * @param <K> the element type of the returned set
2147 >     * @return the new set
2148 >     * @since 1.8
2149 >     */
2150 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2151 >        return new KeySetView<K,Boolean>
2152 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2153 >    }
2154 >
2155 >    /**
2156 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2157 >     * from the given type to {@code Boolean.TRUE}.
2158 >     *
2159 >     * @param initialCapacity The implementation performs internal
2160 >     * sizing to accommodate this many elements.
2161 >     * @param <K> the element type of the returned set
2162 >     * @return the new set
2163 >     * @throws IllegalArgumentException if the initial capacity of
2164 >     * elements is negative
2165 >     * @since 1.8
2166 >     */
2167 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2168 >        return new KeySetView<K,Boolean>
2169 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2170 >    }
2171 >
2172 >    /**
2173 >     * Returns a {@link Set} view of the keys in this map, using the
2174 >     * given common mapped value for any additions (i.e., {@link
2175 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2176 >     * This is of course only appropriate if it is acceptable to use
2177 >     * the same value for all additions from this view.
2178 >     *
2179 >     * @param mappedValue the mapped value to use for any additions
2180 >     * @return the set view
2181 >     * @throws NullPointerException if the mappedValue is null
2182 >     */
2183 >    public KeySetView<K,V> keySet(V mappedValue) {
2184 >        if (mappedValue == null)
2185 >            throw new NullPointerException();
2186 >        return new KeySetView<K,V>(this, mappedValue);
2187 >    }
2188 >
2189 >    /* ---------------- Special Nodes -------------- */
2190 >
2191 >    /**
2192 >     * A node inserted at head of bins during transfer operations.
2193 >     */
2194 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2195 >        final Node<K,V>[] nextTable;
2196 >        ForwardingNode(Node<K,V>[] tab) {
2197 >            super(MOVED, null, null);
2198 >            this.nextTable = tab;
2199 >        }
2200 >
2201 >        Node<K,V> find(int h, Object k) {
2202 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2203 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2204 >                Node<K,V> e; int n;
2205 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2206 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2207 >                    return null;
2208 >                for (;;) {
2209 >                    int eh; K ek;
2210 >                    if ((eh = e.hash) == h &&
2211 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2212 >                        return e;
2213 >                    if (eh < 0) {
2214 >                        if (e instanceof ForwardingNode) {
2215 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2216 >                            continue outer;
2217                          }
2218                          else
2219 <                            tab = (Node[])fk;
1760 <                    }
1761 <                    else {
1762 <                        int len = 0;
1763 <                        synchronized (f) {
1764 <                            if (tabAt(tab, i) == f) {
1765 <                                len = 1;
1766 <                                for (Node e = f;; ++len) {
1767 <                                    Object ek, ev;
1768 <                                    if (e.hash == h &&
1769 <                                        (ev = e.val) != null &&
1770 <                                        ((ek = e.key) == k || k.equals(ek))) {
1771 <                                        e.val = v;
1772 <                                        break;
1773 <                                    }
1774 <                                    Node last = e;
1775 <                                    if ((e = e.next) == null) {
1776 <                                        ++delta;
1777 <                                        last.next = new Node(h, k, v, null);
1778 <                                        if (len >= TREE_THRESHOLD)
1779 <                                            replaceWithTreeBin(tab, i, k);
1780 <                                        break;
1781 <                                    }
1782 <                                }
1783 <                            }
1784 <                        }
1785 <                        if (len != 0) {
1786 <                            if (len > 1)
1787 <                                addCount(delta, len);
1788 <                            break;
1789 <                        }
2219 >                            return e.find(h, k);
2220                      }
2221 +                    if ((e = e.next) == null)
2222 +                        return null;
2223                  }
2224              }
1793        } finally {
1794            if (delta != 0L)
1795                addCount(delta, 2);
2225          }
1797        if (npe)
1798            throw new NullPointerException();
2226      }
2227  
2228      /**
2229 <     * Implementation for clear. Steps through each bin, removing all
1803 <     * nodes.
2229 >     * A place-holder node used in computeIfAbsent and compute.
2230       */
2231 <    private final void internalClear() {
2232 <        long delta = 0L; // negative number of deletions
2233 <        int i = 0;
2234 <        Node[] tab = table;
2235 <        while (tab != null && i < tab.length) {
2236 <            Node f = tabAt(tab, i);
2237 <            if (f == null)
1812 <                ++i;
1813 <            else if (f.hash < 0) {
1814 <                Object fk;
1815 <                if ((fk = f.key) instanceof TreeBin) {
1816 <                    TreeBin t = (TreeBin)fk;
1817 <                    t.acquire(0);
1818 <                    try {
1819 <                        if (tabAt(tab, i) == f) {
1820 <                            for (Node p = t.first; p != null; p = p.next) {
1821 <                                if (p.val != null) { // (currently always true)
1822 <                                    p.val = null;
1823 <                                    --delta;
1824 <                                }
1825 <                            }
1826 <                            t.first = null;
1827 <                            t.root = null;
1828 <                            ++i;
1829 <                        }
1830 <                    } finally {
1831 <                        t.release(0);
1832 <                    }
1833 <                }
1834 <                else
1835 <                    tab = (Node[])fk;
1836 <            }
1837 <            else {
1838 <                synchronized (f) {
1839 <                    if (tabAt(tab, i) == f) {
1840 <                        for (Node e = f; e != null; e = e.next) {
1841 <                            if (e.val != null) {  // (currently always true)
1842 <                                e.val = null;
1843 <                                --delta;
1844 <                            }
1845 <                        }
1846 <                        setTabAt(tab, i, null);
1847 <                        ++i;
1848 <                    }
1849 <                }
1850 <            }
2231 >    static final class ReservationNode<K,V> extends Node<K,V> {
2232 >        ReservationNode() {
2233 >            super(RESERVED, null, null);
2234 >        }
2235 >
2236 >        Node<K,V> find(int h, Object k) {
2237 >            return null;
2238          }
1852        if (delta != 0L)
1853            addCount(delta, -1);
2239      }
2240  
2241      /* ---------------- Table Initialization and Resizing -------------- */
2242  
2243      /**
2244 <     * Returns a power of two table size for the given desired capacity.
2245 <     * See Hackers Delight, sec 3.2
2244 >     * Returns the stamp bits for resizing a table of size n.
2245 >     * Must be negative when shifted left by RESIZE_STAMP_SHIFT.
2246       */
2247 <    private static final int tableSizeFor(int c) {
2248 <        int n = c - 1;
1864 <        n |= n >>> 1;
1865 <        n |= n >>> 2;
1866 <        n |= n >>> 4;
1867 <        n |= n >>> 8;
1868 <        n |= n >>> 16;
1869 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
2247 >    static final int resizeStamp(int n) {
2248 >        return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
2249      }
2250  
2251      /**
2252       * Initializes table, using the size recorded in sizeCtl.
2253       */
2254 <    private final Node[] initTable() {
2255 <        Node[] tab; int sc;
2256 <        while ((tab = table) == null) {
2254 >    private final Node<K,V>[] initTable() {
2255 >        Node<K,V>[] tab; int sc;
2256 >        while ((tab = table) == null || tab.length == 0) {
2257              if ((sc = sizeCtl) < 0)
2258                  Thread.yield(); // lost initialization race; just spin
2259 <            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2259 >            else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {
2260                  try {
2261 <                    if ((tab = table) == null) {
2261 >                    if ((tab = table) == null || tab.length == 0) {
2262                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2263 <                        tab = table = new Node[n];
2263 >                        @SuppressWarnings("unchecked")
2264 >                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2265 >                        table = tab = nt;
2266                          sc = n - (n >>> 2);
2267                      }
2268                  } finally {
# Line 1904 | Line 2285 | public class ConcurrentHashMap<K, V>
2285       * @param check if <0, don't check resize, if <= 1 only check if uncontended
2286       */
2287      private final void addCount(long x, int check) {
2288 <        CounterCell[] as; long b, s;
2289 <        if ((as = counterCells) != null ||
2290 <            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2291 <            CounterHashCode hc; CounterCell a; long v; int m;
2288 >        CounterCell[] cs; long b, s;
2289 >        if ((cs = counterCells) != null ||
2290 >            !U.compareAndSetLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2291 >            CounterCell c; long v; int m;
2292              boolean uncontended = true;
2293 <            if ((hc = threadCounterHashCode.get()) == null ||
2294 <                as == null || (m = as.length - 1) < 0 ||
1914 <                (a = as[m & hc.code]) == null ||
2293 >            if (cs == null || (m = cs.length - 1) < 0 ||
2294 >                (c = cs[ThreadLocalRandom.getProbe() & m]) == null ||
2295                  !(uncontended =
2296 <                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2297 <                fullAddCount(x, hc, uncontended);
2296 >                  U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))) {
2297 >                fullAddCount(x, uncontended);
2298                  return;
2299              }
2300              if (check <= 1)
# Line 1922 | Line 2302 | public class ConcurrentHashMap<K, V>
2302              s = sumCount();
2303          }
2304          if (check >= 0) {
2305 <            Node[] tab, nt; int sc;
2305 >            Node<K,V>[] tab, nt; int n, sc;
2306              while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2307 <                   tab.length < MAXIMUM_CAPACITY) {
2307 >                   (n = tab.length) < MAXIMUM_CAPACITY) {
2308 >                int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;
2309                  if (sc < 0) {
2310 <                    if (sc == -1 || transferIndex <= transferOrigin ||
2311 <                        (nt = nextTable) == null)
2310 >                    if (sc == rs + MAX_RESIZERS || sc == rs + 1 ||
2311 >                        (nt = nextTable) == null || transferIndex <= 0)
2312                          break;
2313 <                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2313 >                    if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1))
2314                          transfer(tab, nt);
2315                  }
2316 <                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2316 >                else if (U.compareAndSetInt(this, SIZECTL, sc, rs + 2))
2317                      transfer(tab, null);
2318                  s = sumCount();
2319              }
# Line 1940 | Line 2321 | public class ConcurrentHashMap<K, V>
2321      }
2322  
2323      /**
2324 +     * Helps transfer if a resize is in progress.
2325 +     */
2326 +    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2327 +        Node<K,V>[] nextTab; int sc;
2328 +        if (tab != null && (f instanceof ForwardingNode) &&
2329 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2330 +            int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT;
2331 +            while (nextTab == nextTable && table == tab &&
2332 +                   (sc = sizeCtl) < 0) {
2333 +                if (sc == rs + MAX_RESIZERS || sc == rs + 1 ||
2334 +                    transferIndex <= 0)
2335 +                    break;
2336 +                if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) {
2337 +                    transfer(tab, nextTab);
2338 +                    break;
2339 +                }
2340 +            }
2341 +            return nextTab;
2342 +        }
2343 +        return table;
2344 +    }
2345 +
2346 +    /**
2347       * Tries to presize table to accommodate the given number of elements.
2348       *
2349       * @param size number of elements (doesn't need to be perfectly accurate)
# Line 1949 | Line 2353 | public class ConcurrentHashMap<K, V>
2353              tableSizeFor(size + (size >>> 1) + 1);
2354          int sc;
2355          while ((sc = sizeCtl) >= 0) {
2356 <            Node[] tab = table; int n;
2356 >            Node<K,V>[] tab = table; int n;
2357              if (tab == null || (n = tab.length) == 0) {
2358                  n = (sc > c) ? sc : c;
2359 <                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2359 >                if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {
2360                      try {
2361                          if (table == tab) {
2362 <                            table = new Node[n];
2362 >                            @SuppressWarnings("unchecked")
2363 >                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2364 >                            table = nt;
2365                              sc = n - (n >>> 2);
2366                          }
2367                      } finally {
# Line 1965 | Line 2371 | public class ConcurrentHashMap<K, V>
2371              }
2372              else if (c <= sc || n >= MAXIMUM_CAPACITY)
2373                  break;
2374 <            else if (tab == table &&
2375 <                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2376 <                transfer(tab, null);
2374 >            else if (tab == table) {
2375 >                int rs = resizeStamp(n);
2376 >                if (U.compareAndSetInt(this, SIZECTL, sc,
2377 >                                        (rs << RESIZE_STAMP_SHIFT) + 2))
2378 >                    transfer(tab, null);
2379 >            }
2380          }
2381      }
2382  
2383 <    /*
2383 >    /**
2384       * Moves and/or copies the nodes in each bin to new table. See
2385       * above for explanation.
2386       */
2387 <    private final void transfer(Node[] tab, Node[] nextTab) {
2387 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2388          int n = tab.length, stride;
2389          if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2390              stride = MIN_TRANSFER_STRIDE; // subdivide range
2391          if (nextTab == null) {            // initiating
2392              try {
2393 <                nextTab = new Node[n << 1];
2393 >                @SuppressWarnings("unchecked")
2394 >                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
2395 >                nextTab = nt;
2396              } catch (Throwable ex) {      // try to cope with OOME
2397                  sizeCtl = Integer.MAX_VALUE;
2398                  return;
2399              }
2400              nextTable = nextTab;
1990            transferOrigin = n;
2401              transferIndex = n;
1992            Node rev = new Node(MOVED, tab, null, null);
1993            for (int k = n; k > 0;) {    // progressively reveal ready slots
1994                int nextk = (k > stride) ? k - stride : 0;
1995                for (int m = nextk; m < k; ++m)
1996                    nextTab[m] = rev;
1997                for (int m = n + nextk; m < n + k; ++m)
1998                    nextTab[m] = rev;
1999                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
2000            }
2402          }
2403          int nextn = nextTab.length;
2404 <        Node fwd = new Node(MOVED, nextTab, null, null);
2404 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2405          boolean advance = true;
2406 +        boolean finishing = false; // to ensure sweep before committing nextTab
2407          for (int i = 0, bound = 0;;) {
2408 <            int nextIndex, nextBound; Node f; Object fk;
2408 >            Node<K,V> f; int fh;
2409              while (advance) {
2410 <                if (--i >= bound)
2410 >                int nextIndex, nextBound;
2411 >                if (--i >= bound || finishing)
2412                      advance = false;
2413 <                else if ((nextIndex = transferIndex) <= transferOrigin) {
2413 >                else if ((nextIndex = transferIndex) <= 0) {
2414                      i = -1;
2415                      advance = false;
2416                  }
2417 <                else if (U.compareAndSwapInt
2417 >                else if (U.compareAndSetInt
2418                           (this, TRANSFERINDEX, nextIndex,
2419                            nextBound = (nextIndex > stride ?
2420                                         nextIndex - stride : 0))) {
# Line 2021 | Line 2424 | public class ConcurrentHashMap<K, V>
2424                  }
2425              }
2426              if (i < 0 || i >= n || i + n >= nextn) {
2427 <                for (int sc;;) {
2428 <                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2429 <                        if (sc == -1) {
2430 <                            nextTable = null;
2431 <                            table = nextTab;
2432 <                            sizeCtl = (n << 1) - (n >>> 1);
2030 <                        }
2031 <                        return;
2032 <                    }
2427 >                int sc;
2428 >                if (finishing) {
2429 >                    nextTable = null;
2430 >                    table = nextTab;
2431 >                    sizeCtl = (n << 1) - (n >>> 1);
2432 >                    return;
2433                  }
2434 <            }
2435 <            else if ((f = tabAt(tab, i)) == null) {
2436 <                if (casTabAt(tab, i, null, fwd)) {
2437 <                    setTabAt(nextTab, i, null);
2438 <                    setTabAt(nextTab, i + n, null);
2039 <                    advance = true;
2434 >                if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
2435 >                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
2436 >                        return;
2437 >                    finishing = advance = true;
2438 >                    i = n; // recheck before commit
2439                  }
2440              }
2441 <            else if (f.hash >= 0) {
2441 >            else if ((f = tabAt(tab, i)) == null)
2442 >                advance = casTabAt(tab, i, null, fwd);
2443 >            else if ((fh = f.hash) == MOVED)
2444 >                advance = true; // already processed
2445 >            else {
2446                  synchronized (f) {
2447                      if (tabAt(tab, i) == f) {
2448 <                        int runBit = f.hash & n;
2449 <                        Node lastRun = f, lo = null, hi = null;
2450 <                        for (Node p = f.next; p != null; p = p.next) {
2451 <                            int b = p.hash & n;
2452 <                            if (b != runBit) {
2453 <                                runBit = b;
2454 <                                lastRun = p;
2448 >                        Node<K,V> ln, hn;
2449 >                        if (fh >= 0) {
2450 >                            int runBit = fh & n;
2451 >                            Node<K,V> lastRun = f;
2452 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2453 >                                int b = p.hash & n;
2454 >                                if (b != runBit) {
2455 >                                    runBit = b;
2456 >                                    lastRun = p;
2457 >                                }
2458                              }
2459 <                        }
2460 <                        if (runBit == 0)
2461 <                            lo = lastRun;
2056 <                        else
2057 <                            hi = lastRun;
2058 <                        for (Node p = f; p != lastRun; p = p.next) {
2059 <                            int ph = p.hash;
2060 <                            Object pk = p.key, pv = p.val;
2061 <                            if ((ph & n) == 0)
2062 <                                lo = new Node(ph, pk, pv, lo);
2063 <                            else
2064 <                                hi = new Node(ph, pk, pv, hi);
2065 <                        }
2066 <                        setTabAt(nextTab, i, lo);
2067 <                        setTabAt(nextTab, i + n, hi);
2068 <                        setTabAt(tab, i, fwd);
2069 <                        advance = true;
2070 <                    }
2071 <                }
2072 <            }
2073 <            else if ((fk = f.key) instanceof TreeBin) {
2074 <                TreeBin t = (TreeBin)fk;
2075 <                t.acquire(0);
2076 <                try {
2077 <                    if (tabAt(tab, i) == f) {
2078 <                        TreeBin lt = new TreeBin();
2079 <                        TreeBin ht = new TreeBin();
2080 <                        int lc = 0, hc = 0;
2081 <                        for (Node e = t.first; e != null; e = e.next) {
2082 <                            int h = e.hash;
2083 <                            Object k = e.key, v = e.val;
2084 <                            if ((h & n) == 0) {
2085 <                                ++lc;
2086 <                                lt.putTreeNode(h, k, v);
2459 >                            if (runBit == 0) {
2460 >                                ln = lastRun;
2461 >                                hn = null;
2462                              }
2463                              else {
2464 <                                ++hc;
2465 <                                ht.putTreeNode(h, k, v);
2464 >                                hn = lastRun;
2465 >                                ln = null;
2466                              }
2467 +                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2468 +                                int ph = p.hash; K pk = p.key; V pv = p.val;
2469 +                                if ((ph & n) == 0)
2470 +                                    ln = new Node<K,V>(ph, pk, pv, ln);
2471 +                                else
2472 +                                    hn = new Node<K,V>(ph, pk, pv, hn);
2473 +                            }
2474 +                            setTabAt(nextTab, i, ln);
2475 +                            setTabAt(nextTab, i + n, hn);
2476 +                            setTabAt(tab, i, fwd);
2477 +                            advance = true;
2478                          }
2479 <                        Node ln, hn; // throw away trees if too small
2480 <                        if (lc < TREE_THRESHOLD) {
2481 <                            ln = null;
2482 <                            for (Node p = lt.first; p != null; p = p.next)
2483 <                                ln = new Node(p.hash, p.key, p.val, ln);
2484 <                        }
2485 <                        else
2486 <                            ln = new Node(MOVED, lt, null, null);
2487 <                        setTabAt(nextTab, i, ln);
2488 <                        if (hc < TREE_THRESHOLD) {
2489 <                            hn = null;
2490 <                            for (Node p = ht.first; p != null; p = p.next)
2491 <                                hn = new Node(p.hash, p.key, p.val, hn);
2479 >                        else if (f instanceof TreeBin) {
2480 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2481 >                            TreeNode<K,V> lo = null, loTail = null;
2482 >                            TreeNode<K,V> hi = null, hiTail = null;
2483 >                            int lc = 0, hc = 0;
2484 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2485 >                                int h = e.hash;
2486 >                                TreeNode<K,V> p = new TreeNode<K,V>
2487 >                                    (h, e.key, e.val, null, null);
2488 >                                if ((h & n) == 0) {
2489 >                                    if ((p.prev = loTail) == null)
2490 >                                        lo = p;
2491 >                                    else
2492 >                                        loTail.next = p;
2493 >                                    loTail = p;
2494 >                                    ++lc;
2495 >                                }
2496 >                                else {
2497 >                                    if ((p.prev = hiTail) == null)
2498 >                                        hi = p;
2499 >                                    else
2500 >                                        hiTail.next = p;
2501 >                                    hiTail = p;
2502 >                                    ++hc;
2503 >                                }
2504 >                            }
2505 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2506 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2507 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2508 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2509 >                            setTabAt(nextTab, i, ln);
2510 >                            setTabAt(nextTab, i + n, hn);
2511 >                            setTabAt(tab, i, fwd);
2512 >                            advance = true;
2513                          }
2514 <                        else
2515 <                            hn = new Node(MOVED, ht, null, null);
2109 <                        setTabAt(nextTab, i + n, hn);
2110 <                        setTabAt(tab, i, fwd);
2111 <                        advance = true;
2514 >                        else if (f instanceof ReservationNode)
2515 >                            throw new IllegalStateException("Recursive update");
2516                      }
2113                } finally {
2114                    t.release(0);
2517                  }
2518              }
2117            else
2118                advance = true; // already processed
2519          }
2520      }
2521  
2522      /* ---------------- Counter support -------------- */
2523  
2524 +    /**
2525 +     * A padded cell for distributing counts.  Adapted from LongAdder
2526 +     * and Striped64.  See their internal docs for explanation.
2527 +     */
2528 +    @jdk.internal.vm.annotation.Contended static final class CounterCell {
2529 +        volatile long value;
2530 +        CounterCell(long x) { value = x; }
2531 +    }
2532 +
2533      final long sumCount() {
2534 <        CounterCell[] as = counterCells; CounterCell a;
2534 >        CounterCell[] cs = counterCells;
2535          long sum = baseCount;
2536 <        if (as != null) {
2537 <            for (int i = 0; i < as.length; ++i) {
2538 <                if ((a = as[i]) != null)
2539 <                    sum += a.value;
2131 <            }
2536 >        if (cs != null) {
2537 >            for (CounterCell c : cs)
2538 >                if (c != null)
2539 >                    sum += c.value;
2540          }
2541          return sum;
2542      }
2543  
2544      // See LongAdder version for explanation
2545 <    private final void fullAddCount(long x, CounterHashCode hc,
2138 <                                    boolean wasUncontended) {
2545 >    private final void fullAddCount(long x, boolean wasUncontended) {
2546          int h;
2547 <        if (hc == null) {
2548 <            hc = new CounterHashCode();
2549 <            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
2550 <            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
2144 <            threadCounterHashCode.set(hc);
2547 >        if ((h = ThreadLocalRandom.getProbe()) == 0) {
2548 >            ThreadLocalRandom.localInit();      // force initialization
2549 >            h = ThreadLocalRandom.getProbe();
2550 >            wasUncontended = true;
2551          }
2146        else
2147            h = hc.code;
2552          boolean collide = false;                // True if last slot nonempty
2553          for (;;) {
2554 <            CounterCell[] as; CounterCell a; int n; long v;
2555 <            if ((as = counterCells) != null && (n = as.length) > 0) {
2556 <                if ((a = as[(n - 1) & h]) == null) {
2557 <                    if (counterBusy == 0) {            // Try to attach new Cell
2554 >            CounterCell[] cs; CounterCell c; int n; long v;
2555 >            if ((cs = counterCells) != null && (n = cs.length) > 0) {
2556 >                if ((c = cs[(n - 1) & h]) == null) {
2557 >                    if (cellsBusy == 0) {            // Try to attach new Cell
2558                          CounterCell r = new CounterCell(x); // Optimistic create
2559 <                        if (counterBusy == 0 &&
2560 <                            U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2559 >                        if (cellsBusy == 0 &&
2560 >                            U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {
2561                              boolean created = false;
2562                              try {               // Recheck under lock
2563                                  CounterCell[] rs; int m, j;
# Line 2164 | Line 2568 | public class ConcurrentHashMap<K, V>
2568                                      created = true;
2569                                  }
2570                              } finally {
2571 <                                counterBusy = 0;
2571 >                                cellsBusy = 0;
2572                              }
2573                              if (created)
2574                                  break;
# Line 2175 | Line 2579 | public class ConcurrentHashMap<K, V>
2579                  }
2580                  else if (!wasUncontended)       // CAS already known to fail
2581                      wasUncontended = true;      // Continue after rehash
2582 <                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2582 >                else if (U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))
2583                      break;
2584 <                else if (counterCells != as || n >= NCPU)
2584 >                else if (counterCells != cs || n >= NCPU)
2585                      collide = false;            // At max size or stale
2586                  else if (!collide)
2587                      collide = true;
2588 <                else if (counterBusy == 0 &&
2589 <                         U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2588 >                else if (cellsBusy == 0 &&
2589 >                         U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {
2590                      try {
2591 <                        if (counterCells == as) {// Expand table unless stale
2592 <                            CounterCell[] rs = new CounterCell[n << 1];
2189 <                            for (int i = 0; i < n; ++i)
2190 <                                rs[i] = as[i];
2191 <                            counterCells = rs;
2192 <                        }
2591 >                        if (counterCells == cs) // Expand table unless stale
2592 >                            counterCells = Arrays.copyOf(cs, n << 1);
2593                      } finally {
2594 <                        counterBusy = 0;
2594 >                        cellsBusy = 0;
2595                      }
2596                      collide = false;
2597                      continue;                   // Retry with expanded table
2598                  }
2599 <                h ^= h << 13;                   // Rehash
2200 <                h ^= h >>> 17;
2201 <                h ^= h << 5;
2599 >                h = ThreadLocalRandom.advanceProbe(h);
2600              }
2601 <            else if (counterBusy == 0 && counterCells == as &&
2602 <                     U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2601 >            else if (cellsBusy == 0 && counterCells == cs &&
2602 >                     U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {
2603                  boolean init = false;
2604                  try {                           // Initialize table
2605 <                    if (counterCells == as) {
2605 >                    if (counterCells == cs) {
2606                          CounterCell[] rs = new CounterCell[2];
2607                          rs[h & 1] = new CounterCell(x);
2608                          counterCells = rs;
2609                          init = true;
2610                      }
2611                  } finally {
2612 <                    counterBusy = 0;
2612 >                    cellsBusy = 0;
2613                  }
2614                  if (init)
2615                      break;
2616              }
2617 <            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2617 >            else if (U.compareAndSetLong(this, BASECOUNT, v = baseCount, v + x))
2618                  break;                          // Fall back on using base
2619          }
2222        hc.code = h;                            // Record index for next time
2620      }
2621  
2622 <    /* ----------------Table Traversal -------------- */
2622 >    /* ---------------- Conversion from/to TreeBins -------------- */
2623  
2624      /**
2625 <     * Encapsulates traversal for methods such as containsValue; also
2626 <     * serves as a base class for other iterators and bulk tasks.
2627 <     *
2628 <     * At each step, the iterator snapshots the key ("nextKey") and
2629 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2630 <     * snapshot, has a non-null user value). Because val fields can
2631 <     * change (including to null, indicating deletion), field nextVal
2632 <     * might not be accurate at point of use, but still maintains the
2633 <     * weak consistency property of holding a value that was once
2634 <     * valid. To support iterator.remove, the nextKey field is not
2635 <     * updated (nulled out) when the iterator cannot advance.
2636 <     *
2637 <     * Internal traversals directly access these fields, as in:
2638 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2639 <     *
2640 <     * Exported iterators must track whether the iterator has advanced
2641 <     * (in hasNext vs next) (by setting/checking/nulling field
2642 <     * nextVal), and then extract key, value, or key-value pairs as
2643 <     * return values of next().
2644 <     *
2645 <     * The iterator visits once each still-valid node that was
2249 <     * reachable upon iterator construction. It might miss some that
2250 <     * were added to a bin after the bin was visited, which is OK wrt
2251 <     * consistency guarantees. Maintaining this property in the face
2252 <     * of possible ongoing resizes requires a fair amount of
2253 <     * bookkeeping state that is difficult to optimize away amidst
2254 <     * volatile accesses.  Even so, traversal maintains reasonable
2255 <     * throughput.
2256 <     *
2257 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2258 <     * However, if the table has been resized, then all future steps
2259 <     * must traverse both the bin at the current index as well as at
2260 <     * (index + baseSize); and so on for further resizings. To
2261 <     * paranoically cope with potential sharing by users of iterators
2262 <     * across threads, iteration terminates if a bounds checks fails
2263 <     * for a table read.
2264 <     *
2265 <     * This class extends CountedCompleter to streamline parallel
2266 <     * iteration in bulk operations. This adds only a few fields of
2267 <     * space overhead, which is small enough in cases where it is not
2268 <     * needed to not worry about it.  Because CountedCompleter is
2269 <     * Serializable, but iterators need not be, we need to add warning
2270 <     * suppressions.
2271 <     */
2272 <    @SuppressWarnings("serial") static class Traverser<K,V,R>
2273 <        extends CountedCompleter<R> {
2274 <        final ConcurrentHashMap<K, V> map;
2275 <        Node next;           // the next entry to use
2276 <        Object nextKey;      // cached key field of next
2277 <        Object nextVal;      // cached val field of next
2278 <        Node[] tab;          // current table; updated if resized
2279 <        int index;           // index of bin to use next
2280 <        int baseIndex;       // current index of initial table
2281 <        int baseLimit;       // index bound for initial table
2282 <        int baseSize;        // initial table size
2283 <        int batch;           // split control
2284 <
2285 <        /** Creates iterator for all entries in the table. */
2286 <        Traverser(ConcurrentHashMap<K, V> map) {
2287 <            this.map = map;
2288 <        }
2289 <
2290 <        /** Creates iterator for split() methods and task constructors */
2291 <        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it, int batch) {
2292 <            super(it);
2293 <            this.batch = batch;
2294 <            if ((this.map = map) != null && it != null) { // split parent
2295 <                Node[] t;
2296 <                if ((t = it.tab) == null &&
2297 <                    (t = it.tab = map.table) != null)
2298 <                    it.baseLimit = it.baseSize = t.length;
2299 <                this.tab = t;
2300 <                this.baseSize = it.baseSize;
2301 <                int hi = this.baseLimit = it.baseLimit;
2302 <                it.baseLimit = this.index = this.baseIndex =
2303 <                    (hi + it.baseIndex + 1) >>> 1;
2304 <            }
2305 <        }
2306 <
2307 <        /**
2308 <         * Advances next; returns nextVal or null if terminated.
2309 <         * See above for explanation.
2310 <         */
2311 <        final Object advance() {
2312 <            Node e = next;
2313 <            Object ev = null;
2314 <            outer: do {
2315 <                if (e != null)                  // advance past used/skipped node
2316 <                    e = e.next;
2317 <                while (e == null) {             // get to next non-null bin
2318 <                    ConcurrentHashMap<K, V> m;
2319 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2320 <                    if ((t = tab) != null)
2321 <                        n = t.length;
2322 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2323 <                        n = baseLimit = baseSize = t.length;
2324 <                    else
2325 <                        break outer;
2326 <                    if ((b = baseIndex) >= baseLimit ||
2327 <                        (i = index) < 0 || i >= n)
2328 <                        break outer;
2329 <                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2330 <                        if ((ek = e.key) instanceof TreeBin)
2331 <                            e = ((TreeBin)ek).first;
2332 <                        else {
2333 <                            tab = (Node[])ek;
2334 <                            continue;           // restarts due to null val
2625 >     * Replaces all linked nodes in bin at given index unless table is
2626 >     * too small, in which case resizes instead.
2627 >     */
2628 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2629 >        Node<K,V> b; int n;
2630 >        if (tab != null) {
2631 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
2632 >                tryPresize(n << 1);
2633 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2634 >                synchronized (b) {
2635 >                    if (tabAt(tab, index) == b) {
2636 >                        TreeNode<K,V> hd = null, tl = null;
2637 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2638 >                            TreeNode<K,V> p =
2639 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2640 >                                                  null, null);
2641 >                            if ((p.prev = tl) == null)
2642 >                                hd = p;
2643 >                            else
2644 >                                tl.next = p;
2645 >                            tl = p;
2646                          }
2647 <                    }                           // visit upper slots if present
2648 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2647 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2648 >                    }
2649                  }
2650 <                nextKey = e.key;
2340 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2341 <            next = e;
2342 <            return nextVal = ev;
2343 <        }
2344 <
2345 <        public final void remove() {
2346 <            Object k = nextKey;
2347 <            if (k == null && (advance() == null || (k = nextKey) == null))
2348 <                throw new IllegalStateException();
2349 <            map.internalReplace(k, null, null);
2350 <        }
2351 <
2352 <        public final boolean hasNext() {
2353 <            return nextVal != null || advance() != null;
2354 <        }
2355 <
2356 <        public final boolean hasMoreElements() { return hasNext(); }
2357 <
2358 <        public void compute() { } // default no-op CountedCompleter body
2359 <
2360 <        /**
2361 <         * Returns a batch value > 0 if this task should (and must) be
2362 <         * split, if so, adding to pending count, and in any case
2363 <         * updating batch value. The initial batch value is approx
2364 <         * exp2 of the number of times (minus one) to split task by
2365 <         * two before executing leaf action. This value is faster to
2366 <         * compute and more convenient to use as a guide to splitting
2367 <         * than is the depth, since it is used while dividing by two
2368 <         * anyway.
2369 <         */
2370 <        final int preSplit() {
2371 <            ConcurrentHashMap<K, V> m; int b; Node[] t;  ForkJoinPool pool;
2372 <            if ((b = batch) < 0 && (m = map) != null) { // force initialization
2373 <                if ((t = tab) == null && (t = tab = m.table) != null)
2374 <                    baseLimit = baseSize = t.length;
2375 <                if (t != null) {
2376 <                    long n = m.sumCount();
2377 <                    int par = ((pool = getPool()) == null) ?
2378 <                        ForkJoinPool.getCommonPoolParallelism() :
2379 <                        pool.getParallelism();
2380 <                    int sp = par << 3; // slack of 8
2381 <                    b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2382 <                }
2383 <            }
2384 <            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2385 <            if ((batch = b) > 0)
2386 <                addToPendingCount(1);
2387 <            return b;
2650 >            }
2651          }
2389
2390    }
2391
2392    /* ---------------- Public operations -------------- */
2393
2394    /**
2395     * Creates a new, empty map with the default initial table size (16).
2396     */
2397    public ConcurrentHashMap() {
2398    }
2399
2400    /**
2401     * Creates a new, empty map with an initial table size
2402     * accommodating the specified number of elements without the need
2403     * to dynamically resize.
2404     *
2405     * @param initialCapacity The implementation performs internal
2406     * sizing to accommodate this many elements.
2407     * @throws IllegalArgumentException if the initial capacity of
2408     * elements is negative
2409     */
2410    public ConcurrentHashMap(int initialCapacity) {
2411        if (initialCapacity < 0)
2412            throw new IllegalArgumentException();
2413        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2414                   MAXIMUM_CAPACITY :
2415                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2416        this.sizeCtl = cap;
2652      }
2653  
2654      /**
2655 <     * Creates a new map with the same mappings as the given map.
2421 <     *
2422 <     * @param m the map
2655 >     * Returns a list of non-TreeNodes replacing those in given list.
2656       */
2657 <    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2658 <        this.sizeCtl = DEFAULT_CAPACITY;
2659 <        internalPutAll(m);
2660 <    }
2661 <
2662 <    /**
2663 <     * Creates a new, empty map with an initial table size based on
2664 <     * the given number of elements ({@code initialCapacity}) and
2665 <     * initial table density ({@code loadFactor}).
2666 <     *
2667 <     * @param initialCapacity the initial capacity. The implementation
2435 <     * performs internal sizing to accommodate this many elements,
2436 <     * given the specified load factor.
2437 <     * @param loadFactor the load factor (table density) for
2438 <     * establishing the initial table size
2439 <     * @throws IllegalArgumentException if the initial capacity of
2440 <     * elements is negative or the load factor is nonpositive
2441 <     *
2442 <     * @since 1.6
2443 <     */
2444 <    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
2445 <        this(initialCapacity, loadFactor, 1);
2446 <    }
2447 <
2448 <    /**
2449 <     * Creates a new, empty map with an initial table size based on
2450 <     * the given number of elements ({@code initialCapacity}), table
2451 <     * density ({@code loadFactor}), and number of concurrently
2452 <     * updating threads ({@code concurrencyLevel}).
2453 <     *
2454 <     * @param initialCapacity the initial capacity. The implementation
2455 <     * performs internal sizing to accommodate this many elements,
2456 <     * given the specified load factor.
2457 <     * @param loadFactor the load factor (table density) for
2458 <     * establishing the initial table size
2459 <     * @param concurrencyLevel the estimated number of concurrently
2460 <     * updating threads. The implementation may use this value as
2461 <     * a sizing hint.
2462 <     * @throws IllegalArgumentException if the initial capacity is
2463 <     * negative or the load factor or concurrencyLevel are
2464 <     * nonpositive
2465 <     */
2466 <    public ConcurrentHashMap(int initialCapacity,
2467 <                               float loadFactor, int concurrencyLevel) {
2468 <        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2469 <            throw new IllegalArgumentException();
2470 <        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2471 <            initialCapacity = concurrencyLevel;   // as estimated threads
2472 <        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2473 <        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2474 <            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2475 <        this.sizeCtl = cap;
2476 <    }
2477 <
2478 <    /**
2479 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2480 <     * from the given type to {@code Boolean.TRUE}.
2481 <     *
2482 <     * @return the new set
2483 <     */
2484 <    public static <K> KeySetView<K,Boolean> newKeySet() {
2485 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(),
2486 <                                      Boolean.TRUE);
2487 <    }
2488 <
2489 <    /**
2490 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2491 <     * from the given type to {@code Boolean.TRUE}.
2492 <     *
2493 <     * @param initialCapacity The implementation performs internal
2494 <     * sizing to accommodate this many elements.
2495 <     * @throws IllegalArgumentException if the initial capacity of
2496 <     * elements is negative
2497 <     * @return the new set
2498 <     */
2499 <    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2500 <        return new KeySetView<K,Boolean>
2501 <            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2657 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2658 >        Node<K,V> hd = null, tl = null;
2659 >        for (Node<K,V> q = b; q != null; q = q.next) {
2660 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val);
2661 >            if (tl == null)
2662 >                hd = p;
2663 >            else
2664 >                tl.next = p;
2665 >            tl = p;
2666 >        }
2667 >        return hd;
2668      }
2669  
2670 <    /**
2505 <     * {@inheritDoc}
2506 <     */
2507 <    public boolean isEmpty() {
2508 <        return sumCount() <= 0L; // ignore transient negative values
2509 <    }
2670 >    /* ---------------- TreeNodes -------------- */
2671  
2672      /**
2673 <     * {@inheritDoc}
2673 >     * Nodes for use in TreeBins.
2674       */
2675 <    public int size() {
2676 <        long n = sumCount();
2677 <        return ((n < 0L) ? 0 :
2678 <                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2679 <                (int)n);
2680 <    }
2675 >    static final class TreeNode<K,V> extends Node<K,V> {
2676 >        TreeNode<K,V> parent;  // red-black tree links
2677 >        TreeNode<K,V> left;
2678 >        TreeNode<K,V> right;
2679 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2680 >        boolean red;
2681  
2682 <    /**
2683 <     * Returns the number of mappings. This method should be used
2684 <     * instead of {@link #size} because a ConcurrentHashMap may
2685 <     * contain more mappings than can be represented as an int. The
2686 <     * value returned is an estimate; the actual count may differ if
2526 <     * there are concurrent insertions or removals.
2527 <     *
2528 <     * @return the number of mappings
2529 <     */
2530 <    public long mappingCount() {
2531 <        long n = sumCount();
2532 <        return (n < 0L) ? 0L : n; // ignore transient negative values
2533 <    }
2682 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2683 >                 TreeNode<K,V> parent) {
2684 >            super(hash, key, val, next);
2685 >            this.parent = parent;
2686 >        }
2687  
2688 <    /**
2689 <     * Returns the value to which the specified key is mapped,
2690 <     * or {@code null} if this map contains no mapping for the key.
2538 <     *
2539 <     * <p>More formally, if this map contains a mapping from a key
2540 <     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2541 <     * then this method returns {@code v}; otherwise it returns
2542 <     * {@code null}.  (There can be at most one such mapping.)
2543 <     *
2544 <     * @throws NullPointerException if the specified key is null
2545 <     */
2546 <    public V get(Object key) {
2547 <        return internalGet(key);
2548 <    }
2688 >        Node<K,V> find(int h, Object k) {
2689 >            return findTreeNode(h, k, null);
2690 >        }
2691  
2692 <    /**
2693 <     * Returns the value to which the specified key is mapped,
2694 <     * or the given defaultValue if this map contains no mapping for the key.
2695 <     *
2696 <     * @param key the key
2697 <     * @param defaultValue the value to return if this map contains
2698 <     * no mapping for the given key
2699 <     * @return the mapping for the key, if present; else the defaultValue
2700 <     * @throws NullPointerException if the specified key is null
2701 <     */
2702 <    public V getValueOrDefault(Object key, V defaultValue) {
2703 <        V v;
2704 <        return (v = internalGet(key)) == null ? defaultValue : v;
2692 >        /**
2693 >         * Returns the TreeNode (or null if not found) for the given key
2694 >         * starting at given root.
2695 >         */
2696 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2697 >            if (k != null) {
2698 >                TreeNode<K,V> p = this;
2699 >                do {
2700 >                    int ph, dir; K pk; TreeNode<K,V> q;
2701 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2702 >                    if ((ph = p.hash) > h)
2703 >                        p = pl;
2704 >                    else if (ph < h)
2705 >                        p = pr;
2706 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2707 >                        return p;
2708 >                    else if (pl == null)
2709 >                        p = pr;
2710 >                    else if (pr == null)
2711 >                        p = pl;
2712 >                    else if ((kc != null ||
2713 >                              (kc = comparableClassFor(k)) != null) &&
2714 >                             (dir = compareComparables(kc, k, pk)) != 0)
2715 >                        p = (dir < 0) ? pl : pr;
2716 >                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
2717 >                        return q;
2718 >                    else
2719 >                        p = pl;
2720 >                } while (p != null);
2721 >            }
2722 >            return null;
2723 >        }
2724      }
2725  
2726 <    /**
2566 <     * Tests if the specified object is a key in this table.
2567 <     *
2568 <     * @param  key   possible key
2569 <     * @return {@code true} if and only if the specified object
2570 <     *         is a key in this table, as determined by the
2571 <     *         {@code equals} method; {@code false} otherwise
2572 <     * @throws NullPointerException if the specified key is null
2573 <     */
2574 <    public boolean containsKey(Object key) {
2575 <        return internalGet(key) != null;
2576 <    }
2726 >    /* ---------------- TreeBins -------------- */
2727  
2728      /**
2729 <     * Returns {@code true} if this map maps one or more keys to the
2730 <     * specified value. Note: This method may require a full traversal
2731 <     * of the map, and is much slower than method {@code containsKey}.
2732 <     *
2733 <     * @param value value whose presence in this map is to be tested
2734 <     * @return {@code true} if this map maps one or more keys to the
2735 <     *         specified value
2736 <     * @throws NullPointerException if the specified value is null
2737 <     */
2738 <    public boolean containsValue(Object value) {
2739 <        if (value == null)
2740 <            throw new NullPointerException();
2741 <        Object v;
2742 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2743 <        while ((v = it.advance()) != null) {
2744 <            if (v == value || value.equals(v))
2745 <                return true;
2729 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2730 >     * keys or values, but instead point to list of TreeNodes and
2731 >     * their root. They also maintain a parasitic read-write lock
2732 >     * forcing writers (who hold bin lock) to wait for readers (who do
2733 >     * not) to complete before tree restructuring operations.
2734 >     */
2735 >    static final class TreeBin<K,V> extends Node<K,V> {
2736 >        TreeNode<K,V> root;
2737 >        volatile TreeNode<K,V> first;
2738 >        volatile Thread waiter;
2739 >        volatile int lockState;
2740 >        // values for lockState
2741 >        static final int WRITER = 1; // set while holding write lock
2742 >        static final int WAITER = 2; // set when waiting for write lock
2743 >        static final int READER = 4; // increment value for setting read lock
2744 >
2745 >        /**
2746 >         * Tie-breaking utility for ordering insertions when equal
2747 >         * hashCodes and non-comparable. We don't require a total
2748 >         * order, just a consistent insertion rule to maintain
2749 >         * equivalence across rebalancings. Tie-breaking further than
2750 >         * necessary simplifies testing a bit.
2751 >         */
2752 >        static int tieBreakOrder(Object a, Object b) {
2753 >            int d;
2754 >            if (a == null || b == null ||
2755 >                (d = a.getClass().getName().
2756 >                 compareTo(b.getClass().getName())) == 0)
2757 >                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2758 >                     -1 : 1);
2759 >            return d;
2760          }
2597        return false;
2598    }
2599
2600    /**
2601     * Legacy method testing if some key maps into the specified value
2602     * in this table.  This method is identical in functionality to
2603     * {@link #containsValue}, and exists solely to ensure
2604     * full compatibility with class {@link java.util.Hashtable},
2605     * which supported this method prior to introduction of the
2606     * Java Collections framework.
2607     *
2608     * @param  value a value to search for
2609     * @return {@code true} if and only if some key maps to the
2610     *         {@code value} argument in this table as
2611     *         determined by the {@code equals} method;
2612     *         {@code false} otherwise
2613     * @throws NullPointerException if the specified value is null
2614     */
2615    public boolean contains(Object value) {
2616        return containsValue(value);
2617    }
2761  
2762 <    /**
2763 <     * Maps the specified key to the specified value in this table.
2764 <     * Neither the key nor the value can be null.
2765 <     *
2766 <     * <p>The value can be retrieved by calling the {@code get} method
2767 <     * with a key that is equal to the original key.
2768 <     *
2769 <     * @param key key with which the specified value is to be associated
2770 <     * @param value value to be associated with the specified key
2771 <     * @return the previous value associated with {@code key}, or
2772 <     *         {@code null} if there was no mapping for {@code key}
2773 <     * @throws NullPointerException if the specified key or value is null
2774 <     */
2775 <    public V put(K key, V value) {
2776 <        return internalPut(key, value, false);
2777 <    }
2762 >        /**
2763 >         * Creates bin with initial set of nodes headed by b.
2764 >         */
2765 >        TreeBin(TreeNode<K,V> b) {
2766 >            super(TREEBIN, null, null);
2767 >            this.first = b;
2768 >            TreeNode<K,V> r = null;
2769 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2770 >                next = (TreeNode<K,V>)x.next;
2771 >                x.left = x.right = null;
2772 >                if (r == null) {
2773 >                    x.parent = null;
2774 >                    x.red = false;
2775 >                    r = x;
2776 >                }
2777 >                else {
2778 >                    K k = x.key;
2779 >                    int h = x.hash;
2780 >                    Class<?> kc = null;
2781 >                    for (TreeNode<K,V> p = r;;) {
2782 >                        int dir, ph;
2783 >                        K pk = p.key;
2784 >                        if ((ph = p.hash) > h)
2785 >                            dir = -1;
2786 >                        else if (ph < h)
2787 >                            dir = 1;
2788 >                        else if ((kc == null &&
2789 >                                  (kc = comparableClassFor(k)) == null) ||
2790 >                                 (dir = compareComparables(kc, k, pk)) == 0)
2791 >                            dir = tieBreakOrder(k, pk);
2792 >                        TreeNode<K,V> xp = p;
2793 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2794 >                            x.parent = xp;
2795 >                            if (dir <= 0)
2796 >                                xp.left = x;
2797 >                            else
2798 >                                xp.right = x;
2799 >                            r = balanceInsertion(r, x);
2800 >                            break;
2801 >                        }
2802 >                    }
2803 >                }
2804 >            }
2805 >            this.root = r;
2806 >            assert checkInvariants(root);
2807 >        }
2808  
2809 <    /**
2810 <     * {@inheritDoc}
2811 <     *
2812 <     * @return the previous value associated with the specified key,
2813 <     *         or {@code null} if there was no mapping for the key
2814 <     * @throws NullPointerException if the specified key or value is null
2815 <     */
2643 <    public V putIfAbsent(K key, V value) {
2644 <        return internalPut(key, value, true);
2645 <    }
2809 >        /**
2810 >         * Acquires write lock for tree restructuring.
2811 >         */
2812 >        private final void lockRoot() {
2813 >            if (!U.compareAndSetInt(this, LOCKSTATE, 0, WRITER))
2814 >                contendedLock(); // offload to separate method
2815 >        }
2816  
2817 <    /**
2818 <     * Copies all of the mappings from the specified map to this one.
2819 <     * These mappings replace any mappings that this map had for any of the
2820 <     * keys currently in the specified map.
2821 <     *
2822 <     * @param m mappings to be stored in this map
2653 <     */
2654 <    public void putAll(Map<? extends K, ? extends V> m) {
2655 <        internalPutAll(m);
2656 <    }
2817 >        /**
2818 >         * Releases write lock for tree restructuring.
2819 >         */
2820 >        private final void unlockRoot() {
2821 >            lockState = 0;
2822 >        }
2823  
2824 <    /**
2825 <     * If the specified key is not already associated with a value,
2826 <     * computes its value using the given mappingFunction and enters
2827 <     * it into the map unless null.  This is equivalent to
2828 <     * <pre> {@code
2829 <     * if (map.containsKey(key))
2830 <     *   return map.get(key);
2831 <     * value = mappingFunction.apply(key);
2832 <     * if (value != null)
2833 <     *   map.put(key, value);
2834 <     * return value;}</pre>
2835 <     *
2836 <     * except that the action is performed atomically.  If the
2837 <     * function returns {@code null} no mapping is recorded. If the
2838 <     * function itself throws an (unchecked) exception, the exception
2839 <     * is rethrown to its caller, and no mapping is recorded.  Some
2840 <     * attempted update operations on this map by other threads may be
2841 <     * blocked while computation is in progress, so the computation
2842 <     * should be short and simple, and must not attempt to update any
2843 <     * other mappings of this Map. The most appropriate usage is to
2844 <     * construct a new object serving as an initial mapped value, or
2845 <     * memoized result, as in:
2846 <     *
2681 <     *  <pre> {@code
2682 <     * map.computeIfAbsent(key, new Fun<K, V>() {
2683 <     *   public V map(K k) { return new Value(f(k)); }});}</pre>
2684 <     *
2685 <     * @param key key with which the specified value is to be associated
2686 <     * @param mappingFunction the function to compute a value
2687 <     * @return the current (existing or computed) value associated with
2688 <     *         the specified key, or null if the computed value is null
2689 <     * @throws NullPointerException if the specified key or mappingFunction
2690 <     *         is null
2691 <     * @throws IllegalStateException if the computation detectably
2692 <     *         attempts a recursive update to this map that would
2693 <     *         otherwise never complete
2694 <     * @throws RuntimeException or Error if the mappingFunction does so,
2695 <     *         in which case the mapping is left unestablished
2696 <     */
2697 <    public V computeIfAbsent
2698 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
2699 <        return internalComputeIfAbsent(key, mappingFunction);
2700 <    }
2824 >        /**
2825 >         * Possibly blocks awaiting root lock.
2826 >         */
2827 >        private final void contendedLock() {
2828 >            boolean waiting = false;
2829 >            for (int s;;) {
2830 >                if (((s = lockState) & ~WAITER) == 0) {
2831 >                    if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {
2832 >                        if (waiting)
2833 >                            waiter = null;
2834 >                        return;
2835 >                    }
2836 >                }
2837 >                else if ((s & WAITER) == 0) {
2838 >                    if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {
2839 >                        waiting = true;
2840 >                        waiter = Thread.currentThread();
2841 >                    }
2842 >                }
2843 >                else if (waiting)
2844 >                    LockSupport.park(this);
2845 >            }
2846 >        }
2847  
2848 <    /**
2849 <     * If the given key is present, computes a new mapping value given a key and
2850 <     * its current mapped value. This is equivalent to
2851 <     *  <pre> {@code
2852 <     *   if (map.containsKey(key)) {
2853 <     *     value = remappingFunction.apply(key, map.get(key));
2854 <     *     if (value != null)
2855 <     *       map.put(key, value);
2856 <     *     else
2857 <     *       map.remove(key);
2858 <     *   }
2859 <     * }</pre>
2860 <     *
2861 <     * except that the action is performed atomically.  If the
2862 <     * function returns {@code null}, the mapping is removed.  If the
2863 <     * function itself throws an (unchecked) exception, the exception
2864 <     * is rethrown to its caller, and the current mapping is left
2865 <     * unchanged.  Some attempted update operations on this map by
2866 <     * other threads may be blocked while computation is in progress,
2867 <     * so the computation should be short and simple, and must not
2868 <     * attempt to update any other mappings of this Map. For example,
2869 <     * to either create or append new messages to a value mapping:
2870 <     *
2871 <     * @param key key with which the specified value is to be associated
2872 <     * @param remappingFunction the function to compute a value
2873 <     * @return the new value associated with the specified key, or null if none
2874 <     * @throws NullPointerException if the specified key or remappingFunction
2875 <     *         is null
2876 <     * @throws IllegalStateException if the computation detectably
2877 <     *         attempts a recursive update to this map that would
2878 <     *         otherwise never complete
2879 <     * @throws RuntimeException or Error if the remappingFunction does so,
2880 <     *         in which case the mapping is unchanged
2735 <     */
2736 <    public V computeIfPresent
2737 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2738 <        return internalCompute(key, true, remappingFunction);
2739 <    }
2848 >        /**
2849 >         * Returns matching node or null if none. Tries to search
2850 >         * using tree comparisons from root, but continues linear
2851 >         * search when lock not available.
2852 >         */
2853 >        final Node<K,V> find(int h, Object k) {
2854 >            if (k != null) {
2855 >                for (Node<K,V> e = first; e != null; ) {
2856 >                    int s; K ek;
2857 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2858 >                        if (e.hash == h &&
2859 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2860 >                            return e;
2861 >                        e = e.next;
2862 >                    }
2863 >                    else if (U.compareAndSetInt(this, LOCKSTATE, s,
2864 >                                                 s + READER)) {
2865 >                        TreeNode<K,V> r, p;
2866 >                        try {
2867 >                            p = ((r = root) == null ? null :
2868 >                                 r.findTreeNode(h, k, null));
2869 >                        } finally {
2870 >                            Thread w;
2871 >                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2872 >                                (READER|WAITER) && (w = waiter) != null)
2873 >                                LockSupport.unpark(w);
2874 >                        }
2875 >                        return p;
2876 >                    }
2877 >                }
2878 >            }
2879 >            return null;
2880 >        }
2881  
2882 <    /**
2883 <     * Computes a new mapping value given a key and
2884 <     * its current mapped value (or {@code null} if there is no current
2885 <     * mapping). This is equivalent to
2886 <     *  <pre> {@code
2887 <     *   value = remappingFunction.apply(key, map.get(key));
2888 <     *   if (value != null)
2889 <     *     map.put(key, value);
2890 <     *   else
2891 <     *     map.remove(key);
2892 <     * }</pre>
2893 <     *
2894 <     * except that the action is performed atomically.  If the
2895 <     * function returns {@code null}, the mapping is removed.  If the
2896 <     * function itself throws an (unchecked) exception, the exception
2897 <     * is rethrown to its caller, and the current mapping is left
2898 <     * unchanged.  Some attempted update operations on this map by
2899 <     * other threads may be blocked while computation is in progress,
2900 <     * so the computation should be short and simple, and must not
2901 <     * attempt to update any other mappings of this Map. For example,
2902 <     * to either create or append new messages to a value mapping:
2903 <     *
2904 <     * <pre> {@code
2905 <     * Map<Key, String> map = ...;
2906 <     * final String msg = ...;
2907 <     * map.compute(key, new BiFun<Key, String, String>() {
2908 <     *   public String apply(Key k, String v) {
2909 <     *    return (v == null) ? msg : v + msg;});}}</pre>
2910 <     *
2911 <     * @param key key with which the specified value is to be associated
2912 <     * @param remappingFunction the function to compute a value
2913 <     * @return the new value associated with the specified key, or null if none
2914 <     * @throws NullPointerException if the specified key or remappingFunction
2915 <     *         is null
2916 <     * @throws IllegalStateException if the computation detectably
2917 <     *         attempts a recursive update to this map that would
2918 <     *         otherwise never complete
2919 <     * @throws RuntimeException or Error if the remappingFunction does so,
2920 <     *         in which case the mapping is unchanged
2921 <     */
2922 <    public V compute
2923 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2924 <        return internalCompute(key, false, remappingFunction);
2925 <    }
2882 >        /**
2883 >         * Finds or adds a node.
2884 >         * @return null if added
2885 >         */
2886 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2887 >            Class<?> kc = null;
2888 >            boolean searched = false;
2889 >            for (TreeNode<K,V> p = root;;) {
2890 >                int dir, ph; K pk;
2891 >                if (p == null) {
2892 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2893 >                    break;
2894 >                }
2895 >                else if ((ph = p.hash) > h)
2896 >                    dir = -1;
2897 >                else if (ph < h)
2898 >                    dir = 1;
2899 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2900 >                    return p;
2901 >                else if ((kc == null &&
2902 >                          (kc = comparableClassFor(k)) == null) ||
2903 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2904 >                    if (!searched) {
2905 >                        TreeNode<K,V> q, ch;
2906 >                        searched = true;
2907 >                        if (((ch = p.left) != null &&
2908 >                             (q = ch.findTreeNode(h, k, kc)) != null) ||
2909 >                            ((ch = p.right) != null &&
2910 >                             (q = ch.findTreeNode(h, k, kc)) != null))
2911 >                            return q;
2912 >                    }
2913 >                    dir = tieBreakOrder(k, pk);
2914 >                }
2915 >
2916 >                TreeNode<K,V> xp = p;
2917 >                if ((p = (dir <= 0) ? p.left : p.right) == null) {
2918 >                    TreeNode<K,V> x, f = first;
2919 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2920 >                    if (f != null)
2921 >                        f.prev = x;
2922 >                    if (dir <= 0)
2923 >                        xp.left = x;
2924 >                    else
2925 >                        xp.right = x;
2926 >                    if (!xp.red)
2927 >                        x.red = true;
2928 >                    else {
2929 >                        lockRoot();
2930 >                        try {
2931 >                            root = balanceInsertion(root, x);
2932 >                        } finally {
2933 >                            unlockRoot();
2934 >                        }
2935 >                    }
2936 >                    break;
2937 >                }
2938 >            }
2939 >            assert checkInvariants(root);
2940 >            return null;
2941 >        }
2942  
2943 <    /**
2944 <     * If the specified key is not already associated
2945 <     * with a value, associate it with the given value.
2946 <     * Otherwise, replace the value with the results of
2947 <     * the given remapping function. This is equivalent to:
2948 <     *  <pre> {@code
2949 <     *   if (!map.containsKey(key))
2950 <     *     map.put(value);
2951 <     *   else {
2952 <     *     newValue = remappingFunction.apply(map.get(key), value);
2953 <     *     if (value != null)
2954 <     *       map.put(key, value);
2955 <     *     else
2956 <     *       map.remove(key);
2957 <     *   }
2958 <     * }</pre>
2959 <     * except that the action is performed atomically.  If the
2960 <     * function returns {@code null}, the mapping is removed.  If the
2961 <     * function itself throws an (unchecked) exception, the exception
2962 <     * is rethrown to its caller, and the current mapping is left
2963 <     * unchanged.  Some attempted update operations on this map by
2964 <     * other threads may be blocked while computation is in progress,
2965 <     * so the computation should be short and simple, and must not
2966 <     * attempt to update any other mappings of this Map.
2967 <     */
2968 <    public V merge
2969 <        (K key, V value,
2970 <         BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2971 <        return internalMerge(key, value, remappingFunction);
2972 <    }
2943 >        /**
2944 >         * Removes the given node, that must be present before this
2945 >         * call.  This is messier than typical red-black deletion code
2946 >         * because we cannot swap the contents of an interior node
2947 >         * with a leaf successor that is pinned by "next" pointers
2948 >         * that are accessible independently of lock. So instead we
2949 >         * swap the tree linkages.
2950 >         *
2951 >         * @return true if now too small, so should be untreeified
2952 >         */
2953 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2954 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2955 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2956 >            TreeNode<K,V> r, rl;
2957 >            if (pred == null)
2958 >                first = next;
2959 >            else
2960 >                pred.next = next;
2961 >            if (next != null)
2962 >                next.prev = pred;
2963 >            if (first == null) {
2964 >                root = null;
2965 >                return true;
2966 >            }
2967 >            if ((r = root) == null || r.right == null || // too small
2968 >                (rl = r.left) == null || rl.left == null)
2969 >                return true;
2970 >            lockRoot();
2971 >            try {
2972 >                TreeNode<K,V> replacement;
2973 >                TreeNode<K,V> pl = p.left;
2974 >                TreeNode<K,V> pr = p.right;
2975 >                if (pl != null && pr != null) {
2976 >                    TreeNode<K,V> s = pr, sl;
2977 >                    while ((sl = s.left) != null) // find successor
2978 >                        s = sl;
2979 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2980 >                    TreeNode<K,V> sr = s.right;
2981 >                    TreeNode<K,V> pp = p.parent;
2982 >                    if (s == pr) { // p was s's direct parent
2983 >                        p.parent = s;
2984 >                        s.right = p;
2985 >                    }
2986 >                    else {
2987 >                        TreeNode<K,V> sp = s.parent;
2988 >                        if ((p.parent = sp) != null) {
2989 >                            if (s == sp.left)
2990 >                                sp.left = p;
2991 >                            else
2992 >                                sp.right = p;
2993 >                        }
2994 >                        if ((s.right = pr) != null)
2995 >                            pr.parent = s;
2996 >                    }
2997 >                    p.left = null;
2998 >                    if ((p.right = sr) != null)
2999 >                        sr.parent = p;
3000 >                    if ((s.left = pl) != null)
3001 >                        pl.parent = s;
3002 >                    if ((s.parent = pp) == null)
3003 >                        r = s;
3004 >                    else if (p == pp.left)
3005 >                        pp.left = s;
3006 >                    else
3007 >                        pp.right = s;
3008 >                    if (sr != null)
3009 >                        replacement = sr;
3010 >                    else
3011 >                        replacement = p;
3012 >                }
3013 >                else if (pl != null)
3014 >                    replacement = pl;
3015 >                else if (pr != null)
3016 >                    replacement = pr;
3017 >                else
3018 >                    replacement = p;
3019 >                if (replacement != p) {
3020 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
3021 >                    if (pp == null)
3022 >                        r = replacement;
3023 >                    else if (p == pp.left)
3024 >                        pp.left = replacement;
3025 >                    else
3026 >                        pp.right = replacement;
3027 >                    p.left = p.right = p.parent = null;
3028 >                }
3029  
3030 <    /**
2818 <     * Removes the key (and its corresponding value) from this map.
2819 <     * This method does nothing if the key is not in the map.
2820 <     *
2821 <     * @param  key the key that needs to be removed
2822 <     * @return the previous value associated with {@code key}, or
2823 <     *         {@code null} if there was no mapping for {@code key}
2824 <     * @throws NullPointerException if the specified key is null
2825 <     */
2826 <    public V remove(Object key) {
2827 <        return internalReplace(key, null, null);
2828 <    }
3030 >                root = (p.red) ? r : balanceDeletion(r, replacement);
3031  
3032 <    /**
3033 <     * {@inheritDoc}
3034 <     *
3035 <     * @throws NullPointerException if the specified key is null
3036 <     */
3037 <    public boolean remove(Object key, Object value) {
3038 <        return value != null && internalReplace(key, null, value) != null;
3039 <    }
3032 >                if (p == replacement) {  // detach pointers
3033 >                    TreeNode<K,V> pp;
3034 >                    if ((pp = p.parent) != null) {
3035 >                        if (p == pp.left)
3036 >                            pp.left = null;
3037 >                        else if (p == pp.right)
3038 >                            pp.right = null;
3039 >                        p.parent = null;
3040 >                    }
3041 >                }
3042 >            } finally {
3043 >                unlockRoot();
3044 >            }
3045 >            assert checkInvariants(root);
3046 >            return false;
3047 >        }
3048  
3049 <    /**
3050 <     * {@inheritDoc}
2841 <     *
2842 <     * @throws NullPointerException if any of the arguments are null
2843 <     */
2844 <    public boolean replace(K key, V oldValue, V newValue) {
2845 <        if (key == null || oldValue == null || newValue == null)
2846 <            throw new NullPointerException();
2847 <        return internalReplace(key, newValue, oldValue) != null;
2848 <    }
3049 >        /* ------------------------------------------------------------ */
3050 >        // Red-black tree methods, all adapted from CLR
3051  
3052 <    /**
3053 <     * {@inheritDoc}
3054 <     *
3055 <     * @return the previous value associated with the specified key,
3056 <     *         or {@code null} if there was no mapping for the key
3057 <     * @throws NullPointerException if the specified key or value is null
3058 <     */
3059 <    public V replace(K key, V value) {
3060 <        if (key == null || value == null)
3061 <            throw new NullPointerException();
3062 <        return internalReplace(key, value, null);
3063 <    }
3052 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
3053 >                                              TreeNode<K,V> p) {
3054 >            TreeNode<K,V> r, pp, rl;
3055 >            if (p != null && (r = p.right) != null) {
3056 >                if ((rl = p.right = r.left) != null)
3057 >                    rl.parent = p;
3058 >                if ((pp = r.parent = p.parent) == null)
3059 >                    (root = r).red = false;
3060 >                else if (pp.left == p)
3061 >                    pp.left = r;
3062 >                else
3063 >                    pp.right = r;
3064 >                r.left = p;
3065 >                p.parent = r;
3066 >            }
3067 >            return root;
3068 >        }
3069  
3070 <    /**
3071 <     * Removes all of the mappings from this map.
3072 <     */
3073 <    public void clear() {
3074 <        internalClear();
3075 <    }
3070 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
3071 >                                               TreeNode<K,V> p) {
3072 >            TreeNode<K,V> l, pp, lr;
3073 >            if (p != null && (l = p.left) != null) {
3074 >                if ((lr = p.left = l.right) != null)
3075 >                    lr.parent = p;
3076 >                if ((pp = l.parent = p.parent) == null)
3077 >                    (root = l).red = false;
3078 >                else if (pp.right == p)
3079 >                    pp.right = l;
3080 >                else
3081 >                    pp.left = l;
3082 >                l.right = p;
3083 >                p.parent = l;
3084 >            }
3085 >            return root;
3086 >        }
3087  
3088 <    /**
3089 <     * Returns a {@link Set} view of the keys contained in this map.
3090 <     * The set is backed by the map, so changes to the map are
3091 <     * reflected in the set, and vice-versa.
3092 <     *
3093 <     * @return the set view
3094 <     */
3095 <    public KeySetView<K,V> keySet() {
3096 <        KeySetView<K,V> ks = keySet;
3097 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
3098 <    }
3088 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
3089 >                                                    TreeNode<K,V> x) {
3090 >            x.red = true;
3091 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
3092 >                if ((xp = x.parent) == null) {
3093 >                    x.red = false;
3094 >                    return x;
3095 >                }
3096 >                else if (!xp.red || (xpp = xp.parent) == null)
3097 >                    return root;
3098 >                if (xp == (xppl = xpp.left)) {
3099 >                    if ((xppr = xpp.right) != null && xppr.red) {
3100 >                        xppr.red = false;
3101 >                        xp.red = false;
3102 >                        xpp.red = true;
3103 >                        x = xpp;
3104 >                    }
3105 >                    else {
3106 >                        if (x == xp.right) {
3107 >                            root = rotateLeft(root, x = xp);
3108 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3109 >                        }
3110 >                        if (xp != null) {
3111 >                            xp.red = false;
3112 >                            if (xpp != null) {
3113 >                                xpp.red = true;
3114 >                                root = rotateRight(root, xpp);
3115 >                            }
3116 >                        }
3117 >                    }
3118 >                }
3119 >                else {
3120 >                    if (xppl != null && xppl.red) {
3121 >                        xppl.red = false;
3122 >                        xp.red = false;
3123 >                        xpp.red = true;
3124 >                        x = xpp;
3125 >                    }
3126 >                    else {
3127 >                        if (x == xp.left) {
3128 >                            root = rotateRight(root, x = xp);
3129 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3130 >                        }
3131 >                        if (xp != null) {
3132 >                            xp.red = false;
3133 >                            if (xpp != null) {
3134 >                                xpp.red = true;
3135 >                                root = rotateLeft(root, xpp);
3136 >                            }
3137 >                        }
3138 >                    }
3139 >                }
3140 >            }
3141 >        }
3142  
3143 <    /**
3144 <     * Returns a {@link Set} view of the keys in this map, using the
3145 <     * given common mapped value for any additions (i.e., {@link
3146 <     * Collection#add} and {@link Collection#addAll}). This is of
3147 <     * course only appropriate if it is acceptable to use the same
3148 <     * value for all additions from this view.
3149 <     *
3150 <     * @param mappedValue the mapped value to use for any
3151 <     * additions.
3152 <     * @return the set view
3153 <     * @throws NullPointerException if the mappedValue is null
3154 <     */
3155 <    public KeySetView<K,V> keySet(V mappedValue) {
3156 <        if (mappedValue == null)
3157 <            throw new NullPointerException();
3158 <        return new KeySetView<K,V>(this, mappedValue);
3159 <    }
3143 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3144 >                                                   TreeNode<K,V> x) {
3145 >            for (TreeNode<K,V> xp, xpl, xpr;;) {
3146 >                if (x == null || x == root)
3147 >                    return root;
3148 >                else if ((xp = x.parent) == null) {
3149 >                    x.red = false;
3150 >                    return x;
3151 >                }
3152 >                else if (x.red) {
3153 >                    x.red = false;
3154 >                    return root;
3155 >                }
3156 >                else if ((xpl = xp.left) == x) {
3157 >                    if ((xpr = xp.right) != null && xpr.red) {
3158 >                        xpr.red = false;
3159 >                        xp.red = true;
3160 >                        root = rotateLeft(root, xp);
3161 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3162 >                    }
3163 >                    if (xpr == null)
3164 >                        x = xp;
3165 >                    else {
3166 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3167 >                        if ((sr == null || !sr.red) &&
3168 >                            (sl == null || !sl.red)) {
3169 >                            xpr.red = true;
3170 >                            x = xp;
3171 >                        }
3172 >                        else {
3173 >                            if (sr == null || !sr.red) {
3174 >                                if (sl != null)
3175 >                                    sl.red = false;
3176 >                                xpr.red = true;
3177 >                                root = rotateRight(root, xpr);
3178 >                                xpr = (xp = x.parent) == null ?
3179 >                                    null : xp.right;
3180 >                            }
3181 >                            if (xpr != null) {
3182 >                                xpr.red = (xp == null) ? false : xp.red;
3183 >                                if ((sr = xpr.right) != null)
3184 >                                    sr.red = false;
3185 >                            }
3186 >                            if (xp != null) {
3187 >                                xp.red = false;
3188 >                                root = rotateLeft(root, xp);
3189 >                            }
3190 >                            x = root;
3191 >                        }
3192 >                    }
3193 >                }
3194 >                else { // symmetric
3195 >                    if (xpl != null && xpl.red) {
3196 >                        xpl.red = false;
3197 >                        xp.red = true;
3198 >                        root = rotateRight(root, xp);
3199 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3200 >                    }
3201 >                    if (xpl == null)
3202 >                        x = xp;
3203 >                    else {
3204 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3205 >                        if ((sl == null || !sl.red) &&
3206 >                            (sr == null || !sr.red)) {
3207 >                            xpl.red = true;
3208 >                            x = xp;
3209 >                        }
3210 >                        else {
3211 >                            if (sl == null || !sl.red) {
3212 >                                if (sr != null)
3213 >                                    sr.red = false;
3214 >                                xpl.red = true;
3215 >                                root = rotateLeft(root, xpl);
3216 >                                xpl = (xp = x.parent) == null ?
3217 >                                    null : xp.left;
3218 >                            }
3219 >                            if (xpl != null) {
3220 >                                xpl.red = (xp == null) ? false : xp.red;
3221 >                                if ((sl = xpl.left) != null)
3222 >                                    sl.red = false;
3223 >                            }
3224 >                            if (xp != null) {
3225 >                                xp.red = false;
3226 >                                root = rotateRight(root, xp);
3227 >                            }
3228 >                            x = root;
3229 >                        }
3230 >                    }
3231 >                }
3232 >            }
3233 >        }
3234  
3235 <    /**
3236 <     * Returns a {@link Collection} view of the values contained in this map.
3237 <     * The collection is backed by the map, so changes to the map are
3238 <     * reflected in the collection, and vice-versa.
3239 <     */
3240 <    public ValuesView<K,V> values() {
3241 <        ValuesView<K,V> vs = values;
3242 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
3243 <    }
3235 >        /**
3236 >         * Checks invariants recursively for the tree of Nodes rooted at t.
3237 >         */
3238 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3239 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3240 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3241 >            if (tb != null && tb.next != t)
3242 >                return false;
3243 >            if (tn != null && tn.prev != t)
3244 >                return false;
3245 >            if (tp != null && t != tp.left && t != tp.right)
3246 >                return false;
3247 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3248 >                return false;
3249 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3250 >                return false;
3251 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3252 >                return false;
3253 >            if (tl != null && !checkInvariants(tl))
3254 >                return false;
3255 >            if (tr != null && !checkInvariants(tr))
3256 >                return false;
3257 >            return true;
3258 >        }
3259  
3260 <    /**
3261 <     * Returns a {@link Set} view of the mappings contained in this map.
3262 <     * The set is backed by the map, so changes to the map are
2913 <     * reflected in the set, and vice-versa.  The set supports element
2914 <     * removal, which removes the corresponding mapping from the map,
2915 <     * via the {@code Iterator.remove}, {@code Set.remove},
2916 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
2917 <     * operations.  It does not support the {@code add} or
2918 <     * {@code addAll} operations.
2919 <     *
2920 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2921 <     * that will never throw {@link ConcurrentModificationException},
2922 <     * and guarantees to traverse elements as they existed upon
2923 <     * construction of the iterator, and may (but is not guaranteed to)
2924 <     * reflect any modifications subsequent to construction.
2925 <     */
2926 <    public Set<Map.Entry<K,V>> entrySet() {
2927 <        EntrySetView<K,V> es = entrySet;
2928 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
3260 >        private static final Unsafe U = Unsafe.getUnsafe();
3261 >        private static final long LOCKSTATE
3262 >                = U.objectFieldOffset(TreeBin.class, "lockState");
3263      }
3264  
3265 <    /**
2932 <     * Returns an enumeration of the keys in this table.
2933 <     *
2934 <     * @return an enumeration of the keys in this table
2935 <     * @see #keySet()
2936 <     */
2937 <    public Enumeration<K> keys() {
2938 <        return new KeyIterator<K,V>(this);
2939 <    }
3265 >    /* ----------------Table Traversal -------------- */
3266  
3267      /**
3268 <     * Returns an enumeration of the values in this table.
3269 <     *
3270 <     * @return an enumeration of the values in this table
3271 <     * @see #values()
3272 <     */
3273 <    public Enumeration<V> elements() {
3274 <        return new ValueIterator<K,V>(this);
3268 >     * Records the table, its length, and current traversal index for a
3269 >     * traverser that must process a region of a forwarded table before
3270 >     * proceeding with current table.
3271 >     */
3272 >    static final class TableStack<K,V> {
3273 >        int length;
3274 >        int index;
3275 >        Node<K,V>[] tab;
3276 >        TableStack<K,V> next;
3277      }
3278  
3279      /**
3280 <     * Returns a partitionable iterator of the keys in this map.
3280 >     * Encapsulates traversal for methods such as containsValue; also
3281 >     * serves as a base class for other iterators and spliterators.
3282       *
3283 <     * @return a partitionable iterator of the keys in this map
3284 <     */
3285 <    public Spliterator<K> keySpliterator() {
3286 <        return new KeyIterator<K,V>(this);
3287 <    }
3288 <
3289 <    /**
3290 <     * Returns a partitionable iterator of the values in this map.
3283 >     * Method advance visits once each still-valid node that was
3284 >     * reachable upon iterator construction. It might miss some that
3285 >     * were added to a bin after the bin was visited, which is OK wrt
3286 >     * consistency guarantees. Maintaining this property in the face
3287 >     * of possible ongoing resizes requires a fair amount of
3288 >     * bookkeeping state that is difficult to optimize away amidst
3289 >     * volatile accesses.  Even so, traversal maintains reasonable
3290 >     * throughput.
3291       *
3292 <     * @return a partitionable iterator of the values in this map
3292 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3293 >     * However, if the table has been resized, then all future steps
3294 >     * must traverse both the bin at the current index as well as at
3295 >     * (index + baseSize); and so on for further resizings. To
3296 >     * paranoically cope with potential sharing by users of iterators
3297 >     * across threads, iteration terminates if a bounds checks fails
3298 >     * for a table read.
3299       */
3300 <    public Spliterator<V> valueSpliterator() {
3301 <        return new ValueIterator<K,V>(this);
3302 <    }
3300 >    static class Traverser<K,V> {
3301 >        Node<K,V>[] tab;        // current table; updated if resized
3302 >        Node<K,V> next;         // the next entry to use
3303 >        TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3304 >        int index;              // index of bin to use next
3305 >        int baseIndex;          // current index of initial table
3306 >        int baseLimit;          // index bound for initial table
3307 >        final int baseSize;     // initial table size
3308 >
3309 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3310 >            this.tab = tab;
3311 >            this.baseSize = size;
3312 >            this.baseIndex = this.index = index;
3313 >            this.baseLimit = limit;
3314 >            this.next = null;
3315 >        }
3316  
3317 <    /**
3318 <     * Returns a partitionable iterator of the entries in this map.
3319 <     *
3320 <     * @return a partitionable iterator of the entries in this map
3321 <     */
3322 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
3323 <        return new EntryIterator<K,V>(this);
3324 <    }
3317 >        /**
3318 >         * Advances if possible, returning next valid node, or null if none.
3319 >         */
3320 >        final Node<K,V> advance() {
3321 >            Node<K,V> e;
3322 >            if ((e = next) != null)
3323 >                e = e.next;
3324 >            for (;;) {
3325 >                Node<K,V>[] t; int i, n;  // must use locals in checks
3326 >                if (e != null)
3327 >                    return next = e;
3328 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3329 >                    (n = t.length) <= (i = index) || i < 0)
3330 >                    return next = null;
3331 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
3332 >                    if (e instanceof ForwardingNode) {
3333 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3334 >                        e = null;
3335 >                        pushState(t, i, n);
3336 >                        continue;
3337 >                    }
3338 >                    else if (e instanceof TreeBin)
3339 >                        e = ((TreeBin<K,V>)e).first;
3340 >                    else
3341 >                        e = null;
3342 >                }
3343 >                if (stack != null)
3344 >                    recoverState(n);
3345 >                else if ((index = i + baseSize) >= n)
3346 >                    index = ++baseIndex; // visit upper slots if present
3347 >            }
3348 >        }
3349  
3350 <    /**
3351 <     * Returns the hash code value for this {@link Map}, i.e.,
3352 <     * the sum of, for each key-value pair in the map,
3353 <     * {@code key.hashCode() ^ value.hashCode()}.
3354 <     *
3355 <     * @return the hash code value for this map
3356 <     */
3357 <    public int hashCode() {
3358 <        int h = 0;
3359 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3360 <        Object v;
3361 <        while ((v = it.advance()) != null) {
3362 <            h += it.nextKey.hashCode() ^ v.hashCode();
3350 >        /**
3351 >         * Saves traversal state upon encountering a forwarding node.
3352 >         */
3353 >        private void pushState(Node<K,V>[] t, int i, int n) {
3354 >            TableStack<K,V> s = spare;  // reuse if possible
3355 >            if (s != null)
3356 >                spare = s.next;
3357 >            else
3358 >                s = new TableStack<K,V>();
3359 >            s.tab = t;
3360 >            s.length = n;
3361 >            s.index = i;
3362 >            s.next = stack;
3363 >            stack = s;
3364          }
2992        return h;
2993    }
3365  
3366 <    /**
3367 <     * Returns a string representation of this map.  The string
3368 <     * representation consists of a list of key-value mappings (in no
3369 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3370 <     * mappings are separated by the characters {@code ", "} (comma
3371 <     * and space).  Each key-value mapping is rendered as the key
3372 <     * followed by an equals sign ("{@code =}") followed by the
3373 <     * associated value.
3374 <     *
3375 <     * @return a string representation of this map
3376 <     */
3377 <    public String toString() {
3378 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3379 <        StringBuilder sb = new StringBuilder();
3380 <        sb.append('{');
3381 <        Object v;
3011 <        if ((v = it.advance()) != null) {
3012 <            for (;;) {
3013 <                Object k = it.nextKey;
3014 <                sb.append(k == this ? "(this Map)" : k);
3015 <                sb.append('=');
3016 <                sb.append(v == this ? "(this Map)" : v);
3017 <                if ((v = it.advance()) == null)
3018 <                    break;
3019 <                sb.append(',').append(' ');
3366 >        /**
3367 >         * Possibly pops traversal state.
3368 >         *
3369 >         * @param n length of current table
3370 >         */
3371 >        private void recoverState(int n) {
3372 >            TableStack<K,V> s; int len;
3373 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
3374 >                n = len;
3375 >                index = s.index;
3376 >                tab = s.tab;
3377 >                s.tab = null;
3378 >                TableStack<K,V> next = s.next;
3379 >                s.next = spare; // save for reuse
3380 >                stack = next;
3381 >                spare = s;
3382              }
3383 +            if (s == null && (index += baseSize) >= n)
3384 +                index = ++baseIndex;
3385          }
3022        return sb.append('}').toString();
3386      }
3387  
3388      /**
3389 <     * Compares the specified object with this map for equality.
3390 <     * Returns {@code true} if the given object is a map with the same
3028 <     * mappings as this map.  This operation may return misleading
3029 <     * results if either map is concurrently modified during execution
3030 <     * of this method.
3031 <     *
3032 <     * @param o object to be compared for equality with this map
3033 <     * @return {@code true} if the specified object is equal to this map
3389 >     * Base of key, value, and entry Iterators. Adds fields to
3390 >     * Traverser to support iterator.remove.
3391       */
3392 <    public boolean equals(Object o) {
3393 <        if (o != this) {
3394 <            if (!(o instanceof Map))
3395 <                return false;
3396 <            Map<?,?> m = (Map<?,?>) o;
3397 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3398 <            Object val;
3399 <            while ((val = it.advance()) != null) {
3043 <                Object v = m.get(it.nextKey);
3044 <                if (v == null || (v != val && !v.equals(val)))
3045 <                    return false;
3046 <            }
3047 <            for (Map.Entry<?,?> e : m.entrySet()) {
3048 <                Object mk, mv, v;
3049 <                if ((mk = e.getKey()) == null ||
3050 <                    (mv = e.getValue()) == null ||
3051 <                    (v = internalGet(mk)) == null ||
3052 <                    (mv != v && !mv.equals(v)))
3053 <                    return false;
3054 <            }
3392 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3393 >        final ConcurrentHashMap<K,V> map;
3394 >        Node<K,V> lastReturned;
3395 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3396 >                    ConcurrentHashMap<K,V> map) {
3397 >            super(tab, size, index, limit);
3398 >            this.map = map;
3399 >            advance();
3400          }
3056        return true;
3057    }
3401  
3402 <    /* ----------------Iterators -------------- */
3402 >        public final boolean hasNext() { return next != null; }
3403 >        public final boolean hasMoreElements() { return next != null; }
3404  
3405 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3406 <        extends Traverser<K,V,Object>
3407 <        implements Spliterator<K>, Enumeration<K> {
3064 <        KeyIterator(ConcurrentHashMap<K, V> map) { super(map); }
3065 <        KeyIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
3066 <            super(map, it, -1);
3067 <        }
3068 <        public KeyIterator<K,V> split() {
3069 <            if (nextKey != null)
3405 >        public final void remove() {
3406 >            Node<K,V> p;
3407 >            if ((p = lastReturned) == null)
3408                  throw new IllegalStateException();
3409 <            return new KeyIterator<K,V>(map, this);
3409 >            lastReturned = null;
3410 >            map.replaceNode(p.key, null, null);
3411 >        }
3412 >    }
3413 >
3414 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3415 >        implements Iterator<K>, Enumeration<K> {
3416 >        KeyIterator(Node<K,V>[] tab, int size, int index, int limit,
3417 >                    ConcurrentHashMap<K,V> map) {
3418 >            super(tab, size, index, limit, map);
3419          }
3420 <        @SuppressWarnings("unchecked") public final K next() {
3421 <            if (nextVal == null && advance() == null)
3420 >
3421 >        public final K next() {
3422 >            Node<K,V> p;
3423 >            if ((p = next) == null)
3424                  throw new NoSuchElementException();
3425 <            Object k = nextKey;
3426 <            nextVal = null;
3427 <            return (K) k;
3425 >            K k = p.key;
3426 >            lastReturned = p;
3427 >            advance();
3428 >            return k;
3429          }
3430  
3431          public final K nextElement() { return next(); }
3432      }
3433  
3434 <    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3435 <        extends Traverser<K,V,Object>
3436 <        implements Spliterator<V>, Enumeration<V> {
3437 <        ValueIterator(ConcurrentHashMap<K, V> map) { super(map); }
3438 <        ValueIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
3089 <            super(map, it, -1);
3090 <        }
3091 <        public ValueIterator<K,V> split() {
3092 <            if (nextKey != null)
3093 <                throw new IllegalStateException();
3094 <            return new ValueIterator<K,V>(map, this);
3434 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3435 >        implements Iterator<V>, Enumeration<V> {
3436 >        ValueIterator(Node<K,V>[] tab, int size, int index, int limit,
3437 >                      ConcurrentHashMap<K,V> map) {
3438 >            super(tab, size, index, limit, map);
3439          }
3440  
3441 <        @SuppressWarnings("unchecked") public final V next() {
3442 <            Object v;
3443 <            if ((v = nextVal) == null && (v = advance()) == null)
3441 >        public final V next() {
3442 >            Node<K,V> p;
3443 >            if ((p = next) == null)
3444                  throw new NoSuchElementException();
3445 <            nextVal = null;
3446 <            return (V) v;
3445 >            V v = p.val;
3446 >            lastReturned = p;
3447 >            advance();
3448 >            return v;
3449          }
3450  
3451          public final V nextElement() { return next(); }
3452      }
3453  
3454 <    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3455 <        extends Traverser<K,V,Object>
3456 <        implements Spliterator<Map.Entry<K,V>> {
3457 <        EntryIterator(ConcurrentHashMap<K, V> map) { super(map); }
3458 <        EntryIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
3113 <            super(map, it, -1);
3114 <        }
3115 <        public EntryIterator<K,V> split() {
3116 <            if (nextKey != null)
3117 <                throw new IllegalStateException();
3118 <            return new EntryIterator<K,V>(map, this);
3454 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3455 >        implements Iterator<Map.Entry<K,V>> {
3456 >        EntryIterator(Node<K,V>[] tab, int size, int index, int limit,
3457 >                      ConcurrentHashMap<K,V> map) {
3458 >            super(tab, size, index, limit, map);
3459          }
3460  
3461 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3462 <            Object v;
3463 <            if ((v = nextVal) == null && (v = advance()) == null)
3461 >        public final Map.Entry<K,V> next() {
3462 >            Node<K,V> p;
3463 >            if ((p = next) == null)
3464                  throw new NoSuchElementException();
3465 <            Object k = nextKey;
3466 <            nextVal = null;
3467 <            return new MapEntry<K,V>((K)k, (V)v, map);
3465 >            K k = p.key;
3466 >            V v = p.val;
3467 >            lastReturned = p;
3468 >            advance();
3469 >            return new MapEntry<K,V>(k, v, map);
3470          }
3471      }
3472  
3473      /**
3474 <     * Exported Entry for iterators
3474 >     * Exported Entry for EntryIterator.
3475       */
3476 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3476 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3477          final K key; // non-null
3478          V val;       // non-null
3479 <        final ConcurrentHashMap<K, V> map;
3480 <        MapEntry(K key, V val, ConcurrentHashMap<K, V> map) {
3479 >        final ConcurrentHashMap<K,V> map;
3480 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3481              this.key = key;
3482              this.val = val;
3483              this.map = map;
3484          }
3485 <        public final K getKey()       { return key; }
3486 <        public final V getValue()     { return val; }
3487 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3488 <        public final String toString(){ return key + "=" + val; }
3485 >        public K getKey()        { return key; }
3486 >        public V getValue()      { return val; }
3487 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3488 >        public String toString() {
3489 >            return Helpers.mapEntryToString(key, val);
3490 >        }
3491  
3492 <        public final boolean equals(Object o) {
3492 >        public boolean equals(Object o) {
3493              Object k, v; Map.Entry<?,?> e;
3494              return ((o instanceof Map.Entry) &&
3495                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3159 | Line 3503 | public class ConcurrentHashMap<K, V>
3503           * value to return is somewhat arbitrary here. Since we do not
3504           * necessarily track asynchronous changes, the most recent
3505           * "previous" value could be different from what we return (or
3506 <         * could even have been removed in which case the put will
3506 >         * could even have been removed, in which case the put will
3507           * re-establish). We do not and cannot guarantee more.
3508           */
3509 <        public final V setValue(V value) {
3509 >        public V setValue(V value) {
3510              if (value == null) throw new NullPointerException();
3511              V v = val;
3512              val = value;
# Line 3171 | Line 3515 | public class ConcurrentHashMap<K, V>
3515          }
3516      }
3517  
3518 <    /**
3519 <     * Returns exportable snapshot entry for the given key and value
3520 <     * when write-through can't or shouldn't be used.
3521 <     */
3522 <    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3523 <        return new AbstractMap.SimpleEntry<K,V>(k, v);
3524 <    }
3518 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3519 >        implements Spliterator<K> {
3520 >        long est;               // size estimate
3521 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3522 >                       long est) {
3523 >            super(tab, size, index, limit);
3524 >            this.est = est;
3525 >        }
3526 >
3527 >        public KeySpliterator<K,V> trySplit() {
3528 >            int i, f, h;
3529 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3530 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3531 >                                        f, est >>>= 1);
3532 >        }
3533  
3534 <    /* ---------------- Serialization Support -------------- */
3534 >        public void forEachRemaining(Consumer<? super K> action) {
3535 >            if (action == null) throw new NullPointerException();
3536 >            for (Node<K,V> p; (p = advance()) != null;)
3537 >                action.accept(p.key);
3538 >        }
3539  
3540 <    /**
3541 <     * Stripped-down version of helper class used in previous version,
3542 <     * declared for the sake of serialization compatibility
3543 <     */
3544 <    static class Segment<K,V> implements Serializable {
3545 <        private static final long serialVersionUID = 2249069246763182397L;
3546 <        final float loadFactor;
3547 <        Segment(float lf) { this.loadFactor = lf; }
3192 <    }
3540 >        public boolean tryAdvance(Consumer<? super K> action) {
3541 >            if (action == null) throw new NullPointerException();
3542 >            Node<K,V> p;
3543 >            if ((p = advance()) == null)
3544 >                return false;
3545 >            action.accept(p.key);
3546 >            return true;
3547 >        }
3548  
3549 <    /**
3550 <     * Saves the state of the {@code ConcurrentHashMap} instance to a
3551 <     * stream (i.e., serializes it).
3552 <     * @param s the stream
3553 <     * @serialData
3199 <     * the key (Object) and value (Object)
3200 <     * for each key-value mapping, followed by a null pair.
3201 <     * The key-value mappings are emitted in no particular order.
3202 <     */
3203 <    @SuppressWarnings("unchecked") private void writeObject
3204 <        (java.io.ObjectOutputStream s)
3205 <        throws java.io.IOException {
3206 <        if (segments == null) { // for serialization compatibility
3207 <            segments = (Segment<K,V>[])
3208 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3209 <            for (int i = 0; i < segments.length; ++i)
3210 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3211 <        }
3212 <        s.defaultWriteObject();
3213 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3214 <        Object v;
3215 <        while ((v = it.advance()) != null) {
3216 <            s.writeObject(it.nextKey);
3217 <            s.writeObject(v);
3549 >        public long estimateSize() { return est; }
3550 >
3551 >        public int characteristics() {
3552 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3553 >                Spliterator.NONNULL;
3554          }
3219        s.writeObject(null);
3220        s.writeObject(null);
3221        segments = null; // throw away
3555      }
3556  
3557 <    /**
3558 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3559 <     * @param s the stream
3560 <     */
3561 <    @SuppressWarnings("unchecked") private void readObject
3562 <        (java.io.ObjectInputStream s)
3563 <        throws java.io.IOException, ClassNotFoundException {
3564 <        s.defaultReadObject();
3232 <        this.segments = null; // unneeded
3557 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3558 >        implements Spliterator<V> {
3559 >        long est;               // size estimate
3560 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3561 >                         long est) {
3562 >            super(tab, size, index, limit);
3563 >            this.est = est;
3564 >        }
3565  
3566 <        // Create all nodes, then place in table once size is known
3567 <        long size = 0L;
3568 <        Node p = null;
3569 <        for (;;) {
3570 <            K k = (K) s.readObject();
3239 <            V v = (V) s.readObject();
3240 <            if (k != null && v != null) {
3241 <                int h = spread(k.hashCode());
3242 <                p = new Node(h, k, v, p);
3243 <                ++size;
3244 <            }
3245 <            else
3246 <                break;
3566 >        public ValueSpliterator<K,V> trySplit() {
3567 >            int i, f, h;
3568 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3569 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3570 >                                          f, est >>>= 1);
3571          }
3572 <        if (p != null) {
3573 <            boolean init = false;
3574 <            int n;
3575 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3576 <                n = MAXIMUM_CAPACITY;
3577 <            else {
3578 <                int sz = (int)size;
3579 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3580 <            }
3581 <            int sc = sizeCtl;
3582 <            boolean collide = false;
3583 <            if (n > sc &&
3584 <                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3585 <                try {
3586 <                    if (table == null) {
3587 <                        init = true;
3588 <                        Node[] tab = new Node[n];
3589 <                        int mask = n - 1;
3590 <                        while (p != null) {
3591 <                            int j = p.hash & mask;
3268 <                            Node next = p.next;
3269 <                            Node q = p.next = tabAt(tab, j);
3270 <                            setTabAt(tab, j, p);
3271 <                            if (!collide && q != null && q.hash == p.hash)
3272 <                                collide = true;
3273 <                            p = next;
3274 <                        }
3275 <                        table = tab;
3276 <                        addCount(size, -1);
3277 <                        sc = n - (n >>> 2);
3278 <                    }
3279 <                } finally {
3280 <                    sizeCtl = sc;
3281 <                }
3282 <                if (collide) { // rescan and convert to TreeBins
3283 <                    Node[] tab = table;
3284 <                    for (int i = 0; i < tab.length; ++i) {
3285 <                        int c = 0;
3286 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3287 <                            if (++c > TREE_THRESHOLD &&
3288 <                                (e.key instanceof Comparable)) {
3289 <                                replaceWithTreeBin(tab, i, e.key);
3290 <                                break;
3291 <                            }
3292 <                        }
3293 <                    }
3294 <                }
3295 <            }
3296 <            if (!init) { // Can only happen if unsafely published.
3297 <                while (p != null) {
3298 <                    internalPut((K)p.key, (V)p.val, false);
3299 <                    p = p.next;
3300 <                }
3301 <            }
3572 >
3573 >        public void forEachRemaining(Consumer<? super V> action) {
3574 >            if (action == null) throw new NullPointerException();
3575 >            for (Node<K,V> p; (p = advance()) != null;)
3576 >                action.accept(p.val);
3577 >        }
3578 >
3579 >        public boolean tryAdvance(Consumer<? super V> action) {
3580 >            if (action == null) throw new NullPointerException();
3581 >            Node<K,V> p;
3582 >            if ((p = advance()) == null)
3583 >                return false;
3584 >            action.accept(p.val);
3585 >            return true;
3586 >        }
3587 >
3588 >        public long estimateSize() { return est; }
3589 >
3590 >        public int characteristics() {
3591 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3592          }
3593      }
3594  
3595 <    // -------------------------------------------------------
3595 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3596 >        implements Spliterator<Map.Entry<K,V>> {
3597 >        final ConcurrentHashMap<K,V> map; // To export MapEntry
3598 >        long est;               // size estimate
3599 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3600 >                         long est, ConcurrentHashMap<K,V> map) {
3601 >            super(tab, size, index, limit);
3602 >            this.map = map;
3603 >            this.est = est;
3604 >        }
3605  
3606 <    // Sams
3607 <    /** Interface describing a void action of one argument */
3608 <    public interface Action<A> { void apply(A a); }
3609 <    /** Interface describing a void action of two arguments */
3610 <    public interface BiAction<A,B> { void apply(A a, B b); }
3611 <    /** Interface describing a function of one argument */
3313 <    public interface Fun<A,T> { T apply(A a); }
3314 <    /** Interface describing a function of two arguments */
3315 <    public interface BiFun<A,B,T> { T apply(A a, B b); }
3316 <    /** Interface describing a function of no arguments */
3317 <    public interface Generator<T> { T apply(); }
3318 <    /** Interface describing a function mapping its argument to a double */
3319 <    public interface ObjectToDouble<A> { double apply(A a); }
3320 <    /** Interface describing a function mapping its argument to a long */
3321 <    public interface ObjectToLong<A> { long apply(A a); }
3322 <    /** Interface describing a function mapping its argument to an int */
3323 <    public interface ObjectToInt<A> {int apply(A a); }
3324 <    /** Interface describing a function mapping two arguments to a double */
3325 <    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
3326 <    /** Interface describing a function mapping two arguments to a long */
3327 <    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
3328 <    /** Interface describing a function mapping two arguments to an int */
3329 <    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
3330 <    /** Interface describing a function mapping a double to a double */
3331 <    public interface DoubleToDouble { double apply(double a); }
3332 <    /** Interface describing a function mapping a long to a long */
3333 <    public interface LongToLong { long apply(long a); }
3334 <    /** Interface describing a function mapping an int to an int */
3335 <    public interface IntToInt { int apply(int a); }
3336 <    /** Interface describing a function mapping two doubles to a double */
3337 <    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3338 <    /** Interface describing a function mapping two longs to a long */
3339 <    public interface LongByLongToLong { long apply(long a, long b); }
3340 <    /** Interface describing a function mapping two ints to an int */
3341 <    public interface IntByIntToInt { int apply(int a, int b); }
3606 >        public EntrySpliterator<K,V> trySplit() {
3607 >            int i, f, h;
3608 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3609 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3610 >                                          f, est >>>= 1, map);
3611 >        }
3612  
3613 +        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3614 +            if (action == null) throw new NullPointerException();
3615 +            for (Node<K,V> p; (p = advance()) != null; )
3616 +                action.accept(new MapEntry<K,V>(p.key, p.val, map));
3617 +        }
3618  
3619 <    // -------------------------------------------------------
3619 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3620 >            if (action == null) throw new NullPointerException();
3621 >            Node<K,V> p;
3622 >            if ((p = advance()) == null)
3623 >                return false;
3624 >            action.accept(new MapEntry<K,V>(p.key, p.val, map));
3625 >            return true;
3626 >        }
3627 >
3628 >        public long estimateSize() { return est; }
3629 >
3630 >        public int characteristics() {
3631 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3632 >                Spliterator.NONNULL;
3633 >        }
3634 >    }
3635 >
3636 >    // Parallel bulk operations
3637 >
3638 >    /**
3639 >     * Computes initial batch value for bulk tasks. The returned value
3640 >     * is approximately exp2 of the number of times (minus one) to
3641 >     * split task by two before executing leaf action. This value is
3642 >     * faster to compute and more convenient to use as a guide to
3643 >     * splitting than is the depth, since it is used while dividing by
3644 >     * two anyway.
3645 >     */
3646 >    final int batchFor(long b) {
3647 >        long n;
3648 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3649 >            return 0;
3650 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3651 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3652 >    }
3653  
3654      /**
3655       * Performs the given action for each (key, value).
3656       *
3657 +     * @param parallelismThreshold the (estimated) number of elements
3658 +     * needed for this operation to be executed in parallel
3659       * @param action the action
3660 +     * @since 1.8
3661       */
3662 <    public void forEach(BiAction<K,V> action) {
3663 <        ForkJoinTasks.forEach
3664 <            (this, action).invoke();
3662 >    public void forEach(long parallelismThreshold,
3663 >                        BiConsumer<? super K,? super V> action) {
3664 >        if (action == null) throw new NullPointerException();
3665 >        new ForEachMappingTask<K,V>
3666 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3667 >             action).invoke();
3668      }
3669  
3670      /**
3671       * Performs the given action for each non-null transformation
3672       * of each (key, value).
3673       *
3674 +     * @param parallelismThreshold the (estimated) number of elements
3675 +     * needed for this operation to be executed in parallel
3676       * @param transformer a function returning the transformation
3677 <     * for an element, or null of there is no transformation (in
3678 <     * which case the action is not applied).
3677 >     * for an element, or null if there is no transformation (in
3678 >     * which case the action is not applied)
3679       * @param action the action
3680 +     * @param <U> the return type of the transformer
3681 +     * @since 1.8
3682       */
3683 <    public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3684 <                            Action<U> action) {
3685 <        ForkJoinTasks.forEach
3686 <            (this, transformer, action).invoke();
3683 >    public <U> void forEach(long parallelismThreshold,
3684 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3685 >                            Consumer<? super U> action) {
3686 >        if (transformer == null || action == null)
3687 >            throw new NullPointerException();
3688 >        new ForEachTransformedMappingTask<K,V,U>
3689 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3690 >             transformer, action).invoke();
3691      }
3692  
3693      /**
# Line 3375 | Line 3697 | public class ConcurrentHashMap<K, V>
3697       * results of any other parallel invocations of the search
3698       * function are ignored.
3699       *
3700 +     * @param parallelismThreshold the (estimated) number of elements
3701 +     * needed for this operation to be executed in parallel
3702       * @param searchFunction a function returning a non-null
3703       * result on success, else null
3704 +     * @param <U> the return type of the search function
3705       * @return a non-null result from applying the given search
3706       * function on each (key, value), or null if none
3707 +     * @since 1.8
3708       */
3709 <    public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3710 <        return ForkJoinTasks.search
3711 <            (this, searchFunction).invoke();
3709 >    public <U> U search(long parallelismThreshold,
3710 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3711 >        if (searchFunction == null) throw new NullPointerException();
3712 >        return new SearchMappingsTask<K,V,U>
3713 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3714 >             searchFunction, new AtomicReference<U>()).invoke();
3715      }
3716  
3717      /**
# Line 3390 | Line 3719 | public class ConcurrentHashMap<K, V>
3719       * of all (key, value) pairs using the given reducer to
3720       * combine values, or null if none.
3721       *
3722 +     * @param parallelismThreshold the (estimated) number of elements
3723 +     * needed for this operation to be executed in parallel
3724       * @param transformer a function returning the transformation
3725 <     * for an element, or null of there is no transformation (in
3726 <     * which case it is not combined).
3725 >     * for an element, or null if there is no transformation (in
3726 >     * which case it is not combined)
3727       * @param reducer a commutative associative combining function
3728 +     * @param <U> the return type of the transformer
3729       * @return the result of accumulating the given transformation
3730       * of all (key, value) pairs
3731 +     * @since 1.8
3732       */
3733 <    public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3734 <                        BiFun<? super U, ? super U, ? extends U> reducer) {
3735 <        return ForkJoinTasks.reduce
3736 <            (this, transformer, reducer).invoke();
3733 >    public <U> U reduce(long parallelismThreshold,
3734 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3735 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3736 >        if (transformer == null || reducer == null)
3737 >            throw new NullPointerException();
3738 >        return new MapReduceMappingsTask<K,V,U>
3739 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3740 >             null, transformer, reducer).invoke();
3741      }
3742  
3743      /**
# Line 3408 | Line 3745 | public class ConcurrentHashMap<K, V>
3745       * of all (key, value) pairs using the given reducer to
3746       * combine values, and the given basis as an identity value.
3747       *
3748 +     * @param parallelismThreshold the (estimated) number of elements
3749 +     * needed for this operation to be executed in parallel
3750       * @param transformer a function returning the transformation
3751       * for an element
3752       * @param basis the identity (initial default value) for the reduction
3753       * @param reducer a commutative associative combining function
3754       * @return the result of accumulating the given transformation
3755       * of all (key, value) pairs
3756 +     * @since 1.8
3757       */
3758 <    public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
3758 >    public double reduceToDouble(long parallelismThreshold,
3759 >                                 ToDoubleBiFunction<? super K, ? super V> transformer,
3760                                   double basis,
3761 <                                 DoubleByDoubleToDouble reducer) {
3762 <        return ForkJoinTasks.reduceToDouble
3763 <            (this, transformer, basis, reducer).invoke();
3761 >                                 DoubleBinaryOperator reducer) {
3762 >        if (transformer == null || reducer == null)
3763 >            throw new NullPointerException();
3764 >        return new MapReduceMappingsToDoubleTask<K,V>
3765 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3766 >             null, transformer, basis, reducer).invoke();
3767      }
3768  
3769      /**
# Line 3427 | Line 3771 | public class ConcurrentHashMap<K, V>
3771       * of all (key, value) pairs using the given reducer to
3772       * combine values, and the given basis as an identity value.
3773       *
3774 +     * @param parallelismThreshold the (estimated) number of elements
3775 +     * needed for this operation to be executed in parallel
3776       * @param transformer a function returning the transformation
3777       * for an element
3778       * @param basis the identity (initial default value) for the reduction
3779       * @param reducer a commutative associative combining function
3780       * @return the result of accumulating the given transformation
3781       * of all (key, value) pairs
3782 +     * @since 1.8
3783       */
3784 <    public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
3784 >    public long reduceToLong(long parallelismThreshold,
3785 >                             ToLongBiFunction<? super K, ? super V> transformer,
3786                               long basis,
3787 <                             LongByLongToLong reducer) {
3788 <        return ForkJoinTasks.reduceToLong
3789 <            (this, transformer, basis, reducer).invoke();
3787 >                             LongBinaryOperator reducer) {
3788 >        if (transformer == null || reducer == null)
3789 >            throw new NullPointerException();
3790 >        return new MapReduceMappingsToLongTask<K,V>
3791 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3792 >             null, transformer, basis, reducer).invoke();
3793      }
3794  
3795      /**
# Line 3446 | Line 3797 | public class ConcurrentHashMap<K, V>
3797       * of all (key, value) pairs using the given reducer to
3798       * combine values, and the given basis as an identity value.
3799       *
3800 +     * @param parallelismThreshold the (estimated) number of elements
3801 +     * needed for this operation to be executed in parallel
3802       * @param transformer a function returning the transformation
3803       * for an element
3804       * @param basis the identity (initial default value) for the reduction
3805       * @param reducer a commutative associative combining function
3806       * @return the result of accumulating the given transformation
3807       * of all (key, value) pairs
3808 +     * @since 1.8
3809       */
3810 <    public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
3810 >    public int reduceToInt(long parallelismThreshold,
3811 >                           ToIntBiFunction<? super K, ? super V> transformer,
3812                             int basis,
3813 <                           IntByIntToInt reducer) {
3814 <        return ForkJoinTasks.reduceToInt
3815 <            (this, transformer, basis, reducer).invoke();
3813 >                           IntBinaryOperator reducer) {
3814 >        if (transformer == null || reducer == null)
3815 >            throw new NullPointerException();
3816 >        return new MapReduceMappingsToIntTask<K,V>
3817 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3818 >             null, transformer, basis, reducer).invoke();
3819      }
3820  
3821      /**
3822       * Performs the given action for each key.
3823       *
3824 +     * @param parallelismThreshold the (estimated) number of elements
3825 +     * needed for this operation to be executed in parallel
3826       * @param action the action
3827 +     * @since 1.8
3828       */
3829 <    public void forEachKey(Action<K> action) {
3830 <        ForkJoinTasks.forEachKey
3831 <            (this, action).invoke();
3829 >    public void forEachKey(long parallelismThreshold,
3830 >                           Consumer<? super K> action) {
3831 >        if (action == null) throw new NullPointerException();
3832 >        new ForEachKeyTask<K,V>
3833 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3834 >             action).invoke();
3835      }
3836  
3837      /**
3838       * Performs the given action for each non-null transformation
3839       * of each key.
3840       *
3841 +     * @param parallelismThreshold the (estimated) number of elements
3842 +     * needed for this operation to be executed in parallel
3843       * @param transformer a function returning the transformation
3844 <     * for an element, or null of there is no transformation (in
3845 <     * which case the action is not applied).
3844 >     * for an element, or null if there is no transformation (in
3845 >     * which case the action is not applied)
3846       * @param action the action
3847 +     * @param <U> the return type of the transformer
3848 +     * @since 1.8
3849       */
3850 <    public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
3851 <                               Action<U> action) {
3852 <        ForkJoinTasks.forEachKey
3853 <            (this, transformer, action).invoke();
3850 >    public <U> void forEachKey(long parallelismThreshold,
3851 >                               Function<? super K, ? extends U> transformer,
3852 >                               Consumer<? super U> action) {
3853 >        if (transformer == null || action == null)
3854 >            throw new NullPointerException();
3855 >        new ForEachTransformedKeyTask<K,V,U>
3856 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3857 >             transformer, action).invoke();
3858      }
3859  
3860      /**
# Line 3492 | Line 3864 | public class ConcurrentHashMap<K, V>
3864       * any other parallel invocations of the search function are
3865       * ignored.
3866       *
3867 +     * @param parallelismThreshold the (estimated) number of elements
3868 +     * needed for this operation to be executed in parallel
3869       * @param searchFunction a function returning a non-null
3870       * result on success, else null
3871 +     * @param <U> the return type of the search function
3872       * @return a non-null result from applying the given search
3873       * function on each key, or null if none
3874 +     * @since 1.8
3875       */
3876 <    public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
3877 <        return ForkJoinTasks.searchKeys
3878 <            (this, searchFunction).invoke();
3876 >    public <U> U searchKeys(long parallelismThreshold,
3877 >                            Function<? super K, ? extends U> searchFunction) {
3878 >        if (searchFunction == null) throw new NullPointerException();
3879 >        return new SearchKeysTask<K,V,U>
3880 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3881 >             searchFunction, new AtomicReference<U>()).invoke();
3882      }
3883  
3884      /**
3885       * Returns the result of accumulating all keys using the given
3886       * reducer to combine values, or null if none.
3887       *
3888 +     * @param parallelismThreshold the (estimated) number of elements
3889 +     * needed for this operation to be executed in parallel
3890       * @param reducer a commutative associative combining function
3891       * @return the result of accumulating all keys using the given
3892       * reducer to combine values, or null if none
3893 +     * @since 1.8
3894       */
3895 <    public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
3896 <        return ForkJoinTasks.reduceKeys
3897 <            (this, reducer).invoke();
3895 >    public K reduceKeys(long parallelismThreshold,
3896 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3897 >        if (reducer == null) throw new NullPointerException();
3898 >        return new ReduceKeysTask<K,V>
3899 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3900 >             null, reducer).invoke();
3901      }
3902  
3903      /**
# Line 3520 | Line 3905 | public class ConcurrentHashMap<K, V>
3905       * of all keys using the given reducer to combine values, or
3906       * null if none.
3907       *
3908 +     * @param parallelismThreshold the (estimated) number of elements
3909 +     * needed for this operation to be executed in parallel
3910       * @param transformer a function returning the transformation
3911 <     * for an element, or null of there is no transformation (in
3912 <     * which case it is not combined).
3911 >     * for an element, or null if there is no transformation (in
3912 >     * which case it is not combined)
3913       * @param reducer a commutative associative combining function
3914 +     * @param <U> the return type of the transformer
3915       * @return the result of accumulating the given transformation
3916       * of all keys
3917 +     * @since 1.8
3918       */
3919 <    public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
3920 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
3921 <        return ForkJoinTasks.reduceKeys
3922 <            (this, transformer, reducer).invoke();
3919 >    public <U> U reduceKeys(long parallelismThreshold,
3920 >                            Function<? super K, ? extends U> transformer,
3921 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3922 >        if (transformer == null || reducer == null)
3923 >            throw new NullPointerException();
3924 >        return new MapReduceKeysTask<K,V,U>
3925 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3926 >             null, transformer, reducer).invoke();
3927      }
3928  
3929      /**
# Line 3538 | Line 3931 | public class ConcurrentHashMap<K, V>
3931       * of all keys using the given reducer to combine values, and
3932       * the given basis as an identity value.
3933       *
3934 +     * @param parallelismThreshold the (estimated) number of elements
3935 +     * needed for this operation to be executed in parallel
3936       * @param transformer a function returning the transformation
3937       * for an element
3938       * @param basis the identity (initial default value) for the reduction
3939       * @param reducer a commutative associative combining function
3940 <     * @return  the result of accumulating the given transformation
3940 >     * @return the result of accumulating the given transformation
3941       * of all keys
3942 +     * @since 1.8
3943       */
3944 <    public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
3944 >    public double reduceKeysToDouble(long parallelismThreshold,
3945 >                                     ToDoubleFunction<? super K> transformer,
3946                                       double basis,
3947 <                                     DoubleByDoubleToDouble reducer) {
3948 <        return ForkJoinTasks.reduceKeysToDouble
3949 <            (this, transformer, basis, reducer).invoke();
3947 >                                     DoubleBinaryOperator reducer) {
3948 >        if (transformer == null || reducer == null)
3949 >            throw new NullPointerException();
3950 >        return new MapReduceKeysToDoubleTask<K,V>
3951 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3952 >             null, transformer, basis, reducer).invoke();
3953      }
3954  
3955      /**
# Line 3557 | Line 3957 | public class ConcurrentHashMap<K, V>
3957       * of all keys using the given reducer to combine values, and
3958       * the given basis as an identity value.
3959       *
3960 +     * @param parallelismThreshold the (estimated) number of elements
3961 +     * needed for this operation to be executed in parallel
3962       * @param transformer a function returning the transformation
3963       * for an element
3964       * @param basis the identity (initial default value) for the reduction
3965       * @param reducer a commutative associative combining function
3966       * @return the result of accumulating the given transformation
3967       * of all keys
3968 +     * @since 1.8
3969       */
3970 <    public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3970 >    public long reduceKeysToLong(long parallelismThreshold,
3971 >                                 ToLongFunction<? super K> transformer,
3972                                   long basis,
3973 <                                 LongByLongToLong reducer) {
3974 <        return ForkJoinTasks.reduceKeysToLong
3975 <            (this, transformer, basis, reducer).invoke();
3973 >                                 LongBinaryOperator reducer) {
3974 >        if (transformer == null || reducer == null)
3975 >            throw new NullPointerException();
3976 >        return new MapReduceKeysToLongTask<K,V>
3977 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3978 >             null, transformer, basis, reducer).invoke();
3979      }
3980  
3981      /**
# Line 3576 | Line 3983 | public class ConcurrentHashMap<K, V>
3983       * of all keys using the given reducer to combine values, and
3984       * the given basis as an identity value.
3985       *
3986 +     * @param parallelismThreshold the (estimated) number of elements
3987 +     * needed for this operation to be executed in parallel
3988       * @param transformer a function returning the transformation
3989       * for an element
3990       * @param basis the identity (initial default value) for the reduction
3991       * @param reducer a commutative associative combining function
3992       * @return the result of accumulating the given transformation
3993       * of all keys
3994 +     * @since 1.8
3995       */
3996 <    public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3996 >    public int reduceKeysToInt(long parallelismThreshold,
3997 >                               ToIntFunction<? super K> transformer,
3998                                 int basis,
3999 <                               IntByIntToInt reducer) {
4000 <        return ForkJoinTasks.reduceKeysToInt
4001 <            (this, transformer, basis, reducer).invoke();
3999 >                               IntBinaryOperator reducer) {
4000 >        if (transformer == null || reducer == null)
4001 >            throw new NullPointerException();
4002 >        return new MapReduceKeysToIntTask<K,V>
4003 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4004 >             null, transformer, basis, reducer).invoke();
4005      }
4006  
4007      /**
4008       * Performs the given action for each value.
4009       *
4010 +     * @param parallelismThreshold the (estimated) number of elements
4011 +     * needed for this operation to be executed in parallel
4012       * @param action the action
4013 +     * @since 1.8
4014       */
4015 <    public void forEachValue(Action<V> action) {
4016 <        ForkJoinTasks.forEachValue
4017 <            (this, action).invoke();
4015 >    public void forEachValue(long parallelismThreshold,
4016 >                             Consumer<? super V> action) {
4017 >        if (action == null)
4018 >            throw new NullPointerException();
4019 >        new ForEachValueTask<K,V>
4020 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4021 >             action).invoke();
4022      }
4023  
4024      /**
4025       * Performs the given action for each non-null transformation
4026       * of each value.
4027       *
4028 +     * @param parallelismThreshold the (estimated) number of elements
4029 +     * needed for this operation to be executed in parallel
4030       * @param transformer a function returning the transformation
4031 <     * for an element, or null of there is no transformation (in
4032 <     * which case the action is not applied).
4031 >     * for an element, or null if there is no transformation (in
4032 >     * which case the action is not applied)
4033 >     * @param action the action
4034 >     * @param <U> the return type of the transformer
4035 >     * @since 1.8
4036       */
4037 <    public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
4038 <                                 Action<U> action) {
4039 <        ForkJoinTasks.forEachValue
4040 <            (this, transformer, action).invoke();
4037 >    public <U> void forEachValue(long parallelismThreshold,
4038 >                                 Function<? super V, ? extends U> transformer,
4039 >                                 Consumer<? super U> action) {
4040 >        if (transformer == null || action == null)
4041 >            throw new NullPointerException();
4042 >        new ForEachTransformedValueTask<K,V,U>
4043 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4044 >             transformer, action).invoke();
4045      }
4046  
4047      /**
# Line 3621 | Line 4051 | public class ConcurrentHashMap<K, V>
4051       * any other parallel invocations of the search function are
4052       * ignored.
4053       *
4054 +     * @param parallelismThreshold the (estimated) number of elements
4055 +     * needed for this operation to be executed in parallel
4056       * @param searchFunction a function returning a non-null
4057       * result on success, else null
4058 +     * @param <U> the return type of the search function
4059       * @return a non-null result from applying the given search
4060       * function on each value, or null if none
4061 <     *
4061 >     * @since 1.8
4062       */
4063 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
4064 <        return ForkJoinTasks.searchValues
4065 <            (this, searchFunction).invoke();
4063 >    public <U> U searchValues(long parallelismThreshold,
4064 >                              Function<? super V, ? extends U> searchFunction) {
4065 >        if (searchFunction == null) throw new NullPointerException();
4066 >        return new SearchValuesTask<K,V,U>
4067 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4068 >             searchFunction, new AtomicReference<U>()).invoke();
4069      }
4070  
4071      /**
4072       * Returns the result of accumulating all values using the
4073       * given reducer to combine values, or null if none.
4074       *
4075 +     * @param parallelismThreshold the (estimated) number of elements
4076 +     * needed for this operation to be executed in parallel
4077       * @param reducer a commutative associative combining function
4078 <     * @return  the result of accumulating all values
4078 >     * @return the result of accumulating all values
4079 >     * @since 1.8
4080       */
4081 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
4082 <        return ForkJoinTasks.reduceValues
4083 <            (this, reducer).invoke();
4081 >    public V reduceValues(long parallelismThreshold,
4082 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
4083 >        if (reducer == null) throw new NullPointerException();
4084 >        return new ReduceValuesTask<K,V>
4085 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4086 >             null, reducer).invoke();
4087      }
4088  
4089      /**
# Line 3649 | Line 4091 | public class ConcurrentHashMap<K, V>
4091       * of all values using the given reducer to combine values, or
4092       * null if none.
4093       *
4094 +     * @param parallelismThreshold the (estimated) number of elements
4095 +     * needed for this operation to be executed in parallel
4096       * @param transformer a function returning the transformation
4097 <     * for an element, or null of there is no transformation (in
4098 <     * which case it is not combined).
4097 >     * for an element, or null if there is no transformation (in
4098 >     * which case it is not combined)
4099       * @param reducer a commutative associative combining function
4100 +     * @param <U> the return type of the transformer
4101       * @return the result of accumulating the given transformation
4102       * of all values
4103 +     * @since 1.8
4104       */
4105 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
4106 <                              BiFun<? super U, ? super U, ? extends U> reducer) {
4107 <        return ForkJoinTasks.reduceValues
4108 <            (this, transformer, reducer).invoke();
4105 >    public <U> U reduceValues(long parallelismThreshold,
4106 >                              Function<? super V, ? extends U> transformer,
4107 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
4108 >        if (transformer == null || reducer == null)
4109 >            throw new NullPointerException();
4110 >        return new MapReduceValuesTask<K,V,U>
4111 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4112 >             null, transformer, reducer).invoke();
4113      }
4114  
4115      /**
# Line 3667 | Line 4117 | public class ConcurrentHashMap<K, V>
4117       * of all values using the given reducer to combine values,
4118       * and the given basis as an identity value.
4119       *
4120 +     * @param parallelismThreshold the (estimated) number of elements
4121 +     * needed for this operation to be executed in parallel
4122       * @param transformer a function returning the transformation
4123       * for an element
4124       * @param basis the identity (initial default value) for the reduction
4125       * @param reducer a commutative associative combining function
4126       * @return the result of accumulating the given transformation
4127       * of all values
4128 +     * @since 1.8
4129       */
4130 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
4130 >    public double reduceValuesToDouble(long parallelismThreshold,
4131 >                                       ToDoubleFunction<? super V> transformer,
4132                                         double basis,
4133 <                                       DoubleByDoubleToDouble reducer) {
4134 <        return ForkJoinTasks.reduceValuesToDouble
4135 <            (this, transformer, basis, reducer).invoke();
4133 >                                       DoubleBinaryOperator reducer) {
4134 >        if (transformer == null || reducer == null)
4135 >            throw new NullPointerException();
4136 >        return new MapReduceValuesToDoubleTask<K,V>
4137 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4138 >             null, transformer, basis, reducer).invoke();
4139      }
4140  
4141      /**
# Line 3686 | Line 4143 | public class ConcurrentHashMap<K, V>
4143       * of all values using the given reducer to combine values,
4144       * and the given basis as an identity value.
4145       *
4146 +     * @param parallelismThreshold the (estimated) number of elements
4147 +     * needed for this operation to be executed in parallel
4148       * @param transformer a function returning the transformation
4149       * for an element
4150       * @param basis the identity (initial default value) for the reduction
4151       * @param reducer a commutative associative combining function
4152       * @return the result of accumulating the given transformation
4153       * of all values
4154 +     * @since 1.8
4155       */
4156 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
4156 >    public long reduceValuesToLong(long parallelismThreshold,
4157 >                                   ToLongFunction<? super V> transformer,
4158                                     long basis,
4159 <                                   LongByLongToLong reducer) {
4160 <        return ForkJoinTasks.reduceValuesToLong
4161 <            (this, transformer, basis, reducer).invoke();
4159 >                                   LongBinaryOperator reducer) {
4160 >        if (transformer == null || reducer == null)
4161 >            throw new NullPointerException();
4162 >        return new MapReduceValuesToLongTask<K,V>
4163 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4164 >             null, transformer, basis, reducer).invoke();
4165      }
4166  
4167      /**
# Line 3705 | Line 4169 | public class ConcurrentHashMap<K, V>
4169       * of all values using the given reducer to combine values,
4170       * and the given basis as an identity value.
4171       *
4172 +     * @param parallelismThreshold the (estimated) number of elements
4173 +     * needed for this operation to be executed in parallel
4174       * @param transformer a function returning the transformation
4175       * for an element
4176       * @param basis the identity (initial default value) for the reduction
4177       * @param reducer a commutative associative combining function
4178       * @return the result of accumulating the given transformation
4179       * of all values
4180 +     * @since 1.8
4181       */
4182 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4182 >    public int reduceValuesToInt(long parallelismThreshold,
4183 >                                 ToIntFunction<? super V> transformer,
4184                                   int basis,
4185 <                                 IntByIntToInt reducer) {
4186 <        return ForkJoinTasks.reduceValuesToInt
4187 <            (this, transformer, basis, reducer).invoke();
4185 >                                 IntBinaryOperator reducer) {
4186 >        if (transformer == null || reducer == null)
4187 >            throw new NullPointerException();
4188 >        return new MapReduceValuesToIntTask<K,V>
4189 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4190 >             null, transformer, basis, reducer).invoke();
4191      }
4192  
4193      /**
4194       * Performs the given action for each entry.
4195       *
4196 +     * @param parallelismThreshold the (estimated) number of elements
4197 +     * needed for this operation to be executed in parallel
4198       * @param action the action
4199 +     * @since 1.8
4200       */
4201 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
4202 <        ForkJoinTasks.forEachEntry
4203 <            (this, action).invoke();
4201 >    public void forEachEntry(long parallelismThreshold,
4202 >                             Consumer<? super Map.Entry<K,V>> action) {
4203 >        if (action == null) throw new NullPointerException();
4204 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4205 >                                  action).invoke();
4206      }
4207  
4208      /**
4209       * Performs the given action for each non-null transformation
4210       * of each entry.
4211       *
4212 +     * @param parallelismThreshold the (estimated) number of elements
4213 +     * needed for this operation to be executed in parallel
4214       * @param transformer a function returning the transformation
4215 <     * for an element, or null of there is no transformation (in
4216 <     * which case the action is not applied).
4215 >     * for an element, or null if there is no transformation (in
4216 >     * which case the action is not applied)
4217       * @param action the action
4218 +     * @param <U> the return type of the transformer
4219 +     * @since 1.8
4220       */
4221 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4222 <                                 Action<U> action) {
4223 <        ForkJoinTasks.forEachEntry
4224 <            (this, transformer, action).invoke();
4221 >    public <U> void forEachEntry(long parallelismThreshold,
4222 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
4223 >                                 Consumer<? super U> action) {
4224 >        if (transformer == null || action == null)
4225 >            throw new NullPointerException();
4226 >        new ForEachTransformedEntryTask<K,V,U>
4227 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4228 >             transformer, action).invoke();
4229      }
4230  
4231      /**
# Line 3751 | Line 4235 | public class ConcurrentHashMap<K, V>
4235       * any other parallel invocations of the search function are
4236       * ignored.
4237       *
4238 +     * @param parallelismThreshold the (estimated) number of elements
4239 +     * needed for this operation to be executed in parallel
4240       * @param searchFunction a function returning a non-null
4241       * result on success, else null
4242 +     * @param <U> the return type of the search function
4243       * @return a non-null result from applying the given search
4244       * function on each entry, or null if none
4245 +     * @since 1.8
4246       */
4247 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4248 <        return ForkJoinTasks.searchEntries
4249 <            (this, searchFunction).invoke();
4247 >    public <U> U searchEntries(long parallelismThreshold,
4248 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4249 >        if (searchFunction == null) throw new NullPointerException();
4250 >        return new SearchEntriesTask<K,V,U>
4251 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4252 >             searchFunction, new AtomicReference<U>()).invoke();
4253      }
4254  
4255      /**
4256       * Returns the result of accumulating all entries using the
4257       * given reducer to combine values, or null if none.
4258       *
4259 +     * @param parallelismThreshold the (estimated) number of elements
4260 +     * needed for this operation to be executed in parallel
4261       * @param reducer a commutative associative combining function
4262       * @return the result of accumulating all entries
4263 +     * @since 1.8
4264       */
4265 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4266 <        return ForkJoinTasks.reduceEntries
4267 <            (this, reducer).invoke();
4265 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4266 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4267 >        if (reducer == null) throw new NullPointerException();
4268 >        return new ReduceEntriesTask<K,V>
4269 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4270 >             null, reducer).invoke();
4271      }
4272  
4273      /**
# Line 3778 | Line 4275 | public class ConcurrentHashMap<K, V>
4275       * of all entries using the given reducer to combine values,
4276       * or null if none.
4277       *
4278 +     * @param parallelismThreshold the (estimated) number of elements
4279 +     * needed for this operation to be executed in parallel
4280       * @param transformer a function returning the transformation
4281 <     * for an element, or null of there is no transformation (in
4282 <     * which case it is not combined).
4281 >     * for an element, or null if there is no transformation (in
4282 >     * which case it is not combined)
4283       * @param reducer a commutative associative combining function
4284 +     * @param <U> the return type of the transformer
4285       * @return the result of accumulating the given transformation
4286       * of all entries
4287 +     * @since 1.8
4288       */
4289 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4290 <                               BiFun<? super U, ? super U, ? extends U> reducer) {
4291 <        return ForkJoinTasks.reduceEntries
4292 <            (this, transformer, reducer).invoke();
4289 >    public <U> U reduceEntries(long parallelismThreshold,
4290 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
4291 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
4292 >        if (transformer == null || reducer == null)
4293 >            throw new NullPointerException();
4294 >        return new MapReduceEntriesTask<K,V,U>
4295 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4296 >             null, transformer, reducer).invoke();
4297      }
4298  
4299      /**
# Line 3796 | Line 4301 | public class ConcurrentHashMap<K, V>
4301       * of all entries using the given reducer to combine values,
4302       * and the given basis as an identity value.
4303       *
4304 +     * @param parallelismThreshold the (estimated) number of elements
4305 +     * needed for this operation to be executed in parallel
4306       * @param transformer a function returning the transformation
4307       * for an element
4308       * @param basis the identity (initial default value) for the reduction
4309       * @param reducer a commutative associative combining function
4310       * @return the result of accumulating the given transformation
4311       * of all entries
4312 +     * @since 1.8
4313       */
4314 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4314 >    public double reduceEntriesToDouble(long parallelismThreshold,
4315 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
4316                                          double basis,
4317 <                                        DoubleByDoubleToDouble reducer) {
4318 <        return ForkJoinTasks.reduceEntriesToDouble
4319 <            (this, transformer, basis, reducer).invoke();
4317 >                                        DoubleBinaryOperator reducer) {
4318 >        if (transformer == null || reducer == null)
4319 >            throw new NullPointerException();
4320 >        return new MapReduceEntriesToDoubleTask<K,V>
4321 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4322 >             null, transformer, basis, reducer).invoke();
4323      }
4324  
4325      /**
# Line 3815 | Line 4327 | public class ConcurrentHashMap<K, V>
4327       * of all entries using the given reducer to combine values,
4328       * and the given basis as an identity value.
4329       *
4330 +     * @param parallelismThreshold the (estimated) number of elements
4331 +     * needed for this operation to be executed in parallel
4332       * @param transformer a function returning the transformation
4333       * for an element
4334       * @param basis the identity (initial default value) for the reduction
4335       * @param reducer a commutative associative combining function
4336 <     * @return  the result of accumulating the given transformation
4336 >     * @return the result of accumulating the given transformation
4337       * of all entries
4338 +     * @since 1.8
4339       */
4340 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4340 >    public long reduceEntriesToLong(long parallelismThreshold,
4341 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
4342                                      long basis,
4343 <                                    LongByLongToLong reducer) {
4344 <        return ForkJoinTasks.reduceEntriesToLong
4345 <            (this, transformer, basis, reducer).invoke();
4343 >                                    LongBinaryOperator reducer) {
4344 >        if (transformer == null || reducer == null)
4345 >            throw new NullPointerException();
4346 >        return new MapReduceEntriesToLongTask<K,V>
4347 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4348 >             null, transformer, basis, reducer).invoke();
4349      }
4350  
4351      /**
# Line 3834 | Line 4353 | public class ConcurrentHashMap<K, V>
4353       * of all entries using the given reducer to combine values,
4354       * and the given basis as an identity value.
4355       *
4356 +     * @param parallelismThreshold the (estimated) number of elements
4357 +     * needed for this operation to be executed in parallel
4358       * @param transformer a function returning the transformation
4359       * for an element
4360       * @param basis the identity (initial default value) for the reduction
4361       * @param reducer a commutative associative combining function
4362       * @return the result of accumulating the given transformation
4363       * of all entries
4364 +     * @since 1.8
4365       */
4366 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4366 >    public int reduceEntriesToInt(long parallelismThreshold,
4367 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
4368                                    int basis,
4369 <                                  IntByIntToInt reducer) {
4370 <        return ForkJoinTasks.reduceEntriesToInt
4371 <            (this, transformer, basis, reducer).invoke();
4369 >                                  IntBinaryOperator reducer) {
4370 >        if (transformer == null || reducer == null)
4371 >            throw new NullPointerException();
4372 >        return new MapReduceEntriesToIntTask<K,V>
4373 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4374 >             null, transformer, basis, reducer).invoke();
4375      }
4376  
4377 +
4378      /* ----------------Views -------------- */
4379  
4380      /**
4381       * Base class for views.
4382       */
4383 <    static abstract class CHMView<K, V> {
4384 <        final ConcurrentHashMap<K, V> map;
4385 <        CHMView(ConcurrentHashMap<K, V> map)  { this.map = map; }
4383 >    abstract static class CollectionView<K,V,E>
4384 >        implements Collection<E>, java.io.Serializable {
4385 >        private static final long serialVersionUID = 7249069246763182397L;
4386 >        final ConcurrentHashMap<K,V> map;
4387 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4388  
4389          /**
4390           * Returns the map backing this view.
# Line 3864 | Line 4393 | public class ConcurrentHashMap<K, V>
4393           */
4394          public ConcurrentHashMap<K,V> getMap() { return map; }
4395  
4396 <        public final int size()                 { return map.size(); }
4397 <        public final boolean isEmpty()          { return map.isEmpty(); }
4398 <        public final void clear()               { map.clear(); }
4396 >        /**
4397 >         * Removes all of the elements from this view, by removing all
4398 >         * the mappings from the map backing this view.
4399 >         */
4400 >        public final void clear()      { map.clear(); }
4401 >        public final int size()        { return map.size(); }
4402 >        public final boolean isEmpty() { return map.isEmpty(); }
4403  
4404          // implementations below rely on concrete classes supplying these
4405 <        abstract public Iterator<?> iterator();
4406 <        abstract public boolean contains(Object o);
4407 <        abstract public boolean remove(Object o);
4405 >        // abstract methods
4406 >        /**
4407 >         * Returns an iterator over the elements in this collection.
4408 >         *
4409 >         * <p>The returned iterator is
4410 >         * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
4411 >         *
4412 >         * @return an iterator over the elements in this collection
4413 >         */
4414 >        public abstract Iterator<E> iterator();
4415 >        public abstract boolean contains(Object o);
4416 >        public abstract boolean remove(Object o);
4417  
4418 <        private static final String oomeMsg = "Required array size too large";
4418 >        private static final String OOME_MSG = "Required array size too large";
4419  
4420          public final Object[] toArray() {
4421              long sz = map.mappingCount();
4422 <            if (sz > (long)(MAX_ARRAY_SIZE))
4423 <                throw new OutOfMemoryError(oomeMsg);
4422 >            if (sz > MAX_ARRAY_SIZE)
4423 >                throw new OutOfMemoryError(OOME_MSG);
4424              int n = (int)sz;
4425              Object[] r = new Object[n];
4426              int i = 0;
4427 <            Iterator<?> it = iterator();
3886 <            while (it.hasNext()) {
4427 >            for (E e : this) {
4428                  if (i == n) {
4429                      if (n >= MAX_ARRAY_SIZE)
4430 <                        throw new OutOfMemoryError(oomeMsg);
4430 >                        throw new OutOfMemoryError(OOME_MSG);
4431                      if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4432                          n = MAX_ARRAY_SIZE;
4433                      else
4434                          n += (n >>> 1) + 1;
4435                      r = Arrays.copyOf(r, n);
4436                  }
4437 <                r[i++] = it.next();
4437 >                r[i++] = e;
4438              }
4439              return (i == n) ? r : Arrays.copyOf(r, i);
4440          }
4441  
4442 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4442 >        @SuppressWarnings("unchecked")
4443 >        public final <T> T[] toArray(T[] a) {
4444              long sz = map.mappingCount();
4445 <            if (sz > (long)(MAX_ARRAY_SIZE))
4446 <                throw new OutOfMemoryError(oomeMsg);
4445 >            if (sz > MAX_ARRAY_SIZE)
4446 >                throw new OutOfMemoryError(OOME_MSG);
4447              int m = (int)sz;
4448              T[] r = (a.length >= m) ? a :
4449                  (T[])java.lang.reflect.Array
4450                  .newInstance(a.getClass().getComponentType(), m);
4451              int n = r.length;
4452              int i = 0;
4453 <            Iterator<?> it = iterator();
3912 <            while (it.hasNext()) {
4453 >            for (E e : this) {
4454                  if (i == n) {
4455                      if (n >= MAX_ARRAY_SIZE)
4456 <                        throw new OutOfMemoryError(oomeMsg);
4456 >                        throw new OutOfMemoryError(OOME_MSG);
4457                      if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4458                          n = MAX_ARRAY_SIZE;
4459                      else
4460                          n += (n >>> 1) + 1;
4461                      r = Arrays.copyOf(r, n);
4462                  }
4463 <                r[i++] = (T)it.next();
4463 >                r[i++] = (T)e;
4464              }
4465              if (a == r && i < n) {
4466                  r[i] = null; // null-terminate
# Line 3928 | Line 4469 | public class ConcurrentHashMap<K, V>
4469              return (i == n) ? r : Arrays.copyOf(r, i);
4470          }
4471  
4472 <        public final int hashCode() {
4473 <            int h = 0;
4474 <            for (Iterator<?> it = iterator(); it.hasNext();)
4475 <                h += it.next().hashCode();
4476 <            return h;
4477 <        }
4478 <
4472 >        /**
4473 >         * Returns a string representation of this collection.
4474 >         * The string representation consists of the string representations
4475 >         * of the collection's elements in the order they are returned by
4476 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4477 >         * Adjacent elements are separated by the characters {@code ", "}
4478 >         * (comma and space).  Elements are converted to strings as by
4479 >         * {@link String#valueOf(Object)}.
4480 >         *
4481 >         * @return a string representation of this collection
4482 >         */
4483          public final String toString() {
4484              StringBuilder sb = new StringBuilder();
4485              sb.append('[');
4486 <            Iterator<?> it = iterator();
4486 >            Iterator<E> it = iterator();
4487              if (it.hasNext()) {
4488                  for (;;) {
4489                      Object e = it.next();
# Line 3953 | Line 4498 | public class ConcurrentHashMap<K, V>
4498  
4499          public final boolean containsAll(Collection<?> c) {
4500              if (c != this) {
4501 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
3957 <                    Object e = it.next();
4501 >                for (Object e : c) {
4502                      if (e == null || !contains(e))
4503                          return false;
4504                  }
# Line 3962 | Line 4506 | public class ConcurrentHashMap<K, V>
4506              return true;
4507          }
4508  
4509 <        public final boolean removeAll(Collection<?> c) {
4509 >        public boolean removeAll(Collection<?> c) {
4510 >            if (c == null) throw new NullPointerException();
4511              boolean modified = false;
4512 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4513 <                if (c.contains(it.next())) {
4514 <                    it.remove();
4515 <                    modified = true;
4512 >            // Use (c instanceof Set) as a hint that lookup in c is as
4513 >            // efficient as this view
4514 >            Node<K,V>[] t;
4515 >            if ((t = map.table) == null) {
4516 >                return false;
4517 >            } else if (c instanceof Set<?> && c.size() > t.length) {
4518 >                for (Iterator<?> it = iterator(); it.hasNext(); ) {
4519 >                    if (c.contains(it.next())) {
4520 >                        it.remove();
4521 >                        modified = true;
4522 >                    }
4523                  }
4524 +            } else {
4525 +                for (Object e : c)
4526 +                    modified |= remove(e);
4527              }
4528              return modified;
4529          }
4530  
4531          public final boolean retainAll(Collection<?> c) {
4532 +            if (c == null) throw new NullPointerException();
4533              boolean modified = false;
4534 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4534 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4535                  if (!c.contains(it.next())) {
4536                      it.remove();
4537                      modified = true;
# Line 3989 | Line 4545 | public class ConcurrentHashMap<K, V>
4545      /**
4546       * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4547       * which additions may optionally be enabled by mapping to a
4548 <     * common value.  This class cannot be directly instantiated. See
4549 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4550 <     * {@link #newKeySet(int)}.
4548 >     * common value.  This class cannot be directly instantiated.
4549 >     * See {@link #keySet() keySet()},
4550 >     * {@link #keySet(Object) keySet(V)},
4551 >     * {@link #newKeySet() newKeySet()},
4552 >     * {@link #newKeySet(int) newKeySet(int)}.
4553 >     *
4554 >     * @since 1.8
4555       */
4556 <    public static class KeySetView<K,V> extends CHMView<K,V>
4556 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4557          implements Set<K>, java.io.Serializable {
4558          private static final long serialVersionUID = 7249069246763182397L;
4559          private final V value;
4560 <        KeySetView(ConcurrentHashMap<K, V> map, V value) {  // non-public
4560 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4561              super(map);
4562              this.value = value;
4563          }
# Line 4007 | Line 4567 | public class ConcurrentHashMap<K, V>
4567           * or {@code null} if additions are not supported.
4568           *
4569           * @return the default mapped value for additions, or {@code null}
4570 <         * if not supported.
4570 >         * if not supported
4571           */
4572          public V getMappedValue() { return value; }
4573  
4574 <        // implement Set API
4575 <
4574 >        /**
4575 >         * {@inheritDoc}
4576 >         * @throws NullPointerException if the specified key is null
4577 >         */
4578          public boolean contains(Object o) { return map.containsKey(o); }
4017        public boolean remove(Object o)   { return map.remove(o) != null; }
4579  
4580          /**
4581 <         * Returns a "weakly consistent" iterator that will never
4582 <         * throw {@link ConcurrentModificationException}, and
4583 <         * guarantees to traverse elements as they existed upon
4584 <         * construction of the iterator, and may (but is not
4585 <         * guaranteed to) reflect any modifications subsequent to
4586 <         * construction.
4581 >         * Removes the key from this map view, by removing the key (and its
4582 >         * corresponding value) from the backing map.  This method does
4583 >         * nothing if the key is not in the map.
4584 >         *
4585 >         * @param  o the key to be removed from the backing map
4586 >         * @return {@code true} if the backing map contained the specified key
4587 >         * @throws NullPointerException if the specified key is null
4588 >         */
4589 >        public boolean remove(Object o) { return map.remove(o) != null; }
4590 >
4591 >        /**
4592 >         * @return an iterator over the keys of the backing map
4593 >         */
4594 >        public Iterator<K> iterator() {
4595 >            Node<K,V>[] t;
4596 >            ConcurrentHashMap<K,V> m = map;
4597 >            int f = (t = m.table) == null ? 0 : t.length;
4598 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4599 >        }
4600 >
4601 >        /**
4602 >         * Adds the specified key to this set view by mapping the key to
4603 >         * the default mapped value in the backing map, if defined.
4604           *
4605 <         * @return an iterator over the keys of this map
4605 >         * @param e key to be added
4606 >         * @return {@code true} if this set changed as a result of the call
4607 >         * @throws NullPointerException if the specified key is null
4608 >         * @throws UnsupportedOperationException if no default mapped value
4609 >         * for additions was provided
4610           */
4029        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4611          public boolean add(K e) {
4612              V v;
4613              if ((v = value) == null)
4614                  throw new UnsupportedOperationException();
4615 <            if (e == null)
4035 <                throw new NullPointerException();
4036 <            return map.internalPut(e, v, true) == null;
4615 >            return map.putVal(e, v, true) == null;
4616          }
4617 +
4618 +        /**
4619 +         * Adds all of the elements in the specified collection to this set,
4620 +         * as if by calling {@link #add} on each one.
4621 +         *
4622 +         * @param c the elements to be inserted into this set
4623 +         * @return {@code true} if this set changed as a result of the call
4624 +         * @throws NullPointerException if the collection or any of its
4625 +         * elements are {@code null}
4626 +         * @throws UnsupportedOperationException if no default mapped value
4627 +         * for additions was provided
4628 +         */
4629          public boolean addAll(Collection<? extends K> c) {
4630              boolean added = false;
4631              V v;
4632              if ((v = value) == null)
4633                  throw new UnsupportedOperationException();
4634              for (K e : c) {
4635 <                if (e == null)
4045 <                    throw new NullPointerException();
4046 <                if (map.internalPut(e, v, true) == null)
4635 >                if (map.putVal(e, v, true) == null)
4636                      added = true;
4637              }
4638              return added;
4639          }
4640 +
4641 +        public int hashCode() {
4642 +            int h = 0;
4643 +            for (K e : this)
4644 +                h += e.hashCode();
4645 +            return h;
4646 +        }
4647 +
4648          public boolean equals(Object o) {
4649              Set<?> c;
4650              return ((o instanceof Set) &&
# Line 4055 | Line 4652 | public class ConcurrentHashMap<K, V>
4652                       (containsAll(c) && c.containsAll(this))));
4653          }
4654  
4655 <        /**
4656 <         * Performs the given action for each key.
4657 <         *
4658 <         * @param action the action
4659 <         */
4660 <        public void forEach(Action<K> action) {
4064 <            ForkJoinTasks.forEachKey
4065 <                (map, action).invoke();
4066 <        }
4067 <
4068 <        /**
4069 <         * Performs the given action for each non-null transformation
4070 <         * of each key.
4071 <         *
4072 <         * @param transformer a function returning the transformation
4073 <         * for an element, or null of there is no transformation (in
4074 <         * which case the action is not applied).
4075 <         * @param action the action
4076 <         */
4077 <        public <U> void forEach(Fun<? super K, ? extends U> transformer,
4078 <                                Action<U> action) {
4079 <            ForkJoinTasks.forEachKey
4080 <                (map, transformer, action).invoke();
4081 <        }
4082 <
4083 <        /**
4084 <         * Returns a non-null result from applying the given search
4085 <         * function on each key, or null if none. Upon success,
4086 <         * further element processing is suppressed and the results of
4087 <         * any other parallel invocations of the search function are
4088 <         * ignored.
4089 <         *
4090 <         * @param searchFunction a function returning a non-null
4091 <         * result on success, else null
4092 <         * @return a non-null result from applying the given search
4093 <         * function on each key, or null if none
4094 <         */
4095 <        public <U> U search(Fun<? super K, ? extends U> searchFunction) {
4096 <            return ForkJoinTasks.searchKeys
4097 <                (map, searchFunction).invoke();
4098 <        }
4099 <
4100 <        /**
4101 <         * Returns the result of accumulating all keys using the given
4102 <         * reducer to combine values, or null if none.
4103 <         *
4104 <         * @param reducer a commutative associative combining function
4105 <         * @return the result of accumulating all keys using the given
4106 <         * reducer to combine values, or null if none
4107 <         */
4108 <        public K reduce(BiFun<? super K, ? super K, ? extends K> reducer) {
4109 <            return ForkJoinTasks.reduceKeys
4110 <                (map, reducer).invoke();
4111 <        }
4112 <
4113 <        /**
4114 <         * Returns the result of accumulating the given transformation
4115 <         * of all keys using the given reducer to combine values, and
4116 <         * the given basis as an identity value.
4117 <         *
4118 <         * @param transformer a function returning the transformation
4119 <         * for an element
4120 <         * @param basis the identity (initial default value) for the reduction
4121 <         * @param reducer a commutative associative combining function
4122 <         * @return  the result of accumulating the given transformation
4123 <         * of all keys
4124 <         */
4125 <        public double reduceToDouble(ObjectToDouble<? super K> transformer,
4126 <                                     double basis,
4127 <                                     DoubleByDoubleToDouble reducer) {
4128 <            return ForkJoinTasks.reduceKeysToDouble
4129 <                (map, transformer, basis, reducer).invoke();
4130 <        }
4131 <
4132 <        /**
4133 <         * Returns the result of accumulating the given transformation
4134 <         * of all keys using the given reducer to combine values, and
4135 <         * the given basis as an identity value.
4136 <         *
4137 <         * @param transformer a function returning the transformation
4138 <         * for an element
4139 <         * @param basis the identity (initial default value) for the reduction
4140 <         * @param reducer a commutative associative combining function
4141 <         * @return the result of accumulating the given transformation
4142 <         * of all keys
4143 <         */
4144 <        public long reduceToLong(ObjectToLong<? super K> transformer,
4145 <                                 long basis,
4146 <                                 LongByLongToLong reducer) {
4147 <            return ForkJoinTasks.reduceKeysToLong
4148 <                (map, transformer, basis, reducer).invoke();
4655 >        public Spliterator<K> spliterator() {
4656 >            Node<K,V>[] t;
4657 >            ConcurrentHashMap<K,V> m = map;
4658 >            long n = m.sumCount();
4659 >            int f = (t = m.table) == null ? 0 : t.length;
4660 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4661          }
4662  
4663 <        /**
4664 <         * Returns the result of accumulating the given transformation
4665 <         * of all keys using the given reducer to combine values, and
4666 <         * the given basis as an identity value.
4667 <         *
4668 <         * @param transformer a function returning the transformation
4669 <         * for an element
4670 <         * @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 keys
4162 <         */
4163 <        public int reduceToInt(ObjectToInt<? super K> transformer,
4164 <                               int basis,
4165 <                               IntByIntToInt reducer) {
4166 <            return ForkJoinTasks.reduceKeysToInt
4167 <                (map, transformer, basis, reducer).invoke();
4663 >        public void forEach(Consumer<? super K> action) {
4664 >            if (action == null) throw new NullPointerException();
4665 >            Node<K,V>[] t;
4666 >            if ((t = map.table) != null) {
4667 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4668 >                for (Node<K,V> p; (p = it.advance()) != null; )
4669 >                    action.accept(p.key);
4670 >            }
4671          }
4169
4672      }
4673  
4674      /**
4675       * A view of a ConcurrentHashMap as a {@link Collection} of
4676       * values, in which additions are disabled. This class cannot be
4677 <     * directly instantiated. See {@link #values},
4678 <     *
4679 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4680 <     * that will never throw {@link ConcurrentModificationException},
4681 <     * and guarantees to traverse elements as they existed upon
4682 <     * construction of the iterator, and may (but is not guaranteed to)
4683 <     * reflect any modifications subsequent to construction.
4684 <     */
4685 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4686 <        implements Collection<V> {
4185 <        ValuesView(ConcurrentHashMap<K, V> map)   { super(map); }
4186 <        public final boolean contains(Object o) { return map.containsValue(o); }
4677 >     * directly instantiated. See {@link #values()}.
4678 >     */
4679 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4680 >        implements Collection<V>, java.io.Serializable {
4681 >        private static final long serialVersionUID = 2249069246763182397L;
4682 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4683 >        public final boolean contains(Object o) {
4684 >            return map.containsValue(o);
4685 >        }
4686 >
4687          public final boolean remove(Object o) {
4688              if (o != null) {
4689 <                Iterator<V> it = new ValueIterator<K,V>(map);
4190 <                while (it.hasNext()) {
4689 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4690                      if (o.equals(it.next())) {
4691                          it.remove();
4692                          return true;
# Line 4197 | Line 4696 | public class ConcurrentHashMap<K, V>
4696              return false;
4697          }
4698  
4200        /**
4201         * Returns a "weakly consistent" iterator that will never
4202         * throw {@link ConcurrentModificationException}, and
4203         * guarantees to traverse elements as they existed upon
4204         * construction of the iterator, and may (but is not
4205         * guaranteed to) reflect any modifications subsequent to
4206         * construction.
4207         *
4208         * @return an iterator over the values of this map
4209         */
4699          public final Iterator<V> iterator() {
4700 <            return new ValueIterator<K,V>(map);
4700 >            ConcurrentHashMap<K,V> m = map;
4701 >            Node<K,V>[] t;
4702 >            int f = (t = m.table) == null ? 0 : t.length;
4703 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4704          }
4705 +
4706          public final boolean add(V e) {
4707              throw new UnsupportedOperationException();
4708          }
# Line 4217 | Line 4710 | public class ConcurrentHashMap<K, V>
4710              throw new UnsupportedOperationException();
4711          }
4712  
4713 <        /**
4714 <         * Performs the given action for each value.
4715 <         *
4716 <         * @param action the action
4717 <         */
4718 <        public void forEach(Action<V> action) {
4719 <            ForkJoinTasks.forEachValue
4720 <                (map, action).invoke();
4721 <        }
4722 <
4230 <        /**
4231 <         * Performs the given action for each non-null transformation
4232 <         * of each value.
4233 <         *
4234 <         * @param transformer a function returning the transformation
4235 <         * for an element, or null of there is no transformation (in
4236 <         * which case the action is not applied).
4237 <         */
4238 <        public <U> void forEach(Fun<? super V, ? extends U> transformer,
4239 <                                     Action<U> action) {
4240 <            ForkJoinTasks.forEachValue
4241 <                (map, transformer, action).invoke();
4242 <        }
4243 <
4244 <        /**
4245 <         * Returns a non-null result from applying the given search
4246 <         * function on each value, or null if none.  Upon success,
4247 <         * further element processing is suppressed and the results of
4248 <         * any other parallel invocations of the search function are
4249 <         * ignored.
4250 <         *
4251 <         * @param searchFunction a function returning a non-null
4252 <         * result on success, else null
4253 <         * @return a non-null result from applying the given search
4254 <         * function on each value, or null if none
4255 <         *
4256 <         */
4257 <        public <U> U search(Fun<? super V, ? extends U> searchFunction) {
4258 <            return ForkJoinTasks.searchValues
4259 <                (map, searchFunction).invoke();
4260 <        }
4261 <
4262 <        /**
4263 <         * Returns the result of accumulating all values using the
4264 <         * given reducer to combine values, or null if none.
4265 <         *
4266 <         * @param reducer a commutative associative combining function
4267 <         * @return  the result of accumulating all values
4268 <         */
4269 <        public V reduce(BiFun<? super V, ? super V, ? extends V> reducer) {
4270 <            return ForkJoinTasks.reduceValues
4271 <                (map, reducer).invoke();
4713 >        @Override public boolean removeAll(Collection<?> c) {
4714 >            if (c == null) throw new NullPointerException();
4715 >            boolean modified = false;
4716 >            for (Iterator<V> it = iterator(); it.hasNext();) {
4717 >                if (c.contains(it.next())) {
4718 >                    it.remove();
4719 >                    modified = true;
4720 >                }
4721 >            }
4722 >            return modified;
4723          }
4724  
4725 <        /**
4726 <         * Returns the result of accumulating the given transformation
4276 <         * of all values using the given reducer to combine values, or
4277 <         * null if none.
4278 <         *
4279 <         * @param transformer a function returning the transformation
4280 <         * for an element, or null of there is no transformation (in
4281 <         * which case it is not combined).
4282 <         * @param reducer a commutative associative combining function
4283 <         * @return the result of accumulating the given transformation
4284 <         * of all values
4285 <         */
4286 <        public <U> U reduce(Fun<? super V, ? extends U> transformer,
4287 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
4288 <            return ForkJoinTasks.reduceValues
4289 <                (map, transformer, reducer).invoke();
4725 >        public boolean removeIf(Predicate<? super V> filter) {
4726 >            return map.removeValueIf(filter);
4727          }
4728  
4729 <        /**
4730 <         * Returns the result of accumulating the given transformation
4731 <         * of all values using the given reducer to combine values,
4732 <         * and the given basis as an identity value.
4733 <         *
4734 <         * @param transformer a function returning the transformation
4298 <         * for an element
4299 <         * @param basis the identity (initial default value) for the reduction
4300 <         * @param reducer a commutative associative combining function
4301 <         * @return the result of accumulating the given transformation
4302 <         * of all values
4303 <         */
4304 <        public double reduceToDouble(ObjectToDouble<? super V> transformer,
4305 <                                     double basis,
4306 <                                     DoubleByDoubleToDouble reducer) {
4307 <            return ForkJoinTasks.reduceValuesToDouble
4308 <                (map, transformer, basis, reducer).invoke();
4729 >        public Spliterator<V> spliterator() {
4730 >            Node<K,V>[] t;
4731 >            ConcurrentHashMap<K,V> m = map;
4732 >            long n = m.sumCount();
4733 >            int f = (t = m.table) == null ? 0 : t.length;
4734 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4735          }
4736  
4737 <        /**
4738 <         * Returns the result of accumulating the given transformation
4739 <         * of all values using the given reducer to combine values,
4740 <         * and the given basis as an identity value.
4741 <         *
4742 <         * @param transformer a function returning the transformation
4743 <         * for an element
4744 <         * @param basis the identity (initial default value) for the reduction
4319 <         * @param reducer a commutative associative combining function
4320 <         * @return the result of accumulating the given transformation
4321 <         * of all values
4322 <         */
4323 <        public long reduceToLong(ObjectToLong<? super V> transformer,
4324 <                                 long basis,
4325 <                                 LongByLongToLong reducer) {
4326 <            return ForkJoinTasks.reduceValuesToLong
4327 <                (map, transformer, basis, reducer).invoke();
4328 <        }
4329 <
4330 <        /**
4331 <         * Returns the result of accumulating the given transformation
4332 <         * of all values using the given reducer to combine values,
4333 <         * and the given basis as an identity value.
4334 <         *
4335 <         * @param transformer a function returning the transformation
4336 <         * for an element
4337 <         * @param basis the identity (initial default value) for the reduction
4338 <         * @param reducer a commutative associative combining function
4339 <         * @return the result of accumulating the given transformation
4340 <         * of all values
4341 <         */
4342 <        public int reduceToInt(ObjectToInt<? super V> transformer,
4343 <                               int basis,
4344 <                               IntByIntToInt reducer) {
4345 <            return ForkJoinTasks.reduceValuesToInt
4346 <                (map, transformer, basis, reducer).invoke();
4737 >        public void forEach(Consumer<? super V> action) {
4738 >            if (action == null) throw new NullPointerException();
4739 >            Node<K,V>[] t;
4740 >            if ((t = map.table) != null) {
4741 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4742 >                for (Node<K,V> p; (p = it.advance()) != null; )
4743 >                    action.accept(p.val);
4744 >            }
4745          }
4348
4746      }
4747  
4748      /**
4749       * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4750       * entries.  This class cannot be directly instantiated. See
4751 <     * {@link #entrySet}.
4751 >     * {@link #entrySet()}.
4752       */
4753 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4754 <        implements Set<Map.Entry<K,V>> {
4755 <        EntrySetView(ConcurrentHashMap<K, V> map) { super(map); }
4756 <        public final boolean contains(Object o) {
4753 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4754 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4755 >        private static final long serialVersionUID = 2249069246763182397L;
4756 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4757 >
4758 >        public boolean contains(Object o) {
4759              Object k, v, r; Map.Entry<?,?> e;
4760              return ((o instanceof Map.Entry) &&
4761                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4364 | Line 4763 | public class ConcurrentHashMap<K, V>
4763                      (v = e.getValue()) != null &&
4764                      (v == r || v.equals(r)));
4765          }
4766 <        public final boolean remove(Object o) {
4766 >
4767 >        public boolean remove(Object o) {
4768              Object k, v; Map.Entry<?,?> e;
4769              return ((o instanceof Map.Entry) &&
4770                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4373 | Line 4773 | public class ConcurrentHashMap<K, V>
4773          }
4774  
4775          /**
4776 <         * Returns a "weakly consistent" iterator that will never
4377 <         * throw {@link ConcurrentModificationException}, and
4378 <         * guarantees to traverse elements as they existed upon
4379 <         * construction of the iterator, and may (but is not
4380 <         * guaranteed to) reflect any modifications subsequent to
4381 <         * construction.
4382 <         *
4383 <         * @return an iterator over the entries of this map
4776 >         * @return an iterator over the entries of the backing map
4777           */
4778 <        public final Iterator<Map.Entry<K,V>> iterator() {
4779 <            return new EntryIterator<K,V>(map);
4778 >        public Iterator<Map.Entry<K,V>> iterator() {
4779 >            ConcurrentHashMap<K,V> m = map;
4780 >            Node<K,V>[] t;
4781 >            int f = (t = m.table) == null ? 0 : t.length;
4782 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4783          }
4784  
4785 <        public final boolean add(Entry<K,V> e) {
4786 <            K key = e.getKey();
4391 <            V value = e.getValue();
4392 <            if (key == null || value == null)
4393 <                throw new NullPointerException();
4394 <            return map.internalPut(key, value, false) == null;
4785 >        public boolean add(Entry<K,V> e) {
4786 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4787          }
4788 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4788 >
4789 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4790              boolean added = false;
4791              for (Entry<K,V> e : c) {
4792                  if (add(e))
# Line 4401 | Line 4794 | public class ConcurrentHashMap<K, V>
4794              }
4795              return added;
4796          }
4404        public boolean equals(Object o) {
4405            Set<?> c;
4406            return ((o instanceof Set) &&
4407                    ((c = (Set<?>)o) == this ||
4408                     (containsAll(c) && c.containsAll(this))));
4409        }
4410
4411        /**
4412         * Performs the given action for each entry.
4413         *
4414         * @param action the action
4415         */
4416        public void forEach(Action<Map.Entry<K,V>> action) {
4417            ForkJoinTasks.forEachEntry
4418                (map, action).invoke();
4419        }
4420
4421        /**
4422         * Performs the given action for each non-null transformation
4423         * of each entry.
4424         *
4425         * @param transformer a function returning the transformation
4426         * for an element, or null of there is no transformation (in
4427         * which case the action is not applied).
4428         * @param action the action
4429         */
4430        public <U> void forEach(Fun<Map.Entry<K,V>, ? extends U> transformer,
4431                                Action<U> action) {
4432            ForkJoinTasks.forEachEntry
4433                (map, transformer, action).invoke();
4434        }
4435
4436        /**
4437         * Returns a non-null result from applying the given search
4438         * function on each entry, or null if none.  Upon success,
4439         * further element processing is suppressed and the results of
4440         * any other parallel invocations of the search function are
4441         * ignored.
4442         *
4443         * @param searchFunction a function returning a non-null
4444         * result on success, else null
4445         * @return a non-null result from applying the given search
4446         * function on each entry, or null if none
4447         */
4448        public <U> U search(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4449            return ForkJoinTasks.searchEntries
4450                (map, searchFunction).invoke();
4451        }
4797  
4798 <        /**
4799 <         * Returns the result of accumulating all entries using the
4455 <         * given reducer to combine values, or null if none.
4456 <         *
4457 <         * @param reducer a commutative associative combining function
4458 <         * @return the result of accumulating all entries
4459 <         */
4460 <        public Map.Entry<K,V> reduce(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4461 <            return ForkJoinTasks.reduceEntries
4462 <                (map, reducer).invoke();
4798 >        public boolean removeIf(Predicate<? super Entry<K,V>> filter) {
4799 >            return map.removeEntryIf(filter);
4800          }
4801  
4802 <        /**
4803 <         * Returns the result of accumulating the given transformation
4804 <         * of all entries using the given reducer to combine values,
4805 <         * or null if none.
4806 <         *
4807 <         * @param transformer a function returning the transformation
4808 <         * for an element, or null of there is no transformation (in
4809 <         * which case it is not combined).
4810 <         * @param reducer a commutative associative combining function
4811 <         * @return the result of accumulating the given transformation
4475 <         * of all entries
4476 <         */
4477 <        public <U> U reduce(Fun<Map.Entry<K,V>, ? extends U> transformer,
4478 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
4479 <            return ForkJoinTasks.reduceEntries
4480 <                (map, transformer, reducer).invoke();
4802 >        public final int hashCode() {
4803 >            int h = 0;
4804 >            Node<K,V>[] t;
4805 >            if ((t = map.table) != null) {
4806 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4807 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4808 >                    h += p.hashCode();
4809 >                }
4810 >            }
4811 >            return h;
4812          }
4813  
4814 <        /**
4815 <         * Returns the result of accumulating the given transformation
4816 <         * of all entries using the given reducer to combine values,
4817 <         * and the given basis as an identity value.
4818 <         *
4488 <         * @param transformer a function returning the transformation
4489 <         * for an element
4490 <         * @param basis the identity (initial default value) for the reduction
4491 <         * @param reducer a commutative associative combining function
4492 <         * @return the result of accumulating the given transformation
4493 <         * of all entries
4494 <         */
4495 <        public double reduceToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4496 <                                     double basis,
4497 <                                     DoubleByDoubleToDouble reducer) {
4498 <            return ForkJoinTasks.reduceEntriesToDouble
4499 <                (map, transformer, basis, reducer).invoke();
4814 >        public final boolean equals(Object o) {
4815 >            Set<?> c;
4816 >            return ((o instanceof Set) &&
4817 >                    ((c = (Set<?>)o) == this ||
4818 >                     (containsAll(c) && c.containsAll(this))));
4819          }
4820  
4821 <        /**
4822 <         * Returns the result of accumulating the given transformation
4823 <         * of all entries using the given reducer to combine values,
4824 <         * and the given basis as an identity value.
4825 <         *
4826 <         * @param transformer a function returning the transformation
4508 <         * for an element
4509 <         * @param basis the identity (initial default value) for the reduction
4510 <         * @param reducer a commutative associative combining function
4511 <         * @return  the result of accumulating the given transformation
4512 <         * of all entries
4513 <         */
4514 <        public long reduceToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4515 <                                 long basis,
4516 <                                 LongByLongToLong reducer) {
4517 <            return ForkJoinTasks.reduceEntriesToLong
4518 <                (map, transformer, basis, reducer).invoke();
4821 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4822 >            Node<K,V>[] t;
4823 >            ConcurrentHashMap<K,V> m = map;
4824 >            long n = m.sumCount();
4825 >            int f = (t = m.table) == null ? 0 : t.length;
4826 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4827          }
4828  
4829 <        /**
4830 <         * Returns the result of accumulating the given transformation
4831 <         * of all entries using the given reducer to combine values,
4832 <         * and the given basis as an identity value.
4833 <         *
4834 <         * @param transformer a function returning the transformation
4835 <         * for an element
4836 <         * @param basis the identity (initial default value) for the reduction
4529 <         * @param reducer a commutative associative combining function
4530 <         * @return the result of accumulating the given transformation
4531 <         * of all entries
4532 <         */
4533 <        public int reduceToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4534 <                               int basis,
4535 <                               IntByIntToInt reducer) {
4536 <            return ForkJoinTasks.reduceEntriesToInt
4537 <                (map, transformer, basis, reducer).invoke();
4829 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4830 >            if (action == null) throw new NullPointerException();
4831 >            Node<K,V>[] t;
4832 >            if ((t = map.table) != null) {
4833 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4834 >                for (Node<K,V> p; (p = it.advance()) != null; )
4835 >                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
4836 >            }
4837          }
4838  
4839      }
4840  
4841 <    // ---------------------------------------------------------------------
4841 >    // -------------------------------------------------------
4842  
4843      /**
4844 <     * Predefined tasks for performing bulk parallel operations on
4845 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
4547 <     * for bulk operations. Each method has the same name, but returns
4548 <     * a task rather than invoking it. These methods may be useful in
4549 <     * custom applications such as submitting a task without waiting
4550 <     * for completion, using a custom pool, or combining with other
4551 <     * tasks.
4844 >     * Base class for bulk tasks. Repeats some fields and code from
4845 >     * class Traverser, because we need to subclass CountedCompleter.
4846       */
4847 <    public static class ForkJoinTasks {
4848 <        private ForkJoinTasks() {}
4849 <
4850 <        /**
4851 <         * Returns a task that when invoked, performs the given
4852 <         * action for each (key, value)
4853 <         *
4854 <         * @param map the map
4855 <         * @param action the action
4856 <         * @return the task
4857 <         */
4858 <        public static <K,V> ForkJoinTask<Void> forEach
4859 <            (ConcurrentHashMap<K,V> map,
4860 <             BiAction<K,V> action) {
4861 <            if (action == null) throw new NullPointerException();
4862 <            return new ForEachMappingTask<K,V>(map, null, -1, action);
4863 <        }
4864 <
4865 <        /**
4866 <         * Returns a task that when invoked, performs the given
4867 <         * action for each non-null transformation of each (key, value)
4868 <         *
4869 <         * @param map the map
4576 <         * @param transformer a function returning the transformation
4577 <         * for an element, or null if there is no transformation (in
4578 <         * which case the action is not applied)
4579 <         * @param action the action
4580 <         * @return the task
4581 <         */
4582 <        public static <K,V,U> ForkJoinTask<Void> forEach
4583 <            (ConcurrentHashMap<K,V> map,
4584 <             BiFun<? super K, ? super V, ? extends U> transformer,
4585 <             Action<U> action) {
4586 <            if (transformer == null || action == null)
4587 <                throw new NullPointerException();
4588 <            return new ForEachTransformedMappingTask<K,V,U>
4589 <                (map, null, -1, transformer, action);
4590 <        }
4591 <
4592 <        /**
4593 <         * Returns a task that when invoked, returns a non-null result
4594 <         * from applying the given search function on each (key,
4595 <         * value), or null if none. Upon success, further element
4596 <         * processing is suppressed and the results of any other
4597 <         * parallel invocations of the search function are ignored.
4598 <         *
4599 <         * @param map the map
4600 <         * @param searchFunction a function returning a non-null
4601 <         * result on success, else null
4602 <         * @return the task
4603 <         */
4604 <        public static <K,V,U> ForkJoinTask<U> search
4605 <            (ConcurrentHashMap<K,V> map,
4606 <             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4607 <            if (searchFunction == null) throw new NullPointerException();
4608 <            return new SearchMappingsTask<K,V,U>
4609 <                (map, null, -1, searchFunction,
4610 <                 new AtomicReference<U>());
4611 <        }
4612 <
4613 <        /**
4614 <         * Returns a task that when invoked, returns the result of
4615 <         * accumulating the given transformation of all (key, value) pairs
4616 <         * using the given reducer to combine values, or null if none.
4617 <         *
4618 <         * @param map the map
4619 <         * @param transformer a function returning the transformation
4620 <         * for an element, or null if there is no transformation (in
4621 <         * which case it is not combined).
4622 <         * @param reducer a commutative associative combining function
4623 <         * @return the task
4624 <         */
4625 <        public static <K,V,U> ForkJoinTask<U> reduce
4626 <            (ConcurrentHashMap<K,V> map,
4627 <             BiFun<? super K, ? super V, ? extends U> transformer,
4628 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4629 <            if (transformer == null || reducer == null)
4630 <                throw new NullPointerException();
4631 <            return new MapReduceMappingsTask<K,V,U>
4632 <                (map, null, -1, null, transformer, reducer);
4633 <        }
4634 <
4635 <        /**
4636 <         * Returns a task that when invoked, returns the result of
4637 <         * accumulating the given transformation of all (key, value) pairs
4638 <         * using the given reducer to combine values, and the given
4639 <         * basis as an identity value.
4640 <         *
4641 <         * @param map the map
4642 <         * @param transformer a function returning the transformation
4643 <         * for an element
4644 <         * @param basis the identity (initial default value) for the reduction
4645 <         * @param reducer a commutative associative combining function
4646 <         * @return the task
4647 <         */
4648 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4649 <            (ConcurrentHashMap<K,V> map,
4650 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
4651 <             double basis,
4652 <             DoubleByDoubleToDouble reducer) {
4653 <            if (transformer == null || reducer == null)
4654 <                throw new NullPointerException();
4655 <            return new MapReduceMappingsToDoubleTask<K,V>
4656 <                (map, null, -1, null, transformer, basis, reducer);
4657 <        }
4658 <
4659 <        /**
4660 <         * Returns a task that when invoked, returns the result of
4661 <         * accumulating the given transformation of all (key, value) pairs
4662 <         * using the given reducer to combine values, and the given
4663 <         * basis as an identity value.
4664 <         *
4665 <         * @param map the map
4666 <         * @param transformer a function returning the transformation
4667 <         * for an element
4668 <         * @param basis the identity (initial default value) for the reduction
4669 <         * @param reducer a commutative associative combining function
4670 <         * @return the task
4671 <         */
4672 <        public static <K,V> ForkJoinTask<Long> reduceToLong
4673 <            (ConcurrentHashMap<K,V> map,
4674 <             ObjectByObjectToLong<? super K, ? super V> transformer,
4675 <             long basis,
4676 <             LongByLongToLong reducer) {
4677 <            if (transformer == null || reducer == null)
4678 <                throw new NullPointerException();
4679 <            return new MapReduceMappingsToLongTask<K,V>
4680 <                (map, null, -1, null, transformer, basis, reducer);
4681 <        }
4682 <
4683 <        /**
4684 <         * Returns a task that when invoked, returns the result of
4685 <         * accumulating the given transformation of all (key, value) pairs
4686 <         * using the given reducer to combine values, and the given
4687 <         * basis as an identity value.
4688 <         *
4689 <         * @param transformer a function returning the transformation
4690 <         * for an element
4691 <         * @param basis the identity (initial default value) for the reduction
4692 <         * @param reducer a commutative associative combining function
4693 <         * @return the task
4694 <         */
4695 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
4696 <            (ConcurrentHashMap<K,V> map,
4697 <             ObjectByObjectToInt<? super K, ? super V> transformer,
4698 <             int basis,
4699 <             IntByIntToInt reducer) {
4700 <            if (transformer == null || reducer == null)
4701 <                throw new NullPointerException();
4702 <            return new MapReduceMappingsToIntTask<K,V>
4703 <                (map, null, -1, null, transformer, basis, reducer);
4704 <        }
4705 <
4706 <        /**
4707 <         * Returns a task that when invoked, performs the given action
4708 <         * for each key.
4709 <         *
4710 <         * @param map the map
4711 <         * @param action the action
4712 <         * @return the task
4713 <         */
4714 <        public static <K,V> ForkJoinTask<Void> forEachKey
4715 <            (ConcurrentHashMap<K,V> map,
4716 <             Action<K> action) {
4717 <            if (action == null) throw new NullPointerException();
4718 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
4719 <        }
4720 <
4721 <        /**
4722 <         * Returns a task that when invoked, performs the given action
4723 <         * for each non-null transformation of each key.
4724 <         *
4725 <         * @param map the map
4726 <         * @param transformer a function returning the transformation
4727 <         * for an element, or null if there is no transformation (in
4728 <         * which case the action is not applied)
4729 <         * @param action the action
4730 <         * @return the task
4731 <         */
4732 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
4733 <            (ConcurrentHashMap<K,V> map,
4734 <             Fun<? super K, ? extends U> transformer,
4735 <             Action<U> action) {
4736 <            if (transformer == null || action == null)
4737 <                throw new NullPointerException();
4738 <            return new ForEachTransformedKeyTask<K,V,U>
4739 <                (map, null, -1, transformer, action);
4740 <        }
4741 <
4742 <        /**
4743 <         * Returns a task that when invoked, returns a non-null result
4744 <         * from applying the given search function on each key, or
4745 <         * null if none.  Upon success, further element processing is
4746 <         * suppressed and the results of any other parallel
4747 <         * invocations of the search function are ignored.
4748 <         *
4749 <         * @param map the map
4750 <         * @param searchFunction a function returning a non-null
4751 <         * result on success, else null
4752 <         * @return the task
4753 <         */
4754 <        public static <K,V,U> ForkJoinTask<U> searchKeys
4755 <            (ConcurrentHashMap<K,V> map,
4756 <             Fun<? super K, ? extends U> searchFunction) {
4757 <            if (searchFunction == null) throw new NullPointerException();
4758 <            return new SearchKeysTask<K,V,U>
4759 <                (map, null, -1, searchFunction,
4760 <                 new AtomicReference<U>());
4761 <        }
4762 <
4763 <        /**
4764 <         * Returns a task that when invoked, returns the result of
4765 <         * accumulating all keys using the given reducer to combine
4766 <         * values, or null if none.
4767 <         *
4768 <         * @param map the map
4769 <         * @param reducer a commutative associative combining function
4770 <         * @return the task
4771 <         */
4772 <        public static <K,V> ForkJoinTask<K> reduceKeys
4773 <            (ConcurrentHashMap<K,V> map,
4774 <             BiFun<? super K, ? super K, ? extends K> reducer) {
4775 <            if (reducer == null) throw new NullPointerException();
4776 <            return new ReduceKeysTask<K,V>
4777 <                (map, null, -1, null, reducer);
4778 <        }
4779 <
4780 <        /**
4781 <         * Returns a task that when invoked, returns the result of
4782 <         * accumulating the given transformation of all keys using the given
4783 <         * reducer to combine values, or null if none.
4784 <         *
4785 <         * @param map the map
4786 <         * @param transformer a function returning the transformation
4787 <         * for an element, or null if there is no transformation (in
4788 <         * which case it is not combined).
4789 <         * @param reducer a commutative associative combining function
4790 <         * @return the task
4791 <         */
4792 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
4793 <            (ConcurrentHashMap<K,V> map,
4794 <             Fun<? super K, ? extends U> transformer,
4795 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4796 <            if (transformer == null || reducer == null)
4797 <                throw new NullPointerException();
4798 <            return new MapReduceKeysTask<K,V,U>
4799 <                (map, null, -1, null, transformer, reducer);
4800 <        }
4801 <
4802 <        /**
4803 <         * Returns a task that when invoked, returns the result of
4804 <         * accumulating the given transformation of all keys using the given
4805 <         * reducer to combine values, and the given basis as an
4806 <         * identity value.
4807 <         *
4808 <         * @param map the map
4809 <         * @param transformer a function returning the transformation
4810 <         * for an element
4811 <         * @param basis the identity (initial default value) for the reduction
4812 <         * @param reducer a commutative associative combining function
4813 <         * @return the task
4814 <         */
4815 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
4816 <            (ConcurrentHashMap<K,V> map,
4817 <             ObjectToDouble<? super K> transformer,
4818 <             double basis,
4819 <             DoubleByDoubleToDouble reducer) {
4820 <            if (transformer == null || reducer == null)
4821 <                throw new NullPointerException();
4822 <            return new MapReduceKeysToDoubleTask<K,V>
4823 <                (map, null, -1, null, transformer, basis, reducer);
4824 <        }
4825 <
4826 <        /**
4827 <         * Returns a task that when invoked, returns the result of
4828 <         * accumulating the given transformation of all keys using the given
4829 <         * reducer to combine values, and the given basis as an
4830 <         * identity value.
4831 <         *
4832 <         * @param map the map
4833 <         * @param transformer a function returning the transformation
4834 <         * for an element
4835 <         * @param basis the identity (initial default value) for the reduction
4836 <         * @param reducer a commutative associative combining function
4837 <         * @return the task
4838 <         */
4839 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
4840 <            (ConcurrentHashMap<K,V> map,
4841 <             ObjectToLong<? super K> transformer,
4842 <             long basis,
4843 <             LongByLongToLong reducer) {
4844 <            if (transformer == null || reducer == null)
4845 <                throw new NullPointerException();
4846 <            return new MapReduceKeysToLongTask<K,V>
4847 <                (map, null, -1, null, transformer, basis, reducer);
4848 <        }
4849 <
4850 <        /**
4851 <         * Returns a task that when invoked, returns the result of
4852 <         * accumulating the given transformation of all keys using the given
4853 <         * reducer to combine values, and the given basis as an
4854 <         * identity value.
4855 <         *
4856 <         * @param map the map
4857 <         * @param transformer a function returning the transformation
4858 <         * for an element
4859 <         * @param basis the identity (initial default value) for the reduction
4860 <         * @param reducer a commutative associative combining function
4861 <         * @return the task
4862 <         */
4863 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
4864 <            (ConcurrentHashMap<K,V> map,
4865 <             ObjectToInt<? super K> transformer,
4866 <             int basis,
4867 <             IntByIntToInt reducer) {
4868 <            if (transformer == null || reducer == null)
4869 <                throw new NullPointerException();
4870 <            return new MapReduceKeysToIntTask<K,V>
4871 <                (map, null, -1, null, transformer, basis, reducer);
4872 <        }
4873 <
4874 <        /**
4875 <         * Returns a task that when invoked, performs the given action
4876 <         * for each value.
4877 <         *
4878 <         * @param map the map
4879 <         * @param action the action
4880 <         */
4881 <        public static <K,V> ForkJoinTask<Void> forEachValue
4882 <            (ConcurrentHashMap<K,V> map,
4883 <             Action<V> action) {
4884 <            if (action == null) throw new NullPointerException();
4885 <            return new ForEachValueTask<K,V>(map, null, -1, action);
4886 <        }
4887 <
4888 <        /**
4889 <         * Returns a task that when invoked, performs the given action
4890 <         * for each non-null transformation of each value.
4891 <         *
4892 <         * @param map the map
4893 <         * @param transformer a function returning the transformation
4894 <         * for an element, or null if there is no transformation (in
4895 <         * which case the action is not applied)
4896 <         * @param action the action
4897 <         */
4898 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
4899 <            (ConcurrentHashMap<K,V> map,
4900 <             Fun<? super V, ? extends U> transformer,
4901 <             Action<U> action) {
4902 <            if (transformer == null || action == null)
4903 <                throw new NullPointerException();
4904 <            return new ForEachTransformedValueTask<K,V,U>
4905 <                (map, null, -1, transformer, action);
4906 <        }
4907 <
4908 <        /**
4909 <         * Returns a task that when invoked, returns a non-null result
4910 <         * from applying the given search function on each value, or
4911 <         * null if none.  Upon success, further element processing is
4912 <         * suppressed and the results of any other parallel
4913 <         * invocations of the search function are ignored.
4914 <         *
4915 <         * @param map the map
4916 <         * @param searchFunction a function returning a non-null
4917 <         * result on success, else null
4918 <         * @return the task
4919 <         */
4920 <        public static <K,V,U> ForkJoinTask<U> searchValues
4921 <            (ConcurrentHashMap<K,V> map,
4922 <             Fun<? super V, ? extends U> searchFunction) {
4923 <            if (searchFunction == null) throw new NullPointerException();
4924 <            return new SearchValuesTask<K,V,U>
4925 <                (map, null, -1, searchFunction,
4926 <                 new AtomicReference<U>());
4927 <        }
4928 <
4929 <        /**
4930 <         * Returns a task that when invoked, returns the result of
4931 <         * accumulating all values using the given reducer to combine
4932 <         * values, or null if none.
4933 <         *
4934 <         * @param map the map
4935 <         * @param reducer a commutative associative combining function
4936 <         * @return the task
4937 <         */
4938 <        public static <K,V> ForkJoinTask<V> reduceValues
4939 <            (ConcurrentHashMap<K,V> map,
4940 <             BiFun<? super V, ? super V, ? extends V> reducer) {
4941 <            if (reducer == null) throw new NullPointerException();
4942 <            return new ReduceValuesTask<K,V>
4943 <                (map, null, -1, null, reducer);
4944 <        }
4945 <
4946 <        /**
4947 <         * Returns a task that when invoked, returns the result of
4948 <         * accumulating the given transformation of all values using the
4949 <         * given reducer to combine values, or null if none.
4950 <         *
4951 <         * @param map the map
4952 <         * @param transformer a function returning the transformation
4953 <         * for an element, or null if there is no transformation (in
4954 <         * which case it is not combined).
4955 <         * @param reducer a commutative associative combining function
4956 <         * @return the task
4957 <         */
4958 <        public static <K,V,U> ForkJoinTask<U> reduceValues
4959 <            (ConcurrentHashMap<K,V> map,
4960 <             Fun<? super V, ? extends U> transformer,
4961 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4962 <            if (transformer == null || reducer == null)
4963 <                throw new NullPointerException();
4964 <            return new MapReduceValuesTask<K,V,U>
4965 <                (map, null, -1, null, transformer, reducer);
4966 <        }
4967 <
4968 <        /**
4969 <         * Returns a task that when invoked, returns the result of
4970 <         * accumulating the given transformation of all values using the
4971 <         * given reducer to combine values, and the given basis as an
4972 <         * identity value.
4973 <         *
4974 <         * @param map the map
4975 <         * @param transformer a function returning the transformation
4976 <         * for an element
4977 <         * @param basis the identity (initial default value) for the reduction
4978 <         * @param reducer a commutative associative combining function
4979 <         * @return the task
4980 <         */
4981 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
4982 <            (ConcurrentHashMap<K,V> map,
4983 <             ObjectToDouble<? super V> transformer,
4984 <             double basis,
4985 <             DoubleByDoubleToDouble reducer) {
4986 <            if (transformer == null || reducer == null)
4987 <                throw new NullPointerException();
4988 <            return new MapReduceValuesToDoubleTask<K,V>
4989 <                (map, null, -1, null, transformer, basis, reducer);
4990 <        }
4991 <
4992 <        /**
4993 <         * Returns a task that when invoked, returns the result of
4994 <         * accumulating the given transformation of all values using the
4995 <         * given reducer to combine values, and the given basis as an
4996 <         * identity value.
4997 <         *
4998 <         * @param map the map
4999 <         * @param transformer a function returning the transformation
5000 <         * for an element
5001 <         * @param basis the identity (initial default value) for the reduction
5002 <         * @param reducer a commutative associative combining function
5003 <         * @return the task
5004 <         */
5005 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5006 <            (ConcurrentHashMap<K,V> map,
5007 <             ObjectToLong<? super V> transformer,
5008 <             long basis,
5009 <             LongByLongToLong reducer) {
5010 <            if (transformer == null || reducer == null)
5011 <                throw new NullPointerException();
5012 <            return new MapReduceValuesToLongTask<K,V>
5013 <                (map, null, -1, null, transformer, basis, reducer);
5014 <        }
5015 <
5016 <        /**
5017 <         * Returns a task that when invoked, returns the result of
5018 <         * accumulating the given transformation of all values using the
5019 <         * given reducer to combine values, and the given basis as an
5020 <         * identity value.
5021 <         *
5022 <         * @param map the map
5023 <         * @param transformer a function returning the transformation
5024 <         * for an element
5025 <         * @param basis the identity (initial default value) for the reduction
5026 <         * @param reducer a commutative associative combining function
5027 <         * @return the task
5028 <         */
5029 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5030 <            (ConcurrentHashMap<K,V> map,
5031 <             ObjectToInt<? super V> transformer,
5032 <             int basis,
5033 <             IntByIntToInt reducer) {
5034 <            if (transformer == null || reducer == null)
5035 <                throw new NullPointerException();
5036 <            return new MapReduceValuesToIntTask<K,V>
5037 <                (map, null, -1, null, transformer, basis, reducer);
5038 <        }
5039 <
5040 <        /**
5041 <         * Returns a task that when invoked, perform the given action
5042 <         * for each entry.
5043 <         *
5044 <         * @param map the map
5045 <         * @param action the action
5046 <         */
5047 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5048 <            (ConcurrentHashMap<K,V> map,
5049 <             Action<Map.Entry<K,V>> action) {
5050 <            if (action == null) throw new NullPointerException();
5051 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
5052 <        }
5053 <
5054 <        /**
5055 <         * Returns a task that when invoked, perform the given action
5056 <         * for each non-null transformation of each entry.
5057 <         *
5058 <         * @param map the map
5059 <         * @param transformer a function returning the transformation
5060 <         * for an element, or null if there is no transformation (in
5061 <         * which case the action is not applied)
5062 <         * @param action the action
5063 <         */
5064 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5065 <            (ConcurrentHashMap<K,V> map,
5066 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5067 <             Action<U> action) {
5068 <            if (transformer == null || action == null)
5069 <                throw new NullPointerException();
5070 <            return new ForEachTransformedEntryTask<K,V,U>
5071 <                (map, null, -1, transformer, action);
5072 <        }
5073 <
5074 <        /**
5075 <         * Returns a task that when invoked, returns a non-null result
5076 <         * from applying the given search function on each entry, or
5077 <         * null if none.  Upon success, further element processing is
5078 <         * suppressed and the results of any other parallel
5079 <         * invocations of the search function are ignored.
5080 <         *
5081 <         * @param map the map
5082 <         * @param searchFunction a function returning a non-null
5083 <         * result on success, else null
5084 <         * @return the task
5085 <         */
5086 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5087 <            (ConcurrentHashMap<K,V> map,
5088 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5089 <            if (searchFunction == null) throw new NullPointerException();
5090 <            return new SearchEntriesTask<K,V,U>
5091 <                (map, null, -1, searchFunction,
5092 <                 new AtomicReference<U>());
5093 <        }
5094 <
5095 <        /**
5096 <         * Returns a task that when invoked, returns the result of
5097 <         * accumulating all entries using the given reducer to combine
5098 <         * values, or null if none.
5099 <         *
5100 <         * @param map the map
5101 <         * @param reducer a commutative associative combining function
5102 <         * @return the task
5103 <         */
5104 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5105 <            (ConcurrentHashMap<K,V> map,
5106 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5107 <            if (reducer == null) throw new NullPointerException();
5108 <            return new ReduceEntriesTask<K,V>
5109 <                (map, null, -1, null, reducer);
5110 <        }
5111 <
5112 <        /**
5113 <         * Returns a task that when invoked, returns the result of
5114 <         * accumulating the given transformation of all entries using the
5115 <         * given reducer to combine values, or null if none.
5116 <         *
5117 <         * @param map the map
5118 <         * @param transformer a function returning the transformation
5119 <         * for an element, or null if there is no transformation (in
5120 <         * which case it is not combined).
5121 <         * @param reducer a commutative associative combining function
5122 <         * @return the task
5123 <         */
5124 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5125 <            (ConcurrentHashMap<K,V> map,
5126 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5127 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5128 <            if (transformer == null || reducer == null)
5129 <                throw new NullPointerException();
5130 <            return new MapReduceEntriesTask<K,V,U>
5131 <                (map, null, -1, null, transformer, reducer);
5132 <        }
5133 <
5134 <        /**
5135 <         * Returns a task that when invoked, returns the result of
5136 <         * accumulating the given transformation of all entries using the
5137 <         * given reducer to combine values, and the given basis as an
5138 <         * identity value.
5139 <         *
5140 <         * @param map the map
5141 <         * @param transformer a function returning the transformation
5142 <         * for an element
5143 <         * @param basis the identity (initial default value) for the reduction
5144 <         * @param reducer a commutative associative combining function
5145 <         * @return the task
5146 <         */
5147 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5148 <            (ConcurrentHashMap<K,V> map,
5149 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5150 <             double basis,
5151 <             DoubleByDoubleToDouble reducer) {
5152 <            if (transformer == null || reducer == null)
5153 <                throw new NullPointerException();
5154 <            return new MapReduceEntriesToDoubleTask<K,V>
5155 <                (map, null, -1, null, transformer, basis, reducer);
4847 >    @SuppressWarnings("serial")
4848 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4849 >        Node<K,V>[] tab;        // same as Traverser
4850 >        Node<K,V> next;
4851 >        TableStack<K,V> stack, spare;
4852 >        int index;
4853 >        int baseIndex;
4854 >        int baseLimit;
4855 >        final int baseSize;
4856 >        int batch;              // split control
4857 >
4858 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4859 >            super(par);
4860 >            this.batch = b;
4861 >            this.index = this.baseIndex = i;
4862 >            if ((this.tab = t) == null)
4863 >                this.baseSize = this.baseLimit = 0;
4864 >            else if (par == null)
4865 >                this.baseSize = this.baseLimit = t.length;
4866 >            else {
4867 >                this.baseLimit = f;
4868 >                this.baseSize = par.baseSize;
4869 >            }
4870          }
4871  
4872          /**
4873 <         * Returns a task that when invoked, returns the result of
5160 <         * accumulating the given transformation of all entries using the
5161 <         * given reducer to combine values, and the given basis as an
5162 <         * identity value.
5163 <         *
5164 <         * @param map the map
5165 <         * @param transformer a function returning the transformation
5166 <         * for an element
5167 <         * @param basis the identity (initial default value) for the reduction
5168 <         * @param reducer a commutative associative combining function
5169 <         * @return the task
4873 >         * Same as Traverser version.
4874           */
4875 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4876 <            (ConcurrentHashMap<K,V> map,
4877 <             ObjectToLong<Map.Entry<K,V>> transformer,
4878 <             long basis,
4879 <             LongByLongToLong reducer) {
4880 <            if (transformer == null || reducer == null)
4881 <                throw new NullPointerException();
4882 <            return new MapReduceEntriesToLongTask<K,V>
4883 <                (map, null, -1, null, transformer, basis, reducer);
4875 >        final Node<K,V> advance() {
4876 >            Node<K,V> e;
4877 >            if ((e = next) != null)
4878 >                e = e.next;
4879 >            for (;;) {
4880 >                Node<K,V>[] t; int i, n;
4881 >                if (e != null)
4882 >                    return next = e;
4883 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4884 >                    (n = t.length) <= (i = index) || i < 0)
4885 >                    return next = null;
4886 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
4887 >                    if (e instanceof ForwardingNode) {
4888 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4889 >                        e = null;
4890 >                        pushState(t, i, n);
4891 >                        continue;
4892 >                    }
4893 >                    else if (e instanceof TreeBin)
4894 >                        e = ((TreeBin<K,V>)e).first;
4895 >                    else
4896 >                        e = null;
4897 >                }
4898 >                if (stack != null)
4899 >                    recoverState(n);
4900 >                else if ((index = i + baseSize) >= n)
4901 >                    index = ++baseIndex;
4902 >            }
4903          }
4904  
4905 <        /**
4906 <         * Returns a task that when invoked, returns the result of
4907 <         * accumulating the given transformation of all entries using the
4908 <         * given reducer to combine values, and the given basis as an
4909 <         * identity value.
4910 <         *
4911 <         * @param map the map
4912 <         * @param transformer a function returning the transformation
4913 <         * for an element
4914 <         * @param basis the identity (initial default value) for the reduction
4915 <         * @param reducer a commutative associative combining function
4916 <         * @return the task
4917 <         */
4918 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4919 <            (ConcurrentHashMap<K,V> map,
4920 <             ObjectToInt<Map.Entry<K,V>> transformer,
4921 <             int basis,
4922 <             IntByIntToInt reducer) {
4923 <            if (transformer == null || reducer == null)
4924 <                throw new NullPointerException();
4925 <            return new MapReduceEntriesToIntTask<K,V>
4926 <                (map, null, -1, null, transformer, basis, reducer);
4905 >        private void pushState(Node<K,V>[] t, int i, int n) {
4906 >            TableStack<K,V> s = spare;
4907 >            if (s != null)
4908 >                spare = s.next;
4909 >            else
4910 >                s = new TableStack<K,V>();
4911 >            s.tab = t;
4912 >            s.length = n;
4913 >            s.index = i;
4914 >            s.next = stack;
4915 >            stack = s;
4916 >        }
4917 >
4918 >        private void recoverState(int n) {
4919 >            TableStack<K,V> s; int len;
4920 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
4921 >                n = len;
4922 >                index = s.index;
4923 >                tab = s.tab;
4924 >                s.tab = null;
4925 >                TableStack<K,V> next = s.next;
4926 >                s.next = spare; // save for reuse
4927 >                stack = next;
4928 >                spare = s;
4929 >            }
4930 >            if (s == null && (index += baseSize) >= n)
4931 >                index = ++baseIndex;
4932          }
4933      }
4934  
5207    // -------------------------------------------------------
5208
4935      /*
4936       * Task classes. Coded in a regular but ugly format/style to
4937       * simplify checks that each variant differs in the right way from
# Line 5213 | Line 4939 | public class ConcurrentHashMap<K, V>
4939       * that we've already null-checked task arguments, so we force
4940       * simplest hoisted bypass to help avoid convoluted traps.
4941       */
4942 <
4943 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4944 <        extends Traverser<K,V,Void> {
4945 <        final Action<K> action;
4942 >    @SuppressWarnings("serial")
4943 >    static final class ForEachKeyTask<K,V>
4944 >        extends BulkTask<K,V,Void> {
4945 >        final Consumer<? super K> action;
4946          ForEachKeyTask
4947 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4948 <             Action<K> action) {
4949 <            super(m, p, b);
4947 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4948 >             Consumer<? super K> action) {
4949 >            super(p, b, i, f, t);
4950              this.action = action;
4951          }
4952 <        @SuppressWarnings("unchecked") public final void compute() {
4953 <            final Action<K> action;
4952 >        public final void compute() {
4953 >            final Consumer<? super K> action;
4954              if ((action = this.action) != null) {
4955 <                for (int b; (b = preSplit()) > 0;)
4956 <                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
4957 <                while (advance() != null)
4958 <                    action.apply((K)nextKey);
4955 >                for (int i = baseIndex, f, h; batch > 0 &&
4956 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4957 >                    addToPendingCount(1);
4958 >                    new ForEachKeyTask<K,V>
4959 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4960 >                         action).fork();
4961 >                }
4962 >                for (Node<K,V> p; (p = advance()) != null;)
4963 >                    action.accept(p.key);
4964                  propagateCompletion();
4965              }
4966          }
4967      }
4968  
4969 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4970 <        extends Traverser<K,V,Void> {
4971 <        final Action<V> action;
4969 >    @SuppressWarnings("serial")
4970 >    static final class ForEachValueTask<K,V>
4971 >        extends BulkTask<K,V,Void> {
4972 >        final Consumer<? super V> action;
4973          ForEachValueTask
4974 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4975 <             Action<V> action) {
4976 <            super(m, p, b);
4974 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4975 >             Consumer<? super V> action) {
4976 >            super(p, b, i, f, t);
4977              this.action = action;
4978          }
4979 <        @SuppressWarnings("unchecked") public final void compute() {
4980 <            final Action<V> action;
4979 >        public final void compute() {
4980 >            final Consumer<? super V> action;
4981              if ((action = this.action) != null) {
4982 <                for (int b; (b = preSplit()) > 0;)
4983 <                    new ForEachValueTask<K,V>(map, this, b, action).fork();
4984 <                Object v;
4985 <                while ((v = advance()) != null)
4986 <                    action.apply((V)v);
4982 >                for (int i = baseIndex, f, h; batch > 0 &&
4983 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4984 >                    addToPendingCount(1);
4985 >                    new ForEachValueTask<K,V>
4986 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4987 >                         action).fork();
4988 >                }
4989 >                for (Node<K,V> p; (p = advance()) != null;)
4990 >                    action.accept(p.val);
4991                  propagateCompletion();
4992              }
4993          }
4994      }
4995  
4996 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4997 <        extends Traverser<K,V,Void> {
4998 <        final Action<Entry<K,V>> action;
4996 >    @SuppressWarnings("serial")
4997 >    static final class ForEachEntryTask<K,V>
4998 >        extends BulkTask<K,V,Void> {
4999 >        final Consumer<? super Entry<K,V>> action;
5000          ForEachEntryTask
5001 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5002 <             Action<Entry<K,V>> action) {
5003 <            super(m, p, b);
5001 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5002 >             Consumer<? super Entry<K,V>> action) {
5003 >            super(p, b, i, f, t);
5004              this.action = action;
5005          }
5006 <        @SuppressWarnings("unchecked") public final void compute() {
5007 <            final Action<Entry<K,V>> action;
5006 >        public final void compute() {
5007 >            final Consumer<? super Entry<K,V>> action;
5008              if ((action = this.action) != null) {
5009 <                for (int b; (b = preSplit()) > 0;)
5010 <                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
5011 <                Object v;
5012 <                while ((v = advance()) != null)
5013 <                    action.apply(entryFor((K)nextKey, (V)v));
5009 >                for (int i = baseIndex, f, h; batch > 0 &&
5010 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5011 >                    addToPendingCount(1);
5012 >                    new ForEachEntryTask<K,V>
5013 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5014 >                         action).fork();
5015 >                }
5016 >                for (Node<K,V> p; (p = advance()) != null; )
5017 >                    action.accept(p);
5018                  propagateCompletion();
5019              }
5020          }
5021      }
5022  
5023 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5024 <        extends Traverser<K,V,Void> {
5025 <        final BiAction<K,V> action;
5023 >    @SuppressWarnings("serial")
5024 >    static final class ForEachMappingTask<K,V>
5025 >        extends BulkTask<K,V,Void> {
5026 >        final BiConsumer<? super K, ? super V> action;
5027          ForEachMappingTask
5028 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5029 <             BiAction<K,V> action) {
5030 <            super(m, p, b);
5028 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5029 >             BiConsumer<? super K,? super V> action) {
5030 >            super(p, b, i, f, t);
5031              this.action = action;
5032          }
5033 <        @SuppressWarnings("unchecked") public final void compute() {
5034 <            final BiAction<K,V> action;
5033 >        public final void compute() {
5034 >            final BiConsumer<? super K, ? super V> action;
5035              if ((action = this.action) != null) {
5036 <                for (int b; (b = preSplit()) > 0;)
5037 <                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
5038 <                Object v;
5039 <                while ((v = advance()) != null)
5040 <                    action.apply((K)nextKey, (V)v);
5036 >                for (int i = baseIndex, f, h; batch > 0 &&
5037 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5038 >                    addToPendingCount(1);
5039 >                    new ForEachMappingTask<K,V>
5040 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5041 >                         action).fork();
5042 >                }
5043 >                for (Node<K,V> p; (p = advance()) != null; )
5044 >                    action.accept(p.key, p.val);
5045                  propagateCompletion();
5046              }
5047          }
5048      }
5049  
5050 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5051 <        extends Traverser<K,V,Void> {
5052 <        final Fun<? super K, ? extends U> transformer;
5053 <        final Action<U> action;
5050 >    @SuppressWarnings("serial")
5051 >    static final class ForEachTransformedKeyTask<K,V,U>
5052 >        extends BulkTask<K,V,Void> {
5053 >        final Function<? super K, ? extends U> transformer;
5054 >        final Consumer<? super U> action;
5055          ForEachTransformedKeyTask
5056 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5057 <             Fun<? super K, ? extends U> transformer, Action<U> action) {
5058 <            super(m, p, b);
5056 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5057 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5058 >            super(p, b, i, f, t);
5059              this.transformer = transformer; this.action = action;
5060          }
5061 <        @SuppressWarnings("unchecked") public final void compute() {
5062 <            final Fun<? super K, ? extends U> transformer;
5063 <            final Action<U> action;
5061 >        public final void compute() {
5062 >            final Function<? super K, ? extends U> transformer;
5063 >            final Consumer<? super U> action;
5064              if ((transformer = this.transformer) != null &&
5065                  (action = this.action) != null) {
5066 <                for (int b; (b = preSplit()) > 0;)
5066 >                for (int i = baseIndex, f, h; batch > 0 &&
5067 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5068 >                    addToPendingCount(1);
5069                      new ForEachTransformedKeyTask<K,V,U>
5070 <                        (map, this, b, transformer, action).fork();
5071 <                U u;
5072 <                while (advance() != null) {
5073 <                    if ((u = transformer.apply((K)nextKey)) != null)
5074 <                        action.apply(u);
5070 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5071 >                         transformer, action).fork();
5072 >                }
5073 >                for (Node<K,V> p; (p = advance()) != null; ) {
5074 >                    U u;
5075 >                    if ((u = transformer.apply(p.key)) != null)
5076 >                        action.accept(u);
5077                  }
5078                  propagateCompletion();
5079              }
5080          }
5081      }
5082  
5083 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5084 <        extends Traverser<K,V,Void> {
5085 <        final Fun<? super V, ? extends U> transformer;
5086 <        final Action<U> action;
5083 >    @SuppressWarnings("serial")
5084 >    static final class ForEachTransformedValueTask<K,V,U>
5085 >        extends BulkTask<K,V,Void> {
5086 >        final Function<? super V, ? extends U> transformer;
5087 >        final Consumer<? super U> action;
5088          ForEachTransformedValueTask
5089 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5090 <             Fun<? super V, ? extends U> transformer, Action<U> action) {
5091 <            super(m, p, b);
5089 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5090 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5091 >            super(p, b, i, f, t);
5092              this.transformer = transformer; this.action = action;
5093          }
5094 <        @SuppressWarnings("unchecked") public final void compute() {
5095 <            final Fun<? super V, ? extends U> transformer;
5096 <            final Action<U> action;
5094 >        public final void compute() {
5095 >            final Function<? super V, ? extends U> transformer;
5096 >            final Consumer<? super U> action;
5097              if ((transformer = this.transformer) != null &&
5098                  (action = this.action) != null) {
5099 <                for (int b; (b = preSplit()) > 0;)
5099 >                for (int i = baseIndex, f, h; batch > 0 &&
5100 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5101 >                    addToPendingCount(1);
5102                      new ForEachTransformedValueTask<K,V,U>
5103 <                        (map, this, b, transformer, action).fork();
5104 <                Object v; U u;
5105 <                while ((v = advance()) != null) {
5106 <                    if ((u = transformer.apply((V)v)) != null)
5107 <                        action.apply(u);
5103 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5104 >                         transformer, action).fork();
5105 >                }
5106 >                for (Node<K,V> p; (p = advance()) != null; ) {
5107 >                    U u;
5108 >                    if ((u = transformer.apply(p.val)) != null)
5109 >                        action.accept(u);
5110                  }
5111                  propagateCompletion();
5112              }
5113          }
5114      }
5115  
5116 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5117 <        extends Traverser<K,V,Void> {
5118 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5119 <        final Action<U> action;
5116 >    @SuppressWarnings("serial")
5117 >    static final class ForEachTransformedEntryTask<K,V,U>
5118 >        extends BulkTask<K,V,Void> {
5119 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5120 >        final Consumer<? super U> action;
5121          ForEachTransformedEntryTask
5122 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5123 <             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<U> action) {
5124 <            super(m, p, b);
5122 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5123 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5124 >            super(p, b, i, f, t);
5125              this.transformer = transformer; this.action = action;
5126          }
5127 <        @SuppressWarnings("unchecked") public final void compute() {
5128 <            final Fun<Map.Entry<K,V>, ? extends U> transformer;
5129 <            final Action<U> action;
5127 >        public final void compute() {
5128 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5129 >            final Consumer<? super U> action;
5130              if ((transformer = this.transformer) != null &&
5131                  (action = this.action) != null) {
5132 <                for (int b; (b = preSplit()) > 0;)
5132 >                for (int i = baseIndex, f, h; batch > 0 &&
5133 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5134 >                    addToPendingCount(1);
5135                      new ForEachTransformedEntryTask<K,V,U>
5136 <                        (map, this, b, transformer, action).fork();
5137 <                Object v; U u;
5138 <                while ((v = advance()) != null) {
5139 <                    if ((u = transformer.apply(entryFor((K)nextKey,
5140 <                                                        (V)v))) != null)
5141 <                        action.apply(u);
5136 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5137 >                         transformer, action).fork();
5138 >                }
5139 >                for (Node<K,V> p; (p = advance()) != null; ) {
5140 >                    U u;
5141 >                    if ((u = transformer.apply(p)) != null)
5142 >                        action.accept(u);
5143                  }
5144                  propagateCompletion();
5145              }
5146          }
5147      }
5148  
5149 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5150 <        extends Traverser<K,V,Void> {
5151 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5152 <        final Action<U> action;
5149 >    @SuppressWarnings("serial")
5150 >    static final class ForEachTransformedMappingTask<K,V,U>
5151 >        extends BulkTask<K,V,Void> {
5152 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5153 >        final Consumer<? super U> action;
5154          ForEachTransformedMappingTask
5155 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5156 <             BiFun<? super K, ? super V, ? extends U> transformer,
5157 <             Action<U> action) {
5158 <            super(m, p, b);
5155 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5156 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5157 >             Consumer<? super U> action) {
5158 >            super(p, b, i, f, t);
5159              this.transformer = transformer; this.action = action;
5160          }
5161 <        @SuppressWarnings("unchecked") public final void compute() {
5162 <            final BiFun<? super K, ? super V, ? extends U> transformer;
5163 <            final Action<U> action;
5161 >        public final void compute() {
5162 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5163 >            final Consumer<? super U> action;
5164              if ((transformer = this.transformer) != null &&
5165                  (action = this.action) != null) {
5166 <                for (int b; (b = preSplit()) > 0;)
5166 >                for (int i = baseIndex, f, h; batch > 0 &&
5167 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5168 >                    addToPendingCount(1);
5169                      new ForEachTransformedMappingTask<K,V,U>
5170 <                        (map, this, b, transformer, action).fork();
5171 <                Object v; U u;
5172 <                while ((v = advance()) != null) {
5173 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5174 <                        action.apply(u);
5170 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5171 >                         transformer, action).fork();
5172 >                }
5173 >                for (Node<K,V> p; (p = advance()) != null; ) {
5174 >                    U u;
5175 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5176 >                        action.accept(u);
5177                  }
5178                  propagateCompletion();
5179              }
5180          }
5181      }
5182  
5183 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5184 <        extends Traverser<K,V,U> {
5185 <        final Fun<? super K, ? extends U> searchFunction;
5183 >    @SuppressWarnings("serial")
5184 >    static final class SearchKeysTask<K,V,U>
5185 >        extends BulkTask<K,V,U> {
5186 >        final Function<? super K, ? extends U> searchFunction;
5187          final AtomicReference<U> result;
5188          SearchKeysTask
5189 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5190 <             Fun<? super K, ? extends U> searchFunction,
5189 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5190 >             Function<? super K, ? extends U> searchFunction,
5191               AtomicReference<U> result) {
5192 <            super(m, p, b);
5192 >            super(p, b, i, f, t);
5193              this.searchFunction = searchFunction; this.result = result;
5194          }
5195          public final U getRawResult() { return result.get(); }
5196 <        @SuppressWarnings("unchecked") public final void compute() {
5197 <            final Fun<? super K, ? extends U> searchFunction;
5196 >        public final void compute() {
5197 >            final Function<? super K, ? extends U> searchFunction;
5198              final AtomicReference<U> result;
5199              if ((searchFunction = this.searchFunction) != null &&
5200                  (result = this.result) != null) {
5201 <                for (int b;;) {
5201 >                for (int i = baseIndex, f, h; batch > 0 &&
5202 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5203                      if (result.get() != null)
5204                          return;
5205 <                    if ((b = preSplit()) <= 0)
5439 <                        break;
5205 >                    addToPendingCount(1);
5206                      new SearchKeysTask<K,V,U>
5207 <                        (map, this, b, searchFunction, result).fork();
5207 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5208 >                         searchFunction, result).fork();
5209                  }
5210                  while (result.get() == null) {
5211                      U u;
5212 <                    if (advance() == null) {
5212 >                    Node<K,V> p;
5213 >                    if ((p = advance()) == null) {
5214                          propagateCompletion();
5215                          break;
5216                      }
5217 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
5217 >                    if ((u = searchFunction.apply(p.key)) != null) {
5218                          if (result.compareAndSet(null, u))
5219                              quietlyCompleteRoot();
5220                          break;
# Line 5456 | Line 5224 | public class ConcurrentHashMap<K, V>
5224          }
5225      }
5226  
5227 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5228 <        extends Traverser<K,V,U> {
5229 <        final Fun<? super V, ? extends U> searchFunction;
5227 >    @SuppressWarnings("serial")
5228 >    static final class SearchValuesTask<K,V,U>
5229 >        extends BulkTask<K,V,U> {
5230 >        final Function<? super V, ? extends U> searchFunction;
5231          final AtomicReference<U> result;
5232          SearchValuesTask
5233 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5234 <             Fun<? super V, ? extends U> searchFunction,
5233 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5234 >             Function<? super V, ? extends U> searchFunction,
5235               AtomicReference<U> result) {
5236 <            super(m, p, b);
5236 >            super(p, b, i, f, t);
5237              this.searchFunction = searchFunction; this.result = result;
5238          }
5239          public final U getRawResult() { return result.get(); }
5240 <        @SuppressWarnings("unchecked") public final void compute() {
5241 <            final Fun<? super V, ? extends U> searchFunction;
5240 >        public final void compute() {
5241 >            final Function<? super V, ? extends U> searchFunction;
5242              final AtomicReference<U> result;
5243              if ((searchFunction = this.searchFunction) != null &&
5244                  (result = this.result) != null) {
5245 <                for (int b;;) {
5245 >                for (int i = baseIndex, f, h; batch > 0 &&
5246 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5247                      if (result.get() != null)
5248                          return;
5249 <                    if ((b = preSplit()) <= 0)
5480 <                        break;
5249 >                    addToPendingCount(1);
5250                      new SearchValuesTask<K,V,U>
5251 <                        (map, this, b, searchFunction, result).fork();
5251 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5252 >                         searchFunction, result).fork();
5253                  }
5254                  while (result.get() == null) {
5255 <                    Object v; U u;
5256 <                    if ((v = advance()) == null) {
5255 >                    U u;
5256 >                    Node<K,V> p;
5257 >                    if ((p = advance()) == null) {
5258                          propagateCompletion();
5259                          break;
5260                      }
5261 <                    if ((u = searchFunction.apply((V)v)) != null) {
5261 >                    if ((u = searchFunction.apply(p.val)) != null) {
5262                          if (result.compareAndSet(null, u))
5263                              quietlyCompleteRoot();
5264                          break;
# Line 5497 | Line 5268 | public class ConcurrentHashMap<K, V>
5268          }
5269      }
5270  
5271 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5272 <        extends Traverser<K,V,U> {
5273 <        final Fun<Entry<K,V>, ? extends U> searchFunction;
5271 >    @SuppressWarnings("serial")
5272 >    static final class SearchEntriesTask<K,V,U>
5273 >        extends BulkTask<K,V,U> {
5274 >        final Function<Entry<K,V>, ? extends U> searchFunction;
5275          final AtomicReference<U> result;
5276          SearchEntriesTask
5277 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5278 <             Fun<Entry<K,V>, ? extends U> searchFunction,
5277 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5278 >             Function<Entry<K,V>, ? extends U> searchFunction,
5279               AtomicReference<U> result) {
5280 <            super(m, p, b);
5280 >            super(p, b, i, f, t);
5281              this.searchFunction = searchFunction; this.result = result;
5282          }
5283          public final U getRawResult() { return result.get(); }
5284 <        @SuppressWarnings("unchecked") public final void compute() {
5285 <            final Fun<Entry<K,V>, ? extends U> searchFunction;
5284 >        public final void compute() {
5285 >            final Function<Entry<K,V>, ? extends U> searchFunction;
5286              final AtomicReference<U> result;
5287              if ((searchFunction = this.searchFunction) != null &&
5288                  (result = this.result) != null) {
5289 <                for (int b;;) {
5289 >                for (int i = baseIndex, f, h; batch > 0 &&
5290 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5291                      if (result.get() != null)
5292                          return;
5293 <                    if ((b = preSplit()) <= 0)
5521 <                        break;
5293 >                    addToPendingCount(1);
5294                      new SearchEntriesTask<K,V,U>
5295 <                        (map, this, b, searchFunction, result).fork();
5295 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5296 >                         searchFunction, result).fork();
5297                  }
5298                  while (result.get() == null) {
5299 <                    Object v; U u;
5300 <                    if ((v = advance()) == null) {
5299 >                    U u;
5300 >                    Node<K,V> p;
5301 >                    if ((p = advance()) == null) {
5302                          propagateCompletion();
5303                          break;
5304                      }
5305 <                    if ((u = searchFunction.apply(entryFor((K)nextKey,
5532 <                                                           (V)v))) != null) {
5305 >                    if ((u = searchFunction.apply(p)) != null) {
5306                          if (result.compareAndSet(null, u))
5307                              quietlyCompleteRoot();
5308                          return;
# Line 5539 | Line 5312 | public class ConcurrentHashMap<K, V>
5312          }
5313      }
5314  
5315 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5316 <        extends Traverser<K,V,U> {
5317 <        final BiFun<? super K, ? super V, ? extends U> searchFunction;
5315 >    @SuppressWarnings("serial")
5316 >    static final class SearchMappingsTask<K,V,U>
5317 >        extends BulkTask<K,V,U> {
5318 >        final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5319          final AtomicReference<U> result;
5320          SearchMappingsTask
5321 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5322 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
5321 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5322 >             BiFunction<? super K, ? super V, ? extends U> searchFunction,
5323               AtomicReference<U> result) {
5324 <            super(m, p, b);
5324 >            super(p, b, i, f, t);
5325              this.searchFunction = searchFunction; this.result = result;
5326          }
5327          public final U getRawResult() { return result.get(); }
5328 <        @SuppressWarnings("unchecked") public final void compute() {
5329 <            final BiFun<? super K, ? super V, ? extends U> searchFunction;
5328 >        public final void compute() {
5329 >            final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5330              final AtomicReference<U> result;
5331              if ((searchFunction = this.searchFunction) != null &&
5332                  (result = this.result) != null) {
5333 <                for (int b;;) {
5333 >                for (int i = baseIndex, f, h; batch > 0 &&
5334 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5335                      if (result.get() != null)
5336                          return;
5337 <                    if ((b = preSplit()) <= 0)
5563 <                        break;
5337 >                    addToPendingCount(1);
5338                      new SearchMappingsTask<K,V,U>
5339 <                        (map, this, b, searchFunction, result).fork();
5339 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5340 >                         searchFunction, result).fork();
5341                  }
5342                  while (result.get() == null) {
5343 <                    Object v; U u;
5344 <                    if ((v = advance()) == null) {
5343 >                    U u;
5344 >                    Node<K,V> p;
5345 >                    if ((p = advance()) == null) {
5346                          propagateCompletion();
5347                          break;
5348                      }
5349 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5349 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5350                          if (result.compareAndSet(null, u))
5351                              quietlyCompleteRoot();
5352                          break;
# Line 5580 | Line 5356 | public class ConcurrentHashMap<K, V>
5356          }
5357      }
5358  
5359 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5360 <        extends Traverser<K,V,K> {
5361 <        final BiFun<? super K, ? super K, ? extends K> reducer;
5359 >    @SuppressWarnings("serial")
5360 >    static final class ReduceKeysTask<K,V>
5361 >        extends BulkTask<K,V,K> {
5362 >        final BiFunction<? super K, ? super K, ? extends K> reducer;
5363          K result;
5364          ReduceKeysTask<K,V> rights, nextRight;
5365          ReduceKeysTask
5366 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5366 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5367               ReduceKeysTask<K,V> nextRight,
5368 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5369 <            super(m, p, b); this.nextRight = nextRight;
5368 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
5369 >            super(p, b, i, f, t); this.nextRight = nextRight;
5370              this.reducer = reducer;
5371          }
5372          public final K getRawResult() { return result; }
5373 <        @SuppressWarnings("unchecked") public final void compute() {
5374 <            final BiFun<? super K, ? super K, ? extends K> reducer;
5373 >        public final void compute() {
5374 >            final BiFunction<? super K, ? super K, ? extends K> reducer;
5375              if ((reducer = this.reducer) != null) {
5376 <                for (int b; (b = preSplit()) > 0;)
5376 >                for (int i = baseIndex, f, h; batch > 0 &&
5377 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5378 >                    addToPendingCount(1);
5379                      (rights = new ReduceKeysTask<K,V>
5380 <                     (map, this, b, rights, reducer)).fork();
5380 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5381 >                      rights, reducer)).fork();
5382 >                }
5383                  K r = null;
5384 <                while (advance() != null) {
5385 <                    K u = (K)nextKey;
5386 <                    r = (r == null) ? u : reducer.apply(r, u);
5384 >                for (Node<K,V> p; (p = advance()) != null; ) {
5385 >                    K u = p.key;
5386 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5387                  }
5388                  result = r;
5389                  CountedCompleter<?> c;
5390                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5391 +                    @SuppressWarnings("unchecked")
5392                      ReduceKeysTask<K,V>
5393                          t = (ReduceKeysTask<K,V>)c,
5394                          s = t.rights;
# Line 5622 | Line 5404 | public class ConcurrentHashMap<K, V>
5404          }
5405      }
5406  
5407 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5408 <        extends Traverser<K,V,V> {
5409 <        final BiFun<? super V, ? super V, ? extends V> reducer;
5407 >    @SuppressWarnings("serial")
5408 >    static final class ReduceValuesTask<K,V>
5409 >        extends BulkTask<K,V,V> {
5410 >        final BiFunction<? super V, ? super V, ? extends V> reducer;
5411          V result;
5412          ReduceValuesTask<K,V> rights, nextRight;
5413          ReduceValuesTask
5414 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5414 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5415               ReduceValuesTask<K,V> nextRight,
5416 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5417 <            super(m, p, b); this.nextRight = nextRight;
5416 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
5417 >            super(p, b, i, f, t); this.nextRight = nextRight;
5418              this.reducer = reducer;
5419          }
5420          public final V getRawResult() { return result; }
5421 <        @SuppressWarnings("unchecked") public final void compute() {
5422 <            final BiFun<? super V, ? super V, ? extends V> reducer;
5421 >        public final void compute() {
5422 >            final BiFunction<? super V, ? super V, ? extends V> reducer;
5423              if ((reducer = this.reducer) != null) {
5424 <                for (int b; (b = preSplit()) > 0;)
5424 >                for (int i = baseIndex, f, h; batch > 0 &&
5425 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5426 >                    addToPendingCount(1);
5427                      (rights = new ReduceValuesTask<K,V>
5428 <                     (map, this, b, rights, reducer)).fork();
5428 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5429 >                      rights, reducer)).fork();
5430 >                }
5431                  V r = null;
5432 <                Object v;
5433 <                while ((v = advance()) != null) {
5434 <                    V u = (V)v;
5648 <                    r = (r == null) ? u : reducer.apply(r, u);
5432 >                for (Node<K,V> p; (p = advance()) != null; ) {
5433 >                    V v = p.val;
5434 >                    r = (r == null) ? v : reducer.apply(r, v);
5435                  }
5436                  result = r;
5437                  CountedCompleter<?> c;
5438                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5439 +                    @SuppressWarnings("unchecked")
5440                      ReduceValuesTask<K,V>
5441                          t = (ReduceValuesTask<K,V>)c,
5442                          s = t.rights;
# Line 5665 | Line 5452 | public class ConcurrentHashMap<K, V>
5452          }
5453      }
5454  
5455 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5456 <        extends Traverser<K,V,Map.Entry<K,V>> {
5457 <        final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5455 >    @SuppressWarnings("serial")
5456 >    static final class ReduceEntriesTask<K,V>
5457 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5458 >        final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5459          Map.Entry<K,V> result;
5460          ReduceEntriesTask<K,V> rights, nextRight;
5461          ReduceEntriesTask
5462 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5462 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5463               ReduceEntriesTask<K,V> nextRight,
5464 <             BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5465 <            super(m, p, b); this.nextRight = nextRight;
5464 >             BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5465 >            super(p, b, i, f, t); this.nextRight = nextRight;
5466              this.reducer = reducer;
5467          }
5468          public final Map.Entry<K,V> getRawResult() { return result; }
5469 <        @SuppressWarnings("unchecked") public final void compute() {
5470 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5469 >        public final void compute() {
5470 >            final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5471              if ((reducer = this.reducer) != null) {
5472 <                for (int b; (b = preSplit()) > 0;)
5472 >                for (int i = baseIndex, f, h; batch > 0 &&
5473 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5474 >                    addToPendingCount(1);
5475                      (rights = new ReduceEntriesTask<K,V>
5476 <                     (map, this, b, rights, reducer)).fork();
5477 <                Map.Entry<K,V> r = null;
5688 <                Object v;
5689 <                while ((v = advance()) != null) {
5690 <                    Map.Entry<K,V> u = entryFor((K)nextKey, (V)v);
5691 <                    r = (r == null) ? u : reducer.apply(r, u);
5476 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5477 >                      rights, reducer)).fork();
5478                  }
5479 +                Map.Entry<K,V> r = null;
5480 +                for (Node<K,V> p; (p = advance()) != null; )
5481 +                    r = (r == null) ? p : reducer.apply(r, p);
5482                  result = r;
5483                  CountedCompleter<?> c;
5484                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5485 +                    @SuppressWarnings("unchecked")
5486                      ReduceEntriesTask<K,V>
5487                          t = (ReduceEntriesTask<K,V>)c,
5488                          s = t.rights;
# Line 5708 | Line 5498 | public class ConcurrentHashMap<K, V>
5498          }
5499      }
5500  
5501 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5502 <        extends Traverser<K,V,U> {
5503 <        final Fun<? super K, ? extends U> transformer;
5504 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5501 >    @SuppressWarnings("serial")
5502 >    static final class MapReduceKeysTask<K,V,U>
5503 >        extends BulkTask<K,V,U> {
5504 >        final Function<? super K, ? extends U> transformer;
5505 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5506          U result;
5507          MapReduceKeysTask<K,V,U> rights, nextRight;
5508          MapReduceKeysTask
5509 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5509 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5510               MapReduceKeysTask<K,V,U> nextRight,
5511 <             Fun<? super K, ? extends U> transformer,
5512 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5513 <            super(m, p, b); this.nextRight = nextRight;
5511 >             Function<? super K, ? extends U> transformer,
5512 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5513 >            super(p, b, i, f, t); this.nextRight = nextRight;
5514              this.transformer = transformer;
5515              this.reducer = reducer;
5516          }
5517          public final U getRawResult() { return result; }
5518 <        @SuppressWarnings("unchecked") public final void compute() {
5519 <            final Fun<? super K, ? extends U> transformer;
5520 <            final BiFun<? super U, ? super U, ? extends U> reducer;
5518 >        public final void compute() {
5519 >            final Function<? super K, ? extends U> transformer;
5520 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5521              if ((transformer = this.transformer) != null &&
5522                  (reducer = this.reducer) != null) {
5523 <                for (int b; (b = preSplit()) > 0;)
5523 >                for (int i = baseIndex, f, h; batch > 0 &&
5524 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5525 >                    addToPendingCount(1);
5526                      (rights = new MapReduceKeysTask<K,V,U>
5527 <                     (map, this, b, rights, transformer, reducer)).fork();
5528 <                U r = null, u;
5529 <                while (advance() != null) {
5530 <                    if ((u = transformer.apply((K)nextKey)) != null)
5527 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5528 >                      rights, transformer, reducer)).fork();
5529 >                }
5530 >                U r = null;
5531 >                for (Node<K,V> p; (p = advance()) != null; ) {
5532 >                    U u;
5533 >                    if ((u = transformer.apply(p.key)) != null)
5534                          r = (r == null) ? u : reducer.apply(r, u);
5535                  }
5536                  result = r;
5537                  CountedCompleter<?> c;
5538                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5539 +                    @SuppressWarnings("unchecked")
5540                      MapReduceKeysTask<K,V,U>
5541                          t = (MapReduceKeysTask<K,V,U>)c,
5542                          s = t.rights;
# Line 5755 | Line 5552 | public class ConcurrentHashMap<K, V>
5552          }
5553      }
5554  
5555 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5556 <        extends Traverser<K,V,U> {
5557 <        final Fun<? super V, ? extends U> transformer;
5558 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5555 >    @SuppressWarnings("serial")
5556 >    static final class MapReduceValuesTask<K,V,U>
5557 >        extends BulkTask<K,V,U> {
5558 >        final Function<? super V, ? extends U> transformer;
5559 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5560          U result;
5561          MapReduceValuesTask<K,V,U> rights, nextRight;
5562          MapReduceValuesTask
5563 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5563 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5564               MapReduceValuesTask<K,V,U> nextRight,
5565 <             Fun<? super V, ? extends U> transformer,
5566 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5567 <            super(m, p, b); this.nextRight = nextRight;
5565 >             Function<? super V, ? extends U> transformer,
5566 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5567 >            super(p, b, i, f, t); this.nextRight = nextRight;
5568              this.transformer = transformer;
5569              this.reducer = reducer;
5570          }
5571          public final U getRawResult() { return result; }
5572 <        @SuppressWarnings("unchecked") public final void compute() {
5573 <            final Fun<? super V, ? extends U> transformer;
5574 <            final BiFun<? super U, ? super U, ? extends U> reducer;
5572 >        public final void compute() {
5573 >            final Function<? super V, ? extends U> transformer;
5574 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5575              if ((transformer = this.transformer) != null &&
5576                  (reducer = this.reducer) != null) {
5577 <                for (int b; (b = preSplit()) > 0;)
5577 >                for (int i = baseIndex, f, h; batch > 0 &&
5578 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5579 >                    addToPendingCount(1);
5580                      (rights = new MapReduceValuesTask<K,V,U>
5581 <                     (map, this, b, rights, transformer, reducer)).fork();
5582 <                U r = null, u;
5583 <                Object v;
5584 <                while ((v = advance()) != null) {
5585 <                    if ((u = transformer.apply((V)v)) != null)
5581 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5582 >                      rights, transformer, reducer)).fork();
5583 >                }
5584 >                U r = null;
5585 >                for (Node<K,V> p; (p = advance()) != null; ) {
5586 >                    U u;
5587 >                    if ((u = transformer.apply(p.val)) != null)
5588                          r = (r == null) ? u : reducer.apply(r, u);
5589                  }
5590                  result = r;
5591                  CountedCompleter<?> c;
5592                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5593 +                    @SuppressWarnings("unchecked")
5594                      MapReduceValuesTask<K,V,U>
5595                          t = (MapReduceValuesTask<K,V,U>)c,
5596                          s = t.rights;
# Line 5803 | Line 5606 | public class ConcurrentHashMap<K, V>
5606          }
5607      }
5608  
5609 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5610 <        extends Traverser<K,V,U> {
5611 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5612 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5609 >    @SuppressWarnings("serial")
5610 >    static final class MapReduceEntriesTask<K,V,U>
5611 >        extends BulkTask<K,V,U> {
5612 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5613 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5614          U result;
5615          MapReduceEntriesTask<K,V,U> rights, nextRight;
5616          MapReduceEntriesTask
5617 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5617 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5618               MapReduceEntriesTask<K,V,U> nextRight,
5619 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5620 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5621 <            super(m, p, b); this.nextRight = nextRight;
5619 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5620 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5621 >            super(p, b, i, f, t); this.nextRight = nextRight;
5622              this.transformer = transformer;
5623              this.reducer = reducer;
5624          }
5625          public final U getRawResult() { return result; }
5626 <        @SuppressWarnings("unchecked") public final void compute() {
5627 <            final Fun<Map.Entry<K,V>, ? extends U> transformer;
5628 <            final BiFun<? super U, ? super U, ? extends U> reducer;
5626 >        public final void compute() {
5627 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5628 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5629              if ((transformer = this.transformer) != null &&
5630                  (reducer = this.reducer) != null) {
5631 <                for (int b; (b = preSplit()) > 0;)
5631 >                for (int i = baseIndex, f, h; batch > 0 &&
5632 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5633 >                    addToPendingCount(1);
5634                      (rights = new MapReduceEntriesTask<K,V,U>
5635 <                     (map, this, b, rights, transformer, reducer)).fork();
5636 <                U r = null, u;
5637 <                Object v;
5638 <                while ((v = advance()) != null) {
5639 <                    if ((u = transformer.apply(entryFor((K)nextKey,
5640 <                                                        (V)v))) != null)
5635 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5636 >                      rights, transformer, reducer)).fork();
5637 >                }
5638 >                U r = null;
5639 >                for (Node<K,V> p; (p = advance()) != null; ) {
5640 >                    U u;
5641 >                    if ((u = transformer.apply(p)) != null)
5642                          r = (r == null) ? u : reducer.apply(r, u);
5643                  }
5644                  result = r;
5645                  CountedCompleter<?> c;
5646                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5647 +                    @SuppressWarnings("unchecked")
5648                      MapReduceEntriesTask<K,V,U>
5649                          t = (MapReduceEntriesTask<K,V,U>)c,
5650                          s = t.rights;
# Line 5852 | Line 5660 | public class ConcurrentHashMap<K, V>
5660          }
5661      }
5662  
5663 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5664 <        extends Traverser<K,V,U> {
5665 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5666 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5663 >    @SuppressWarnings("serial")
5664 >    static final class MapReduceMappingsTask<K,V,U>
5665 >        extends BulkTask<K,V,U> {
5666 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5667 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5668          U result;
5669          MapReduceMappingsTask<K,V,U> rights, nextRight;
5670          MapReduceMappingsTask
5671 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5671 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5672               MapReduceMappingsTask<K,V,U> nextRight,
5673 <             BiFun<? super K, ? super V, ? extends U> transformer,
5674 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5675 <            super(m, p, b); this.nextRight = nextRight;
5673 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5674 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5675 >            super(p, b, i, f, t); this.nextRight = nextRight;
5676              this.transformer = transformer;
5677              this.reducer = reducer;
5678          }
5679          public final U getRawResult() { return result; }
5680 <        @SuppressWarnings("unchecked") public final void compute() {
5681 <            final BiFun<? super K, ? super V, ? extends U> transformer;
5682 <            final BiFun<? super U, ? super U, ? extends U> reducer;
5680 >        public final void compute() {
5681 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5682 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5683              if ((transformer = this.transformer) != null &&
5684                  (reducer = this.reducer) != null) {
5685 <                for (int b; (b = preSplit()) > 0;)
5685 >                for (int i = baseIndex, f, h; batch > 0 &&
5686 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5687 >                    addToPendingCount(1);
5688                      (rights = new MapReduceMappingsTask<K,V,U>
5689 <                     (map, this, b, rights, transformer, reducer)).fork();
5690 <                U r = null, u;
5691 <                Object v;
5692 <                while ((v = advance()) != null) {
5693 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5689 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5690 >                      rights, transformer, reducer)).fork();
5691 >                }
5692 >                U r = null;
5693 >                for (Node<K,V> p; (p = advance()) != null; ) {
5694 >                    U u;
5695 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5696                          r = (r == null) ? u : reducer.apply(r, u);
5697                  }
5698                  result = r;
5699                  CountedCompleter<?> c;
5700                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5701 +                    @SuppressWarnings("unchecked")
5702                      MapReduceMappingsTask<K,V,U>
5703                          t = (MapReduceMappingsTask<K,V,U>)c,
5704                          s = t.rights;
# Line 5900 | Line 5714 | public class ConcurrentHashMap<K, V>
5714          }
5715      }
5716  
5717 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5718 <        extends Traverser<K,V,Double> {
5719 <        final ObjectToDouble<? super K> transformer;
5720 <        final DoubleByDoubleToDouble reducer;
5717 >    @SuppressWarnings("serial")
5718 >    static final class MapReduceKeysToDoubleTask<K,V>
5719 >        extends BulkTask<K,V,Double> {
5720 >        final ToDoubleFunction<? super K> transformer;
5721 >        final DoubleBinaryOperator reducer;
5722          final double basis;
5723          double result;
5724          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5725          MapReduceKeysToDoubleTask
5726 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5726 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5727               MapReduceKeysToDoubleTask<K,V> nextRight,
5728 <             ObjectToDouble<? super K> transformer,
5728 >             ToDoubleFunction<? super K> transformer,
5729               double basis,
5730 <             DoubleByDoubleToDouble reducer) {
5731 <            super(m, p, b); this.nextRight = nextRight;
5730 >             DoubleBinaryOperator reducer) {
5731 >            super(p, b, i, f, t); this.nextRight = nextRight;
5732              this.transformer = transformer;
5733              this.basis = basis; this.reducer = reducer;
5734          }
5735          public final Double getRawResult() { return result; }
5736 <        @SuppressWarnings("unchecked") public final void compute() {
5737 <            final ObjectToDouble<? super K> transformer;
5738 <            final DoubleByDoubleToDouble reducer;
5736 >        public final void compute() {
5737 >            final ToDoubleFunction<? super K> transformer;
5738 >            final DoubleBinaryOperator reducer;
5739              if ((transformer = this.transformer) != null &&
5740                  (reducer = this.reducer) != null) {
5741                  double r = this.basis;
5742 <                for (int b; (b = preSplit()) > 0;)
5742 >                for (int i = baseIndex, f, h; batch > 0 &&
5743 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5744 >                    addToPendingCount(1);
5745                      (rights = new MapReduceKeysToDoubleTask<K,V>
5746 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5747 <                while (advance() != null)
5748 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5746 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5747 >                      rights, transformer, r, reducer)).fork();
5748 >                }
5749 >                for (Node<K,V> p; (p = advance()) != null; )
5750 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5751                  result = r;
5752                  CountedCompleter<?> c;
5753                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5754 +                    @SuppressWarnings("unchecked")
5755                      MapReduceKeysToDoubleTask<K,V>
5756                          t = (MapReduceKeysToDoubleTask<K,V>)c,
5757                          s = t.rights;
5758                      while (s != null) {
5759 <                        t.result = reducer.apply(t.result, s.result);
5759 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5760                          s = t.rights = s.nextRight;
5761                      }
5762                  }
# Line 5944 | Line 5764 | public class ConcurrentHashMap<K, V>
5764          }
5765      }
5766  
5767 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5768 <        extends Traverser<K,V,Double> {
5769 <        final ObjectToDouble<? super V> transformer;
5770 <        final DoubleByDoubleToDouble reducer;
5767 >    @SuppressWarnings("serial")
5768 >    static final class MapReduceValuesToDoubleTask<K,V>
5769 >        extends BulkTask<K,V,Double> {
5770 >        final ToDoubleFunction<? super V> transformer;
5771 >        final DoubleBinaryOperator reducer;
5772          final double basis;
5773          double result;
5774          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5775          MapReduceValuesToDoubleTask
5776 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5776 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5777               MapReduceValuesToDoubleTask<K,V> nextRight,
5778 <             ObjectToDouble<? super V> transformer,
5778 >             ToDoubleFunction<? super V> transformer,
5779               double basis,
5780 <             DoubleByDoubleToDouble reducer) {
5781 <            super(m, p, b); this.nextRight = nextRight;
5780 >             DoubleBinaryOperator reducer) {
5781 >            super(p, b, i, f, t); this.nextRight = nextRight;
5782              this.transformer = transformer;
5783              this.basis = basis; this.reducer = reducer;
5784          }
5785          public final Double getRawResult() { return result; }
5786 <        @SuppressWarnings("unchecked") public final void compute() {
5787 <            final ObjectToDouble<? super V> transformer;
5788 <            final DoubleByDoubleToDouble reducer;
5786 >        public final void compute() {
5787 >            final ToDoubleFunction<? super V> transformer;
5788 >            final DoubleBinaryOperator reducer;
5789              if ((transformer = this.transformer) != null &&
5790                  (reducer = this.reducer) != null) {
5791                  double r = this.basis;
5792 <                for (int b; (b = preSplit()) > 0;)
5792 >                for (int i = baseIndex, f, h; batch > 0 &&
5793 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5794 >                    addToPendingCount(1);
5795                      (rights = new MapReduceValuesToDoubleTask<K,V>
5796 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5797 <                Object v;
5798 <                while ((v = advance()) != null)
5799 <                    r = reducer.apply(r, transformer.apply((V)v));
5796 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5797 >                      rights, transformer, r, reducer)).fork();
5798 >                }
5799 >                for (Node<K,V> p; (p = advance()) != null; )
5800 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5801                  result = r;
5802                  CountedCompleter<?> c;
5803                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5804 +                    @SuppressWarnings("unchecked")
5805                      MapReduceValuesToDoubleTask<K,V>
5806                          t = (MapReduceValuesToDoubleTask<K,V>)c,
5807                          s = t.rights;
5808                      while (s != null) {
5809 <                        t.result = reducer.apply(t.result, s.result);
5809 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5810                          s = t.rights = s.nextRight;
5811                      }
5812                  }
# Line 5989 | Line 5814 | public class ConcurrentHashMap<K, V>
5814          }
5815      }
5816  
5817 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5818 <        extends Traverser<K,V,Double> {
5819 <        final ObjectToDouble<Map.Entry<K,V>> transformer;
5820 <        final DoubleByDoubleToDouble reducer;
5817 >    @SuppressWarnings("serial")
5818 >    static final class MapReduceEntriesToDoubleTask<K,V>
5819 >        extends BulkTask<K,V,Double> {
5820 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
5821 >        final DoubleBinaryOperator reducer;
5822          final double basis;
5823          double result;
5824          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5825          MapReduceEntriesToDoubleTask
5826 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5826 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5827               MapReduceEntriesToDoubleTask<K,V> nextRight,
5828 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5828 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5829               double basis,
5830 <             DoubleByDoubleToDouble reducer) {
5831 <            super(m, p, b); this.nextRight = nextRight;
5830 >             DoubleBinaryOperator reducer) {
5831 >            super(p, b, i, f, t); this.nextRight = nextRight;
5832              this.transformer = transformer;
5833              this.basis = basis; this.reducer = reducer;
5834          }
5835          public final Double getRawResult() { return result; }
5836 <        @SuppressWarnings("unchecked") public final void compute() {
5837 <            final ObjectToDouble<Map.Entry<K,V>> transformer;
5838 <            final DoubleByDoubleToDouble reducer;
5836 >        public final void compute() {
5837 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
5838 >            final DoubleBinaryOperator reducer;
5839              if ((transformer = this.transformer) != null &&
5840                  (reducer = this.reducer) != null) {
5841                  double r = this.basis;
5842 <                for (int b; (b = preSplit()) > 0;)
5842 >                for (int i = baseIndex, f, h; batch > 0 &&
5843 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5844 >                    addToPendingCount(1);
5845                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5846 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5847 <                Object v;
5848 <                while ((v = advance()) != null)
5849 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5850 <                                                                    (V)v)));
5846 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5847 >                      rights, transformer, r, reducer)).fork();
5848 >                }
5849 >                for (Node<K,V> p; (p = advance()) != null; )
5850 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5851                  result = r;
5852                  CountedCompleter<?> c;
5853                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5854 +                    @SuppressWarnings("unchecked")
5855                      MapReduceEntriesToDoubleTask<K,V>
5856                          t = (MapReduceEntriesToDoubleTask<K,V>)c,
5857                          s = t.rights;
5858                      while (s != null) {
5859 <                        t.result = reducer.apply(t.result, s.result);
5859 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5860                          s = t.rights = s.nextRight;
5861                      }
5862                  }
# Line 6035 | Line 5864 | public class ConcurrentHashMap<K, V>
5864          }
5865      }
5866  
5867 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5868 <        extends Traverser<K,V,Double> {
5869 <        final ObjectByObjectToDouble<? super K, ? super V> transformer;
5870 <        final DoubleByDoubleToDouble reducer;
5867 >    @SuppressWarnings("serial")
5868 >    static final class MapReduceMappingsToDoubleTask<K,V>
5869 >        extends BulkTask<K,V,Double> {
5870 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
5871 >        final DoubleBinaryOperator reducer;
5872          final double basis;
5873          double result;
5874          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5875          MapReduceMappingsToDoubleTask
5876 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5876 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5877               MapReduceMappingsToDoubleTask<K,V> nextRight,
5878 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
5878 >             ToDoubleBiFunction<? super K, ? super V> transformer,
5879               double basis,
5880 <             DoubleByDoubleToDouble reducer) {
5881 <            super(m, p, b); this.nextRight = nextRight;
5880 >             DoubleBinaryOperator reducer) {
5881 >            super(p, b, i, f, t); this.nextRight = nextRight;
5882              this.transformer = transformer;
5883              this.basis = basis; this.reducer = reducer;
5884          }
5885          public final Double getRawResult() { return result; }
5886 <        @SuppressWarnings("unchecked") public final void compute() {
5887 <            final ObjectByObjectToDouble<? super K, ? super V> transformer;
5888 <            final DoubleByDoubleToDouble reducer;
5886 >        public final void compute() {
5887 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
5888 >            final DoubleBinaryOperator reducer;
5889              if ((transformer = this.transformer) != null &&
5890                  (reducer = this.reducer) != null) {
5891                  double r = this.basis;
5892 <                for (int b; (b = preSplit()) > 0;)
5892 >                for (int i = baseIndex, f, h; batch > 0 &&
5893 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5894 >                    addToPendingCount(1);
5895                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5896 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5897 <                Object v;
5898 <                while ((v = advance()) != null)
5899 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5896 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5897 >                      rights, transformer, r, reducer)).fork();
5898 >                }
5899 >                for (Node<K,V> p; (p = advance()) != null; )
5900 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5901                  result = r;
5902                  CountedCompleter<?> c;
5903                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5904 +                    @SuppressWarnings("unchecked")
5905                      MapReduceMappingsToDoubleTask<K,V>
5906                          t = (MapReduceMappingsToDoubleTask<K,V>)c,
5907                          s = t.rights;
5908                      while (s != null) {
5909 <                        t.result = reducer.apply(t.result, s.result);
5909 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5910                          s = t.rights = s.nextRight;
5911                      }
5912                  }
# Line 6080 | Line 5914 | public class ConcurrentHashMap<K, V>
5914          }
5915      }
5916  
5917 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5918 <        extends Traverser<K,V,Long> {
5919 <        final ObjectToLong<? super K> transformer;
5920 <        final LongByLongToLong reducer;
5917 >    @SuppressWarnings("serial")
5918 >    static final class MapReduceKeysToLongTask<K,V>
5919 >        extends BulkTask<K,V,Long> {
5920 >        final ToLongFunction<? super K> transformer;
5921 >        final LongBinaryOperator reducer;
5922          final long basis;
5923          long result;
5924          MapReduceKeysToLongTask<K,V> rights, nextRight;
5925          MapReduceKeysToLongTask
5926 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5926 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5927               MapReduceKeysToLongTask<K,V> nextRight,
5928 <             ObjectToLong<? super K> transformer,
5928 >             ToLongFunction<? super K> transformer,
5929               long basis,
5930 <             LongByLongToLong reducer) {
5931 <            super(m, p, b); this.nextRight = nextRight;
5930 >             LongBinaryOperator reducer) {
5931 >            super(p, b, i, f, t); this.nextRight = nextRight;
5932              this.transformer = transformer;
5933              this.basis = basis; this.reducer = reducer;
5934          }
5935          public final Long getRawResult() { return result; }
5936 <        @SuppressWarnings("unchecked") public final void compute() {
5937 <            final ObjectToLong<? super K> transformer;
5938 <            final LongByLongToLong reducer;
5936 >        public final void compute() {
5937 >            final ToLongFunction<? super K> transformer;
5938 >            final LongBinaryOperator reducer;
5939              if ((transformer = this.transformer) != null &&
5940                  (reducer = this.reducer) != null) {
5941                  long r = this.basis;
5942 <                for (int b; (b = preSplit()) > 0;)
5942 >                for (int i = baseIndex, f, h; batch > 0 &&
5943 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5944 >                    addToPendingCount(1);
5945                      (rights = new MapReduceKeysToLongTask<K,V>
5946 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5947 <                while (advance() != null)
5948 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5946 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5947 >                      rights, transformer, r, reducer)).fork();
5948 >                }
5949 >                for (Node<K,V> p; (p = advance()) != null; )
5950 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5951                  result = r;
5952                  CountedCompleter<?> c;
5953                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5954 +                    @SuppressWarnings("unchecked")
5955                      MapReduceKeysToLongTask<K,V>
5956                          t = (MapReduceKeysToLongTask<K,V>)c,
5957                          s = t.rights;
5958                      while (s != null) {
5959 <                        t.result = reducer.apply(t.result, s.result);
5959 >                        t.result = reducer.applyAsLong(t.result, s.result);
5960                          s = t.rights = s.nextRight;
5961                      }
5962                  }
# Line 6124 | Line 5964 | public class ConcurrentHashMap<K, V>
5964          }
5965      }
5966  
5967 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5968 <        extends Traverser<K,V,Long> {
5969 <        final ObjectToLong<? super V> transformer;
5970 <        final LongByLongToLong reducer;
5967 >    @SuppressWarnings("serial")
5968 >    static final class MapReduceValuesToLongTask<K,V>
5969 >        extends BulkTask<K,V,Long> {
5970 >        final ToLongFunction<? super V> transformer;
5971 >        final LongBinaryOperator reducer;
5972          final long basis;
5973          long result;
5974          MapReduceValuesToLongTask<K,V> rights, nextRight;
5975          MapReduceValuesToLongTask
5976 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5976 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5977               MapReduceValuesToLongTask<K,V> nextRight,
5978 <             ObjectToLong<? super V> transformer,
5978 >             ToLongFunction<? super V> transformer,
5979               long basis,
5980 <             LongByLongToLong reducer) {
5981 <            super(m, p, b); this.nextRight = nextRight;
5980 >             LongBinaryOperator reducer) {
5981 >            super(p, b, i, f, t); this.nextRight = nextRight;
5982              this.transformer = transformer;
5983              this.basis = basis; this.reducer = reducer;
5984          }
5985          public final Long getRawResult() { return result; }
5986 <        @SuppressWarnings("unchecked") public final void compute() {
5987 <            final ObjectToLong<? super V> transformer;
5988 <            final LongByLongToLong reducer;
5986 >        public final void compute() {
5987 >            final ToLongFunction<? super V> transformer;
5988 >            final LongBinaryOperator reducer;
5989              if ((transformer = this.transformer) != null &&
5990                  (reducer = this.reducer) != null) {
5991                  long r = this.basis;
5992 <                for (int b; (b = preSplit()) > 0;)
5992 >                for (int i = baseIndex, f, h; batch > 0 &&
5993 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5994 >                    addToPendingCount(1);
5995                      (rights = new MapReduceValuesToLongTask<K,V>
5996 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5997 <                Object v;
5998 <                while ((v = advance()) != null)
5999 <                    r = reducer.apply(r, transformer.apply((V)v));
5996 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5997 >                      rights, transformer, r, reducer)).fork();
5998 >                }
5999 >                for (Node<K,V> p; (p = advance()) != null; )
6000 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
6001                  result = r;
6002                  CountedCompleter<?> c;
6003                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6004 +                    @SuppressWarnings("unchecked")
6005                      MapReduceValuesToLongTask<K,V>
6006                          t = (MapReduceValuesToLongTask<K,V>)c,
6007                          s = t.rights;
6008                      while (s != null) {
6009 <                        t.result = reducer.apply(t.result, s.result);
6009 >                        t.result = reducer.applyAsLong(t.result, s.result);
6010                          s = t.rights = s.nextRight;
6011                      }
6012                  }
# Line 6169 | Line 6014 | public class ConcurrentHashMap<K, V>
6014          }
6015      }
6016  
6017 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6018 <        extends Traverser<K,V,Long> {
6019 <        final ObjectToLong<Map.Entry<K,V>> transformer;
6020 <        final LongByLongToLong reducer;
6017 >    @SuppressWarnings("serial")
6018 >    static final class MapReduceEntriesToLongTask<K,V>
6019 >        extends BulkTask<K,V,Long> {
6020 >        final ToLongFunction<Map.Entry<K,V>> transformer;
6021 >        final LongBinaryOperator reducer;
6022          final long basis;
6023          long result;
6024          MapReduceEntriesToLongTask<K,V> rights, nextRight;
6025          MapReduceEntriesToLongTask
6026 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6026 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6027               MapReduceEntriesToLongTask<K,V> nextRight,
6028 <             ObjectToLong<Map.Entry<K,V>> transformer,
6028 >             ToLongFunction<Map.Entry<K,V>> transformer,
6029               long basis,
6030 <             LongByLongToLong reducer) {
6031 <            super(m, p, b); this.nextRight = nextRight;
6030 >             LongBinaryOperator reducer) {
6031 >            super(p, b, i, f, t); this.nextRight = nextRight;
6032              this.transformer = transformer;
6033              this.basis = basis; this.reducer = reducer;
6034          }
6035          public final Long getRawResult() { return result; }
6036 <        @SuppressWarnings("unchecked") public final void compute() {
6037 <            final ObjectToLong<Map.Entry<K,V>> transformer;
6038 <            final LongByLongToLong reducer;
6036 >        public final void compute() {
6037 >            final ToLongFunction<Map.Entry<K,V>> transformer;
6038 >            final LongBinaryOperator reducer;
6039              if ((transformer = this.transformer) != null &&
6040                  (reducer = this.reducer) != null) {
6041                  long r = this.basis;
6042 <                for (int b; (b = preSplit()) > 0;)
6042 >                for (int i = baseIndex, f, h; batch > 0 &&
6043 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6044 >                    addToPendingCount(1);
6045                      (rights = new MapReduceEntriesToLongTask<K,V>
6046 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6047 <                Object v;
6048 <                while ((v = advance()) != null)
6049 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6050 <                                                                    (V)v)));
6046 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6047 >                      rights, transformer, r, reducer)).fork();
6048 >                }
6049 >                for (Node<K,V> p; (p = advance()) != null; )
6050 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
6051                  result = r;
6052                  CountedCompleter<?> c;
6053                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6054 +                    @SuppressWarnings("unchecked")
6055                      MapReduceEntriesToLongTask<K,V>
6056                          t = (MapReduceEntriesToLongTask<K,V>)c,
6057                          s = t.rights;
6058                      while (s != null) {
6059 <                        t.result = reducer.apply(t.result, s.result);
6059 >                        t.result = reducer.applyAsLong(t.result, s.result);
6060                          s = t.rights = s.nextRight;
6061                      }
6062                  }
# Line 6215 | Line 6064 | public class ConcurrentHashMap<K, V>
6064          }
6065      }
6066  
6067 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6068 <        extends Traverser<K,V,Long> {
6069 <        final ObjectByObjectToLong<? super K, ? super V> transformer;
6070 <        final LongByLongToLong reducer;
6067 >    @SuppressWarnings("serial")
6068 >    static final class MapReduceMappingsToLongTask<K,V>
6069 >        extends BulkTask<K,V,Long> {
6070 >        final ToLongBiFunction<? super K, ? super V> transformer;
6071 >        final LongBinaryOperator reducer;
6072          final long basis;
6073          long result;
6074          MapReduceMappingsToLongTask<K,V> rights, nextRight;
6075          MapReduceMappingsToLongTask
6076 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6076 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6077               MapReduceMappingsToLongTask<K,V> nextRight,
6078 <             ObjectByObjectToLong<? super K, ? super V> transformer,
6078 >             ToLongBiFunction<? super K, ? super V> transformer,
6079               long basis,
6080 <             LongByLongToLong reducer) {
6081 <            super(m, p, b); this.nextRight = nextRight;
6080 >             LongBinaryOperator reducer) {
6081 >            super(p, b, i, f, t); this.nextRight = nextRight;
6082              this.transformer = transformer;
6083              this.basis = basis; this.reducer = reducer;
6084          }
6085          public final Long getRawResult() { return result; }
6086 <        @SuppressWarnings("unchecked") public final void compute() {
6087 <            final ObjectByObjectToLong<? super K, ? super V> transformer;
6088 <            final LongByLongToLong reducer;
6086 >        public final void compute() {
6087 >            final ToLongBiFunction<? super K, ? super V> transformer;
6088 >            final LongBinaryOperator reducer;
6089              if ((transformer = this.transformer) != null &&
6090                  (reducer = this.reducer) != null) {
6091                  long r = this.basis;
6092 <                for (int b; (b = preSplit()) > 0;)
6092 >                for (int i = baseIndex, f, h; batch > 0 &&
6093 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6094 >                    addToPendingCount(1);
6095                      (rights = new MapReduceMappingsToLongTask<K,V>
6096 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6097 <                Object v;
6098 <                while ((v = advance()) != null)
6099 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6096 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6097 >                      rights, transformer, r, reducer)).fork();
6098 >                }
6099 >                for (Node<K,V> p; (p = advance()) != null; )
6100 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
6101                  result = r;
6102                  CountedCompleter<?> c;
6103                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6104 +                    @SuppressWarnings("unchecked")
6105                      MapReduceMappingsToLongTask<K,V>
6106                          t = (MapReduceMappingsToLongTask<K,V>)c,
6107                          s = t.rights;
6108                      while (s != null) {
6109 <                        t.result = reducer.apply(t.result, s.result);
6109 >                        t.result = reducer.applyAsLong(t.result, s.result);
6110                          s = t.rights = s.nextRight;
6111                      }
6112                  }
# Line 6260 | Line 6114 | public class ConcurrentHashMap<K, V>
6114          }
6115      }
6116  
6117 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6118 <        extends Traverser<K,V,Integer> {
6119 <        final ObjectToInt<? super K> transformer;
6120 <        final IntByIntToInt reducer;
6117 >    @SuppressWarnings("serial")
6118 >    static final class MapReduceKeysToIntTask<K,V>
6119 >        extends BulkTask<K,V,Integer> {
6120 >        final ToIntFunction<? super K> transformer;
6121 >        final IntBinaryOperator reducer;
6122          final int basis;
6123          int result;
6124          MapReduceKeysToIntTask<K,V> rights, nextRight;
6125          MapReduceKeysToIntTask
6126 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6126 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6127               MapReduceKeysToIntTask<K,V> nextRight,
6128 <             ObjectToInt<? super K> transformer,
6128 >             ToIntFunction<? super K> transformer,
6129               int basis,
6130 <             IntByIntToInt reducer) {
6131 <            super(m, p, b); this.nextRight = nextRight;
6130 >             IntBinaryOperator reducer) {
6131 >            super(p, b, i, f, t); this.nextRight = nextRight;
6132              this.transformer = transformer;
6133              this.basis = basis; this.reducer = reducer;
6134          }
6135          public final Integer getRawResult() { return result; }
6136 <        @SuppressWarnings("unchecked") public final void compute() {
6137 <            final ObjectToInt<? super K> transformer;
6138 <            final IntByIntToInt reducer;
6136 >        public final void compute() {
6137 >            final ToIntFunction<? super K> transformer;
6138 >            final IntBinaryOperator reducer;
6139              if ((transformer = this.transformer) != null &&
6140                  (reducer = this.reducer) != null) {
6141                  int r = this.basis;
6142 <                for (int b; (b = preSplit()) > 0;)
6142 >                for (int i = baseIndex, f, h; batch > 0 &&
6143 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6144 >                    addToPendingCount(1);
6145                      (rights = new MapReduceKeysToIntTask<K,V>
6146 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6147 <                while (advance() != null)
6148 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
6146 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6147 >                      rights, transformer, r, reducer)).fork();
6148 >                }
6149 >                for (Node<K,V> p; (p = advance()) != null; )
6150 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
6151                  result = r;
6152                  CountedCompleter<?> c;
6153                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6154 +                    @SuppressWarnings("unchecked")
6155                      MapReduceKeysToIntTask<K,V>
6156                          t = (MapReduceKeysToIntTask<K,V>)c,
6157                          s = t.rights;
6158                      while (s != null) {
6159 <                        t.result = reducer.apply(t.result, s.result);
6159 >                        t.result = reducer.applyAsInt(t.result, s.result);
6160                          s = t.rights = s.nextRight;
6161                      }
6162                  }
# Line 6304 | Line 6164 | public class ConcurrentHashMap<K, V>
6164          }
6165      }
6166  
6167 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6168 <        extends Traverser<K,V,Integer> {
6169 <        final ObjectToInt<? super V> transformer;
6170 <        final IntByIntToInt reducer;
6167 >    @SuppressWarnings("serial")
6168 >    static final class MapReduceValuesToIntTask<K,V>
6169 >        extends BulkTask<K,V,Integer> {
6170 >        final ToIntFunction<? super V> transformer;
6171 >        final IntBinaryOperator reducer;
6172          final int basis;
6173          int result;
6174          MapReduceValuesToIntTask<K,V> rights, nextRight;
6175          MapReduceValuesToIntTask
6176 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6176 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6177               MapReduceValuesToIntTask<K,V> nextRight,
6178 <             ObjectToInt<? super V> transformer,
6178 >             ToIntFunction<? super V> transformer,
6179               int basis,
6180 <             IntByIntToInt reducer) {
6181 <            super(m, p, b); this.nextRight = nextRight;
6180 >             IntBinaryOperator reducer) {
6181 >            super(p, b, i, f, t); this.nextRight = nextRight;
6182              this.transformer = transformer;
6183              this.basis = basis; this.reducer = reducer;
6184          }
6185          public final Integer getRawResult() { return result; }
6186 <        @SuppressWarnings("unchecked") public final void compute() {
6187 <            final ObjectToInt<? super V> transformer;
6188 <            final IntByIntToInt reducer;
6186 >        public final void compute() {
6187 >            final ToIntFunction<? super V> transformer;
6188 >            final IntBinaryOperator reducer;
6189              if ((transformer = this.transformer) != null &&
6190                  (reducer = this.reducer) != null) {
6191                  int r = this.basis;
6192 <                for (int b; (b = preSplit()) > 0;)
6192 >                for (int i = baseIndex, f, h; batch > 0 &&
6193 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6194 >                    addToPendingCount(1);
6195                      (rights = new MapReduceValuesToIntTask<K,V>
6196 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6197 <                Object v;
6198 <                while ((v = advance()) != null)
6199 <                    r = reducer.apply(r, transformer.apply((V)v));
6196 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6197 >                      rights, transformer, r, reducer)).fork();
6198 >                }
6199 >                for (Node<K,V> p; (p = advance()) != null; )
6200 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
6201                  result = r;
6202                  CountedCompleter<?> c;
6203                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6204 +                    @SuppressWarnings("unchecked")
6205                      MapReduceValuesToIntTask<K,V>
6206                          t = (MapReduceValuesToIntTask<K,V>)c,
6207                          s = t.rights;
6208                      while (s != null) {
6209 <                        t.result = reducer.apply(t.result, s.result);
6209 >                        t.result = reducer.applyAsInt(t.result, s.result);
6210                          s = t.rights = s.nextRight;
6211                      }
6212                  }
# Line 6349 | Line 6214 | public class ConcurrentHashMap<K, V>
6214          }
6215      }
6216  
6217 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6218 <        extends Traverser<K,V,Integer> {
6219 <        final ObjectToInt<Map.Entry<K,V>> transformer;
6220 <        final IntByIntToInt reducer;
6217 >    @SuppressWarnings("serial")
6218 >    static final class MapReduceEntriesToIntTask<K,V>
6219 >        extends BulkTask<K,V,Integer> {
6220 >        final ToIntFunction<Map.Entry<K,V>> transformer;
6221 >        final IntBinaryOperator reducer;
6222          final int basis;
6223          int result;
6224          MapReduceEntriesToIntTask<K,V> rights, nextRight;
6225          MapReduceEntriesToIntTask
6226 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6226 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6227               MapReduceEntriesToIntTask<K,V> nextRight,
6228 <             ObjectToInt<Map.Entry<K,V>> transformer,
6228 >             ToIntFunction<Map.Entry<K,V>> transformer,
6229               int basis,
6230 <             IntByIntToInt reducer) {
6231 <            super(m, p, b); this.nextRight = nextRight;
6230 >             IntBinaryOperator reducer) {
6231 >            super(p, b, i, f, t); this.nextRight = nextRight;
6232              this.transformer = transformer;
6233              this.basis = basis; this.reducer = reducer;
6234          }
6235          public final Integer getRawResult() { return result; }
6236 <        @SuppressWarnings("unchecked") public final void compute() {
6237 <            final ObjectToInt<Map.Entry<K,V>> transformer;
6238 <            final IntByIntToInt reducer;
6236 >        public final void compute() {
6237 >            final ToIntFunction<Map.Entry<K,V>> transformer;
6238 >            final IntBinaryOperator reducer;
6239              if ((transformer = this.transformer) != null &&
6240                  (reducer = this.reducer) != null) {
6241                  int r = this.basis;
6242 <                for (int b; (b = preSplit()) > 0;)
6242 >                for (int i = baseIndex, f, h; batch > 0 &&
6243 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6244 >                    addToPendingCount(1);
6245                      (rights = new MapReduceEntriesToIntTask<K,V>
6246 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6247 <                Object v;
6248 <                while ((v = advance()) != null)
6249 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6250 <                                                                    (V)v)));
6246 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6247 >                      rights, transformer, r, reducer)).fork();
6248 >                }
6249 >                for (Node<K,V> p; (p = advance()) != null; )
6250 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
6251                  result = r;
6252                  CountedCompleter<?> c;
6253                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6254 +                    @SuppressWarnings("unchecked")
6255                      MapReduceEntriesToIntTask<K,V>
6256                          t = (MapReduceEntriesToIntTask<K,V>)c,
6257                          s = t.rights;
6258                      while (s != null) {
6259 <                        t.result = reducer.apply(t.result, s.result);
6259 >                        t.result = reducer.applyAsInt(t.result, s.result);
6260                          s = t.rights = s.nextRight;
6261                      }
6262                  }
# Line 6395 | Line 6264 | public class ConcurrentHashMap<K, V>
6264          }
6265      }
6266  
6267 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6268 <        extends Traverser<K,V,Integer> {
6269 <        final ObjectByObjectToInt<? super K, ? super V> transformer;
6270 <        final IntByIntToInt reducer;
6267 >    @SuppressWarnings("serial")
6268 >    static final class MapReduceMappingsToIntTask<K,V>
6269 >        extends BulkTask<K,V,Integer> {
6270 >        final ToIntBiFunction<? super K, ? super V> transformer;
6271 >        final IntBinaryOperator reducer;
6272          final int basis;
6273          int result;
6274          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6275          MapReduceMappingsToIntTask
6276 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6276 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6277               MapReduceMappingsToIntTask<K,V> nextRight,
6278 <             ObjectByObjectToInt<? super K, ? super V> transformer,
6278 >             ToIntBiFunction<? super K, ? super V> transformer,
6279               int basis,
6280 <             IntByIntToInt reducer) {
6281 <            super(m, p, b); this.nextRight = nextRight;
6280 >             IntBinaryOperator reducer) {
6281 >            super(p, b, i, f, t); this.nextRight = nextRight;
6282              this.transformer = transformer;
6283              this.basis = basis; this.reducer = reducer;
6284          }
6285          public final Integer getRawResult() { return result; }
6286 <        @SuppressWarnings("unchecked") public final void compute() {
6287 <            final ObjectByObjectToInt<? super K, ? super V> transformer;
6288 <            final IntByIntToInt reducer;
6286 >        public final void compute() {
6287 >            final ToIntBiFunction<? super K, ? super V> transformer;
6288 >            final IntBinaryOperator reducer;
6289              if ((transformer = this.transformer) != null &&
6290                  (reducer = this.reducer) != null) {
6291                  int r = this.basis;
6292 <                for (int b; (b = preSplit()) > 0;)
6292 >                for (int i = baseIndex, f, h; batch > 0 &&
6293 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6294 >                    addToPendingCount(1);
6295                      (rights = new MapReduceMappingsToIntTask<K,V>
6296 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6297 <                Object v;
6298 <                while ((v = advance()) != null)
6299 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6296 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6297 >                      rights, transformer, r, reducer)).fork();
6298 >                }
6299 >                for (Node<K,V> p; (p = advance()) != null; )
6300 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6301                  result = r;
6302                  CountedCompleter<?> c;
6303                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6304 +                    @SuppressWarnings("unchecked")
6305                      MapReduceMappingsToIntTask<K,V>
6306                          t = (MapReduceMappingsToIntTask<K,V>)c,
6307                          s = t.rights;
6308                      while (s != null) {
6309 <                        t.result = reducer.apply(t.result, s.result);
6309 >                        t.result = reducer.applyAsInt(t.result, s.result);
6310                          s = t.rights = s.nextRight;
6311                      }
6312                  }
# Line 6441 | Line 6315 | public class ConcurrentHashMap<K, V>
6315      }
6316  
6317      // Unsafe mechanics
6318 <    private static final sun.misc.Unsafe U;
6318 >    private static final Unsafe U = Unsafe.getUnsafe();
6319      private static final long SIZECTL;
6320      private static final long TRANSFERINDEX;
6447    private static final long TRANSFERORIGIN;
6321      private static final long BASECOUNT;
6322 <    private static final long COUNTERBUSY;
6322 >    private static final long CELLSBUSY;
6323      private static final long CELLVALUE;
6324 <    private static final long ABASE;
6324 >    private static final int ABASE;
6325      private static final int ASHIFT;
6326  
6327      static {
6328 <        int ss;
6329 <        try {
6330 <            U = sun.misc.Unsafe.getUnsafe();
6331 <            Class<?> k = ConcurrentHashMap.class;
6332 <            SIZECTL = U.objectFieldOffset
6333 <                (k.getDeclaredField("sizeCtl"));
6334 <            TRANSFERINDEX = U.objectFieldOffset
6335 <                (k.getDeclaredField("transferIndex"));
6336 <            TRANSFERORIGIN = U.objectFieldOffset
6337 <                (k.getDeclaredField("transferOrigin"));
6338 <            BASECOUNT = U.objectFieldOffset
6339 <                (k.getDeclaredField("baseCount"));
6340 <            COUNTERBUSY = U.objectFieldOffset
6341 <                (k.getDeclaredField("counterBusy"));
6342 <            Class<?> ck = CounterCell.class;
6343 <            CELLVALUE = U.objectFieldOffset
6344 <                (ck.getDeclaredField("value"));
6345 <            Class<?> sc = Node[].class;
6346 <            ABASE = U.arrayBaseOffset(sc);
6347 <            ss = U.arrayIndexScale(sc);
6348 <            ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6349 <        } catch (Exception e) {
6350 <            throw new Error(e);
6351 <        }
6479 <        if ((ss & (ss-1)) != 0)
6480 <            throw new Error("data type scale not a power of two");
6328 >        SIZECTL = U.objectFieldOffset
6329 >            (ConcurrentHashMap.class, "sizeCtl");
6330 >        TRANSFERINDEX = U.objectFieldOffset
6331 >            (ConcurrentHashMap.class, "transferIndex");
6332 >        BASECOUNT = U.objectFieldOffset
6333 >            (ConcurrentHashMap.class, "baseCount");
6334 >        CELLSBUSY = U.objectFieldOffset
6335 >            (ConcurrentHashMap.class, "cellsBusy");
6336 >
6337 >        CELLVALUE = U.objectFieldOffset
6338 >            (CounterCell.class, "value");
6339 >
6340 >        ABASE = U.arrayBaseOffset(Node[].class);
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