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.143 by jsr166, Fri Nov 9 03:30:03 2012 UTC vs.
Revision 1.217 by dl, Wed May 29 14:38:26 2013 UTC

# Line 5 | Line 5
5   */
6  
7   package java.util.concurrent;
8 < import java.util.concurrent.atomic.LongAdder;
9 < import java.util.concurrent.ForkJoinPool;
10 < import java.util.concurrent.ForkJoinTask;
11 <
12 < import java.util.Comparator;
8 > import java.io.Serializable;
9 > import java.io.ObjectStreamField;
10 > import java.lang.reflect.ParameterizedType;
11 > import java.lang.reflect.Type;
12   import java.util.Arrays;
14 import java.util.Map;
15 import java.util.Set;
13   import java.util.Collection;
14 < import java.util.AbstractMap;
15 < import java.util.AbstractSet;
16 < import java.util.AbstractCollection;
20 < import java.util.Hashtable;
14 > import java.util.Comparator;
15 > import java.util.ConcurrentModificationException;
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;
24 < import java.util.ConcurrentModificationException;
20 > import java.util.Map;
21   import java.util.NoSuchElementException;
22 + import java.util.Set;
23 + import java.util.Spliterator;
24   import java.util.concurrent.ConcurrentMap;
25 < import java.util.concurrent.ThreadLocalRandom;
28 < import java.util.concurrent.locks.LockSupport;
29 < import java.util.concurrent.locks.AbstractQueuedSynchronizer;
25 > import java.util.concurrent.ForkJoinPool;
26   import java.util.concurrent.atomic.AtomicReference;
27 <
28 < import java.io.Serializable;
27 > import java.util.concurrent.locks.ReentrantLock;
28 > import java.util.concurrent.locks.StampedLock;
29 > import java.util.function.BiConsumer;
30 > import java.util.function.BiFunction;
31 > import java.util.function.BinaryOperator;
32 > import java.util.function.Consumer;
33 > import java.util.function.DoubleBinaryOperator;
34 > import java.util.function.Function;
35 > import java.util.function.IntBinaryOperator;
36 > import java.util.function.LongBinaryOperator;
37 > import java.util.function.ToDoubleBiFunction;
38 > import java.util.function.ToDoubleFunction;
39 > import java.util.function.ToIntBiFunction;
40 > import java.util.function.ToIntFunction;
41 > import java.util.function.ToLongBiFunction;
42 > import java.util.function.ToLongFunction;
43 > import java.util.stream.Stream;
44  
45   /**
46   * A hash table supporting full concurrency of retrievals and
# Line 43 | Line 54 | import java.io.Serializable;
54   * interoperable with {@code Hashtable} in programs that rely on its
55   * thread safety but not on its synchronization details.
56   *
57 < * <p> Retrieval operations (including {@code get}) generally do not
57 > * <p>Retrieval operations (including {@code get}) generally do not
58   * block, so may overlap with update operations (including {@code put}
59   * and {@code remove}). Retrievals reflect the results of the most
60   * recently <em>completed</em> update operations holding upon their
# Line 64 | Line 75 | import java.io.Serializable;
75   * that may be adequate for monitoring or estimation purposes, but not
76   * for program control.
77   *
78 < * <p> The table is dynamically expanded when there are too many
78 > * <p>The table is dynamically expanded when there are too many
79   * collisions (i.e., keys that have distinct hash codes but fall into
80   * the same slot modulo the table size), with the expected average
81   * effect of maintaining roughly two bins per mapping (corresponding
# Line 83 | Line 94 | import java.io.Serializable;
94   * expected {@code concurrencyLevel} as an additional hint for
95   * internal sizing.  Note that using many keys with exactly the same
96   * {@code hashCode()} is a sure way to slow down performance of any
97 < * hash table.
97 > * hash table. To ameliorate impact, when keys are {@link Comparable},
98 > * this class may use comparison order among keys to help break ties.
99   *
100 < * <p> A {@link Set} projection of a ConcurrentHashMap may be created
100 > * <p>A {@link Set} projection of a ConcurrentHashMap may be created
101   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
102   * (using {@link #keySet(Object)} when only keys are of interest, and the
103   * mapped values are (perhaps transiently) not used or all take the
104   * same mapping value.
105   *
106 < * <p> A ConcurrentHashMap can be used as scalable frequency map (a
107 < * form of histogram or multiset) by using {@link LongAdder} values
108 < * and initializing via {@link #computeIfAbsent}. For example, to add
109 < * a count to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you
110 < * can use {@code freqs.computeIfAbsent(k -> new
111 < * LongAdder()).increment();}
106 > * <p>A ConcurrentHashMap can be used as scalable frequency map (a
107 > * form of histogram or multiset) by using {@link
108 > * java.util.concurrent.atomic.LongAdder} values and initializing via
109 > * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count
110 > * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
111 > * {@code freqs.computeIfAbsent(k -> new LongAdder()).increment();}
112   *
113   * <p>This class and its views and iterators implement all of the
114   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
115   * interfaces.
116   *
117 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
117 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
118   * does <em>not</em> allow {@code null} to be used as a key or value.
119   *
120 < * <p>ConcurrentHashMaps support parallel operations using the {@link
121 < * ForkJoinPool#commonPool}. (Tasks that may be used in other contexts
122 < * are available in class {@link ForkJoinTasks}). These operations are
123 < * designed to be safely, and often sensibly, applied even with maps
124 < * that are being concurrently updated by other threads; for example,
125 < * when computing a snapshot summary of the values in a shared
126 < * registry.  There are three kinds of operation, each with four
127 < * forms, accepting functions with Keys, Values, Entries, and (Key,
128 < * Value) arguments and/or return values. (The first three forms are
129 < * also available via the {@link #keySet()}, {@link #values()} and
130 < * {@link #entrySet()} views). Because the elements of a
131 < * ConcurrentHashMap are not ordered in any particular way, and may be
132 < * processed in different orders in different parallel executions, the
133 < * correctness of supplied functions should not depend on any
134 < * ordering, or on any other objects or values that may transiently
123 < * change while computation is in progress; and except for forEach
124 < * actions, should ideally be side-effect-free.
120 > * <p>ConcurrentHashMaps support a set of sequential and parallel bulk
121 > * operations that, unlike most {@link Stream} methods, are designed
122 > * to be safely, and often sensibly, applied even with maps that are
123 > * being concurrently updated by other threads; for example, when
124 > * computing a snapshot summary of the values in a shared registry.
125 > * There are three kinds of operation, each with four forms, accepting
126 > * functions with Keys, Values, Entries, and (Key, Value) arguments
127 > * and/or return values. Because the elements of a ConcurrentHashMap
128 > * are not ordered in any particular way, and may be processed in
129 > * different orders in different parallel executions, the correctness
130 > * of supplied functions should not depend on any ordering, or on any
131 > * other objects or values that may transiently change while
132 > * computation is in progress; and except for forEach actions, should
133 > * ideally be side-effect-free. Bulk operations on {@link Map.Entry}
134 > * objects do not support method {@code setValue}.
135   *
136   * <ul>
137   * <li> forEach: Perform a given action on each element.
# Line 148 | Line 158 | import java.io.Serializable;
158   * <li> Reductions to scalar doubles, longs, and ints, using a
159   * given basis value.</li>
160   *
151 * </li>
161   * </ul>
162 + * </li>
163   * </ul>
164   *
165 + * <p>These bulk operations accept a {@code parallelismThreshold}
166 + * argument. Methods proceed sequentially if the current map size is
167 + * estimated to be less than the given threshold. Using a value of
168 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
169 + * of {@code 1} results in maximal parallelism by partitioning into
170 + * enough subtasks to utilize all processors. Normally, you would
171 + * initially choose one of these extreme values, and then measure
172 + * performance of using in-between values that trade off overhead
173 + * versus throughput. Parallel forms use the {@link
174 + * ForkJoinPool#commonPool()}.
175 + *
176   * <p>The concurrency properties of bulk operations follow
177   * from those of ConcurrentHashMap: Any non-null result returned
178   * from {@code get(key)} and related access methods bears a
# Line 187 | Line 208 | import java.io.Serializable;
208   * arguments can be supplied using {@code new
209   * AbstractMap.SimpleEntry(k,v)}.
210   *
211 < * <p> Bulk operations may complete abruptly, throwing an
211 > * <p>Bulk operations may complete abruptly, throwing an
212   * exception encountered in the application of a supplied
213   * function. Bear in mind when handling such exceptions that other
214   * concurrently executing functions could also have thrown
215   * exceptions, or would have done so if the first exception had
216   * not occurred.
217   *
218 < * <p>Parallel speedups for bulk operations compared to sequential
219 < * processing are common but not guaranteed.  Operations involving
220 < * brief functions on small maps may execute more slowly than
221 < * sequential loops if the underlying work to parallelize the
222 < * computation is more expensive than the computation itself.
223 < * Similarly, parallelization may not lead to much actual parallelism
224 < * if all processors are busy performing unrelated tasks.
204 < *
205 < * <p> All arguments to all task methods must be non-null.
218 > * <p>Speedups for parallel compared to sequential forms are common
219 > * but not guaranteed.  Parallel operations involving brief functions
220 > * on small maps may execute more slowly than sequential forms if the
221 > * underlying work to parallelize the computation is more expensive
222 > * than the computation itself.  Similarly, parallelization may not
223 > * lead to much actual parallelism if all processors are busy
224 > * performing unrelated tasks.
225   *
226 < * <p><em>jsr166e note: During transition, this class
208 < * uses nested functional interfaces with different names but the
209 < * same forms as those expected for JDK8.<em>
226 > * <p>All arguments to all task methods must be non-null.
227   *
228   * <p>This class is a member of the
229   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
# Line 217 | Line 234 | import java.io.Serializable;
234   * @param <K> the type of keys maintained by this map
235   * @param <V> the type of mapped values
236   */
237 < public class ConcurrentHashMap<K, V>
238 <    implements ConcurrentMap<K, V>, Serializable {
237 > @SuppressWarnings({"unchecked", "rawtypes", "serial"})
238 > public class ConcurrentHashMap<K,V> implements ConcurrentMap<K,V>, Serializable {
239      private static final long serialVersionUID = 7249069246763182397L;
240  
224    /**
225     * A partitionable iterator. A Spliterator can be traversed
226     * directly, but can also be partitioned (before traversal) by
227     * creating another Spliterator that covers a non-overlapping
228     * portion of the elements, and so may be amenable to parallel
229     * execution.
230     *
231     * <p> This interface exports a subset of expected JDK8
232     * functionality.
233     *
234     * <p>Sample usage: Here is one (of the several) ways to compute
235     * the sum of the values held in a map using the ForkJoin
236     * framework. As illustrated here, Spliterators are well suited to
237     * designs in which a task repeatedly splits off half its work
238     * into forked subtasks until small enough to process directly,
239     * and then joins these subtasks. Variants of this style can also
240     * be used in completion-based designs.
241     *
242     * <pre>
243     * {@code ConcurrentHashMap<String, Long> m = ...
244     * // split as if have 8 * parallelism, for load balance
245     * int n = m.size();
246     * int p = aForkJoinPool.getParallelism() * 8;
247     * int split = (n < p)? n : p;
248     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
249     * // ...
250     * static class SumValues extends RecursiveTask<Long> {
251     *   final Spliterator<Long> s;
252     *   final int split;             // split while > 1
253     *   final SumValues nextJoin;    // records forked subtasks to join
254     *   SumValues(Spliterator<Long> s, int depth, SumValues nextJoin) {
255     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
256     *   }
257     *   public Long compute() {
258     *     long sum = 0;
259     *     SumValues subtasks = null; // fork subtasks
260     *     for (int s = split >>> 1; s > 0; s >>>= 1)
261     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
262     *     while (s.hasNext())        // directly process remaining elements
263     *       sum += s.next();
264     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
265     *       sum += t.join();         // collect subtask results
266     *     return sum;
267     *   }
268     * }
269     * }</pre>
270     */
271    public static interface Spliterator<T> extends Iterator<T> {
272        /**
273         * Returns a Spliterator covering approximately half of the
274         * elements, guaranteed not to overlap with those subsequently
275         * returned by this Spliterator.  After invoking this method,
276         * the current Spliterator will <em>not</em> produce any of
277         * the elements of the returned Spliterator, but the two
278         * Spliterators together will produce all of the elements that
279         * would have been produced by this Spliterator had this
280         * method not been called. The exact number of elements
281         * produced by the returned Spliterator is not guaranteed, and
282         * may be zero (i.e., with {@code hasNext()} reporting {@code
283         * false}) if this Spliterator cannot be further split.
284         *
285         * @return a Spliterator covering approximately half of the
286         * elements
287         * @throws IllegalStateException if this Spliterator has
288         * already commenced traversing elements
289         */
290        Spliterator<T> split();
291    }
292
293
241      /*
242       * Overview:
243       *
# Line 301 | Line 248 | public class ConcurrentHashMap<K, V>
248       * the same or better than java.util.HashMap, and to support high
249       * initial insertion rates on an empty table by many threads.
250       *
251 <     * Each key-value mapping is held in a Node.  Because Node fields
252 <     * can contain special values, they are defined using plain Object
253 <     * types. Similarly in turn, all internal methods that use them
254 <     * work off Object types. And similarly, so do the internal
255 <     * methods of auxiliary iterator and view classes.  All public
256 <     * generic typed methods relay in/out of these internal methods,
257 <     * supplying null-checks and casts as needed. This also allows
258 <     * many of the public methods to be factored into a smaller number
259 <     * of internal methods (although sadly not so for the five
260 <     * variants of put-related operations). The validation-based
314 <     * approach explained below leads to a lot of code sprawl because
315 <     * retry-control precludes factoring into smaller methods.
251 >     * Each key-value mapping is held in a Node.  Because Node key
252 >     * fields can contain special values, they are defined using plain
253 >     * Object types (not type "K"). This leads to a lot of explicit
254 >     * casting (and the use of class-wide warning suppressions).  It
255 >     * also allows some of the public methods to be factored into a
256 >     * smaller number of internal methods (although sadly not so for
257 >     * the five variants of put-related operations). The
258 >     * validation-based approach explained below leads to a lot of
259 >     * code sprawl because retry-control precludes factoring into
260 >     * smaller methods.
261       *
262       * The table is lazily initialized to a power-of-two size upon the
263       * first insertion.  Each bin in the table normally contains a
# Line 320 | Line 265 | public class ConcurrentHashMap<K, V>
265       * Table accesses require volatile/atomic reads, writes, and
266       * CASes.  Because there is no other way to arrange this without
267       * adding further indirections, we use intrinsics
268 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
269 <     * are always accurately traversable under volatile reads, so long
270 <     * as lookups check hash code and non-nullness of value before
271 <     * checking key equality.
272 <     *
273 <     * We use the top two bits of Node hash fields for control
274 <     * purposes -- they are available anyway because of addressing
275 <     * constraints.  As explained further below, these top bits are
331 <     * used as follows:
332 <     *  00 - Normal
333 <     *  01 - Locked
334 <     *  11 - Locked and may have a thread waiting for lock
335 <     *  10 - Node is a forwarding node
336 <     *
337 <     * The lower 30 bits of each Node's hash field contain a
338 <     * transformation of the key's hash code, except for forwarding
339 <     * nodes, for which the lower bits are zero (and so always have
340 <     * hash field == MOVED).
268 >     * (sun.misc.Unsafe) operations.
269 >     *
270 >     * We use the top (sign) bit of Node hash fields for control
271 >     * purposes -- it is available anyway because of addressing
272 >     * constraints.  Nodes with negative hash fields are forwarding
273 >     * nodes to either TreeBins or resized tables.  The lower 31 bits
274 >     * of each normal Node's hash field contain a transformation of
275 >     * the key's hash code.
276       *
277       * Insertion (via put or its variants) of the first node in an
278       * empty bin is performed by just CASing it to the bin.  This is
# Line 346 | Line 281 | public class ConcurrentHashMap<K, V>
281       * delete, and replace) require locks.  We do not want to waste
282       * the space required to associate a distinct lock object with
283       * each bin, so instead use the first node of a bin list itself as
284 <     * a lock. Blocking support for these locks relies on the builtin
285 <     * "synchronized" monitors.  However, we also need a tryLock
351 <     * construction, so we overlay these by using bits of the Node
352 <     * hash field for lock control (see above), and so normally use
353 <     * builtin monitors only for blocking and signalling using
354 <     * wait/notifyAll constructions. See Node.tryAwaitLock.
284 >     * a lock. Locking support for these locks relies on builtin
285 >     * "synchronized" monitors.
286       *
287       * Using the first node of a list as a lock does not by itself
288       * suffice though: When a node is locked, any update must first
289       * validate that it is still the first node after locking it, and
290       * retry if not. Because new nodes are always appended to lists,
291       * once a node is first in a bin, it remains first until deleted
292 <     * or the bin becomes invalidated (upon resizing).  However,
362 <     * operations that only conditionally update may inspect nodes
363 <     * until the point of update. This is a converse of sorts to the
364 <     * lazy locking technique described by Herlihy & Shavit.
292 >     * or the bin becomes invalidated (upon resizing).
293       *
294       * The main disadvantage of per-bin locks is that other update
295       * operations on other nodes in a bin list protected by the same
# Line 402 | Line 330 | public class ConcurrentHashMap<K, V>
330       * a threshold, and at least one of the keys implements
331       * Comparable.  These TreeBins use a balanced tree to hold nodes
332       * (a specialized form of red-black trees), bounding search time
333 <     * to O(log N).  Each search step in a TreeBin is around twice as
333 >     * to O(log N).  Each search step in a TreeBin is at least twice as
334       * slow as in a regular list, but given that N cannot exceed
335       * (1<<64) (before running out of addresses) this bounds search
336       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 413 | Line 341 | public class ConcurrentHashMap<K, V>
341       * iterators in the same way.
342       *
343       * The table is resized when occupancy exceeds a percentage
344 <     * threshold (nominally, 0.75, but see below).  Only a single
345 <     * thread performs the resize (using field "sizeCtl", to arrange
346 <     * exclusion), but the table otherwise remains usable for reads
347 <     * and updates. Resizing proceeds by transferring bins, one by
348 <     * one, from the table to the next table.  Because we are using
349 <     * power-of-two expansion, the elements from each bin must either
350 <     * stay at same index, or move with a power of two offset. We
351 <     * eliminate unnecessary node creation by catching cases where old
352 <     * nodes can be reused because their next fields won't change.  On
353 <     * average, only about one-sixth of them need cloning when a table
354 <     * doubles. The nodes they replace will be garbage collectable as
355 <     * soon as they are no longer referenced by any reader thread that
356 <     * may be in the midst of concurrently traversing table.  Upon
357 <     * transfer, the old table bin contains only a special forwarding
358 <     * node (with hash field "MOVED") that contains the next table as
359 <     * its key. On encountering a forwarding node, access and update
360 <     * operations restart, using the new table.
361 <     *
362 <     * Each bin transfer requires its bin lock. However, unlike other
363 <     * cases, a transfer can skip a bin if it fails to acquire its
364 <     * lock, and revisit it later (unless it is a TreeBin). Method
365 <     * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
366 <     * have been skipped because of failure to acquire a lock, and
367 <     * blocks only if none are available (i.e., only very rarely).
368 <     * The transfer operation must also ensure that all accessible
369 <     * bins in both the old and new table are usable by any traversal.
370 <     * When there are no lock acquisition failures, this is arranged
371 <     * simply by proceeding from the last bin (table.length - 1) up
372 <     * towards the first.  Upon seeing a forwarding node, traversals
373 <     * (see class Iter) arrange to move to the new table
374 <     * without revisiting nodes.  However, when any node is skipped
375 <     * during a transfer, all earlier table bins may have become
376 <     * visible, so are initialized with a reverse-forwarding node back
377 <     * to the old table until the new ones are established. (This
378 <     * sometimes requires transiently locking a forwarding node, which
379 <     * is possible under the above encoding.) These more expensive
380 <     * mechanics trigger only when necessary.
344 >     * threshold (nominally, 0.75, but see below).  Any thread
345 >     * noticing an overfull bin may assist in resizing after the
346 >     * initiating thread allocates and sets up the replacement
347 >     * array. However, rather than stalling, these other threads may
348 >     * proceed with insertions etc.  The use of TreeBins shields us
349 >     * from the worst case effects of overfilling while resizes are in
350 >     * progress.  Resizing proceeds by transferring bins, one by one,
351 >     * from the table to the next table. To enable concurrency, the
352 >     * next table must be (incrementally) prefilled with place-holders
353 >     * serving as reverse forwarders to the old table.  Because we are
354 >     * using power-of-two expansion, the elements from each bin must
355 >     * either stay at same index, or move with a power of two
356 >     * offset. We eliminate unnecessary node creation by catching
357 >     * cases where old nodes can be reused because their next fields
358 >     * won't change.  On average, only about one-sixth of them need
359 >     * cloning when a table doubles. The nodes they replace will be
360 >     * garbage collectable as soon as they are no longer referenced by
361 >     * any reader thread that may be in the midst of concurrently
362 >     * traversing table.  Upon transfer, the old table bin contains
363 >     * only a special forwarding node (with hash field "MOVED") that
364 >     * contains the next table as its key. On encountering a
365 >     * forwarding node, access and update operations restart, using
366 >     * the new table.
367 >     *
368 >     * Each bin transfer requires its bin lock, which can stall
369 >     * waiting for locks while resizing. However, because other
370 >     * threads can join in and help resize rather than contend for
371 >     * locks, average aggregate waits become shorter as resizing
372 >     * progresses.  The transfer operation must also ensure that all
373 >     * accessible bins in both the old and new table are usable by any
374 >     * traversal.  This is arranged by proceeding from the last bin
375 >     * (table.length - 1) up towards the first.  Upon seeing a
376 >     * forwarding node, traversals (see class Traverser) arrange to
377 >     * move to the new table without revisiting nodes.  However, to
378 >     * ensure that no intervening nodes are skipped, bin splitting can
379 >     * only begin after the associated reverse-forwarders are in
380 >     * place.
381       *
382       * The traversal scheme also applies to partial traversals of
383       * ranges of bins (via an alternate Traverser constructor)
# Line 464 | Line 392 | public class ConcurrentHashMap<K, V>
392       * These cases attempt to override the initial capacity settings,
393       * but harmlessly fail to take effect in cases of races.
394       *
395 <     * The element count is maintained using a LongAdder, which avoids
396 <     * contention on updates but can encounter cache thrashing if read
397 <     * too frequently during concurrent access. To avoid reading so
398 <     * often, resizing is attempted either when a bin lock is
399 <     * contended, or upon adding to a bin already holding two or more
400 <     * nodes (checked before adding in the xIfAbsent methods, after
401 <     * adding in others). Under uniform hash distributions, the
402 <     * probability of this occurring at threshold is around 13%,
403 <     * meaning that only about 1 in 8 puts check threshold (and after
404 <     * resizing, many fewer do so). But this approximation has high
405 <     * variance for small table sizes, so we check on any collision
406 <     * for sizes <= 64. The bulk putAll operation further reduces
407 <     * contention by only committing count updates upon these size
408 <     * checks.
395 >     * The element count is maintained using a specialization of
396 >     * LongAdder. We need to incorporate a specialization rather than
397 >     * just use a LongAdder in order to access implicit
398 >     * contention-sensing that leads to creation of multiple
399 >     * Cells.  The counter mechanics avoid contention on
400 >     * updates but can encounter cache thrashing if read too
401 >     * frequently during concurrent access. To avoid reading so often,
402 >     * resizing under contention is attempted only upon adding to a
403 >     * bin already holding two or more nodes. Under uniform hash
404 >     * distributions, the probability of this occurring at threshold
405 >     * is around 13%, meaning that only about 1 in 8 puts check
406 >     * threshold (and after resizing, many fewer do so). The bulk
407 >     * putAll operation further reduces contention by only committing
408 >     * count updates upon these size checks.
409       *
410       * Maintaining API and serialization compatibility with previous
411       * versions of this class introduces several oddities. Mainly: We
# Line 528 | Line 456 | public class ConcurrentHashMap<K, V>
456      private static final float LOAD_FACTOR = 0.75f;
457  
458      /**
531     * The buffer size for skipped bins during transfers. The
532     * value is arbitrary but should be large enough to avoid
533     * most locking stalls during resizes.
534     */
535    private static final int TRANSFER_BUFFER_SIZE = 32;
536
537    /**
459       * The bin count threshold for using a tree rather than list for a
460       * bin.  The value reflects the approximate break-even point for
461       * using tree-based operations.
462       */
463      private static final int TREE_THRESHOLD = 8;
464  
465 +    /**
466 +     * Minimum number of rebinnings per transfer step. Ranges are
467 +     * subdivided to allow multiple resizer threads.  This value
468 +     * serves as a lower bound to avoid resizers encountering
469 +     * excessive memory contention.  The value should be at least
470 +     * DEFAULT_CAPACITY.
471 +     */
472 +    private static final int MIN_TRANSFER_STRIDE = 16;
473 +
474      /*
475 <     * Encodings for special uses of Node hash fields. See above for
546 <     * explanation.
475 >     * Encodings for Node hash fields. See above for explanation.
476       */
477      static final int MOVED     = 0x80000000; // hash field for forwarding nodes
478 <    static final int LOCKED    = 0x40000000; // set/tested only as a bit
479 <    static final int WAITING   = 0xc0000000; // both bits set/tested together
480 <    static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
478 >    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
479 >
480 >    /** Number of CPUS, to place bounds on some sizings */
481 >    static final int NCPU = Runtime.getRuntime().availableProcessors();
482 >
483 >    /** For serialization compatibility. */
484 >    private static final ObjectStreamField[] serialPersistentFields = {
485 >        new ObjectStreamField("segments", Segment[].class),
486 >        new ObjectStreamField("segmentMask", Integer.TYPE),
487 >        new ObjectStreamField("segmentShift", Integer.TYPE)
488 >    };
489 >
490 >    /**
491 >     * A padded cell for distributing counts.  Adapted from LongAdder
492 >     * and Striped64.  See their internal docs for explanation.
493 >     */
494 >    @sun.misc.Contended static final class Cell {
495 >        volatile long value;
496 >        Cell(long x) { value = x; }
497 >    }
498  
499      /* ---------------- Fields -------------- */
500  
# Line 556 | Line 502 | public class ConcurrentHashMap<K, V>
502       * The array of bins. Lazily initialized upon first insertion.
503       * Size is always a power of two. Accessed directly by iterators.
504       */
505 <    transient volatile Node[] table;
505 >    transient volatile Node<K,V>[] table;
506  
507      /**
508 <     * The counter maintaining number of elements.
508 >     * The next table to use; non-null only while resizing.
509       */
510 <    private transient final LongAdder counter;
510 >    private transient volatile Node<K,V>[] nextTable;
511 >
512 >    /**
513 >     * Base counter value, used mainly when there is no contention,
514 >     * but also as a fallback during table initialization
515 >     * races. Updated via CAS.
516 >     */
517 >    private transient volatile long baseCount;
518  
519      /**
520       * Table initialization and resizing control.  When negative, the
521 <     * table is being initialized or resized. Otherwise, when table is
522 <     * null, holds the initial table size to use upon creation, or 0
523 <     * for default. After initialization, holds the next element count
524 <     * value upon which to resize the table.
521 >     * table is being initialized or resized: -1 for initialization,
522 >     * else -(1 + the number of active resizing threads).  Otherwise,
523 >     * when table is null, holds the initial table size to use upon
524 >     * creation, or 0 for default. After initialization, holds the
525 >     * next element count value upon which to resize the table.
526       */
527      private transient volatile int sizeCtl;
528  
529 +    /**
530 +     * The next table index (plus one) to split while resizing.
531 +     */
532 +    private transient volatile int transferIndex;
533 +
534 +    /**
535 +     * The least available table index to split while resizing.
536 +     */
537 +    private transient volatile int transferOrigin;
538 +
539 +    /**
540 +     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
541 +     */
542 +    private transient volatile int cellsBusy;
543 +
544 +    /**
545 +     * Table of counter cells. When non-null, size is a power of 2.
546 +     */
547 +    private transient volatile Cell[] counterCells;
548 +
549      // views
550      private transient KeySetView<K,V> keySet;
551      private transient ValuesView<K,V> values;
552      private transient EntrySetView<K,V> entrySet;
553  
580    /** For serialization compatibility. Null unless serialized; see below */
581    private Segment<K,V>[] segments;
582
554      /* ---------------- Table element access -------------- */
555  
556      /*
# Line 594 | Line 565 | public class ConcurrentHashMap<K, V>
565       * inline assignments below.
566       */
567  
568 <    static final Node tabAt(Node[] tab, int i) { // used by Iter
569 <        return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
568 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
569 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
570      }
571  
572 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
573 <        return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
572 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
573 >                                        Node<K,V> c, Node<K,V> v) {
574 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
575      }
576  
577 <    private static final void setTabAt(Node[] tab, int i, Node v) {
578 <        UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
577 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
578 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
579      }
580  
581      /* ---------------- Nodes -------------- */
582  
583      /**
584 <     * Key-value entry. Note that this is never exported out as a
585 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
586 <     * field of MOVED are special, and do not contain user keys or
587 <     * values.  Otherwise, keys are never null, and null val fields
588 <     * indicate that a node is in the process of being deleted or
589 <     * created. For purposes of read-only access, a key may be read
618 <     * before a val, but can only be used after checking val to be
619 <     * non-null.
584 >     * Key-value entry.  This class is never exported out as a
585 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
586 >     * MapEntry below), but can be used for read-only traversals used
587 >     * in bulk tasks.  Nodes with a hash field of MOVED are special,
588 >     * and do not contain user keys or values (and are never
589 >     * exported).  Otherwise, keys and vals are never null.
590       */
591 <    static class Node {
592 <        volatile int hash;
591 >    static class Node<K,V> implements Map.Entry<K,V> {
592 >        final int hash;
593          final Object key;
594 <        volatile Object val;
595 <        volatile Node next;
594 >        volatile V val;
595 >        Node<K,V> next;
596  
597 <        Node(int hash, Object key, Object val, Node next) {
597 >        Node(int hash, Object key, V val, Node<K,V> next) {
598              this.hash = hash;
599              this.key = key;
600              this.val = val;
601              this.next = next;
602          }
603  
604 <        /** CompareAndSet the hash field */
605 <        final boolean casHash(int cmp, int val) {
606 <            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
604 >        public final K getKey()       { return (K)key; }
605 >        public final V getValue()     { return val; }
606 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
607 >        public final String toString(){ return key + "=" + val; }
608 >        public final V setValue(V value) {
609 >            throw new UnsupportedOperationException();
610          }
611  
612 <        /** The number of spins before blocking for a lock */
613 <        static final int MAX_SPINS =
614 <            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
612 >        public final boolean equals(Object o) {
613 >            Object k, v, u; Map.Entry<?,?> e;
614 >            return ((o instanceof Map.Entry) &&
615 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
616 >                    (v = e.getValue()) != null &&
617 >                    (k == key || k.equals(key)) &&
618 >                    (v == (u = val) || v.equals(u)));
619 >        }
620 >    }
621  
622 <        /**
623 <         * Spins a while if LOCKED bit set and this node is the first
624 <         * of its bin, and then sets WAITING bits on hash field and
625 <         * blocks (once) if they are still set.  It is OK for this
626 <         * method to return even if lock is not available upon exit,
627 <         * which enables these simple single-wait mechanics.
628 <         *
629 <         * The corresponding signalling operation is performed within
630 <         * callers: Upon detecting that WAITING has been set when
631 <         * unlocking lock (via a failed CAS from non-waiting LOCKED
632 <         * state), unlockers acquire the sync lock and perform a
654 <         * notifyAll.
655 <         *
656 <         * The initial sanity check on tab and bounds is not currently
657 <         * necessary in the only usages of this method, but enables
658 <         * use in other future contexts.
659 <         */
660 <        final void tryAwaitLock(Node[] tab, int i) {
661 <            if (tab != null && i >= 0 && i < tab.length) { // sanity check
662 <                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
663 <                int spins = MAX_SPINS, h;
664 <                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
665 <                    if (spins >= 0) {
666 <                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
667 <                        if (r >= 0 && --spins == 0)
668 <                            Thread.yield();  // yield before block
669 <                    }
670 <                    else if (casHash(h, h | WAITING)) {
671 <                        synchronized (this) {
672 <                            if (tabAt(tab, i) == this &&
673 <                                (hash & WAITING) == WAITING) {
674 <                                try {
675 <                                    wait();
676 <                                } catch (InterruptedException ie) {
677 <                                    try {
678 <                                        Thread.currentThread().interrupt();
679 <                                    } catch (SecurityException ignore) {
680 <                                    }
681 <                                }
682 <                            }
683 <                            else
684 <                                notifyAll(); // possibly won race vs signaller
685 <                        }
686 <                        break;
687 <                    }
688 <                }
689 <            }
622 >    /**
623 >     * Exported Entry for EntryIterator
624 >     */
625 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
626 >        final K key; // non-null
627 >        V val;       // non-null
628 >        final ConcurrentHashMap<K,V> map;
629 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
630 >            this.key = key;
631 >            this.val = val;
632 >            this.map = map;
633          }
634 +        public K getKey()        { return key; }
635 +        public V getValue()      { return val; }
636 +        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
637 +        public String toString() { return key + "=" + val; }
638  
639 <        // Unsafe mechanics for casHash
640 <        private static final sun.misc.Unsafe UNSAFE;
641 <        private static final long hashOffset;
639 >        public boolean equals(Object o) {
640 >            Object k, v; Map.Entry<?,?> e;
641 >            return ((o instanceof Map.Entry) &&
642 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
643 >                    (v = e.getValue()) != null &&
644 >                    (k == key || k.equals(key)) &&
645 >                    (v == val || v.equals(val)));
646 >        }
647  
648 <        static {
649 <            try {
650 <                UNSAFE = sun.misc.Unsafe.getUnsafe();
651 <                Class<?> k = Node.class;
652 <                hashOffset = UNSAFE.objectFieldOffset
653 <                    (k.getDeclaredField("hash"));
654 <            } catch (Exception e) {
655 <                throw new Error(e);
656 <            }
648 >        /**
649 >         * Sets our entry's value and writes through to the map. The
650 >         * value to return is somewhat arbitrary here. Since we do not
651 >         * necessarily track asynchronous changes, the most recent
652 >         * "previous" value could be different from what we return (or
653 >         * could even have been removed, in which case the put will
654 >         * re-establish). We do not and cannot guarantee more.
655 >         */
656 >        public V setValue(V value) {
657 >            if (value == null) throw new NullPointerException();
658 >            V v = val;
659 >            val = value;
660 >            map.put(key, value);
661 >            return v;
662          }
663      }
664  
665 +
666      /* ---------------- TreeBins -------------- */
667  
668      /**
669       * Nodes for use in TreeBins
670       */
671 <    static final class TreeNode extends Node {
672 <        TreeNode parent;  // red-black tree links
673 <        TreeNode left;
674 <        TreeNode right;
675 <        TreeNode prev;    // needed to unlink next upon deletion
671 >    static final class TreeNode<K,V> extends Node<K,V> {
672 >        TreeNode<K,V> parent;  // red-black tree links
673 >        TreeNode<K,V> left;
674 >        TreeNode<K,V> right;
675 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
676          boolean red;
677  
678 <        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
678 >        TreeNode(int hash, Object key, V val, Node<K,V> next,
679 >                 TreeNode<K,V> parent) {
680              super(hash, key, val, next);
681              this.parent = parent;
682          }
683      }
684  
685      /**
686 +     * Returns a Class for the given object of the form "class C
687 +     * implements Comparable<C>", if one exists, else null.  See below
688 +     * for explanation.
689 +     */
690 +    static Class<?> comparableClassFor(Object x) {
691 +        Class<?> c, s, cmpc; Type[] ts, as; Type t; ParameterizedType p;
692 +        if ((c = x.getClass()) == String.class) // bypass checks
693 +            return c;
694 +        if ((cmpc = Comparable.class).isAssignableFrom(c)) {
695 +            while (cmpc.isAssignableFrom(s = c.getSuperclass()))
696 +                c = s; // find topmost comparable class
697 +            if ((ts = c.getGenericInterfaces()) != null) {
698 +                for (int i = 0; i < ts.length; ++i) {
699 +                    if (((t = ts[i]) instanceof ParameterizedType) &&
700 +                        ((p = (ParameterizedType)t).getRawType() == cmpc) &&
701 +                        (as = p.getActualTypeArguments()) != null &&
702 +                        as.length == 1 && as[0] == c) // type arg is c
703 +                        return c;
704 +                }
705 +            }
706 +        }
707 +        return null;
708 +    }
709 +
710 +    /**
711       * A specialized form of red-black tree for use in bins
712       * whose size exceeds a threshold.
713       *
# Line 731 | Line 715 | public class ConcurrentHashMap<K, V>
715       * related operations (which is the main reason we cannot use
716       * existing collections such as TreeMaps). TreeBins contain
717       * Comparable elements, but may contain others, as well as
718 <     * elements that are Comparable but not necessarily Comparable<T>
718 >     * elements that are Comparable but not necessarily Comparable
719       * for the same T, so we cannot invoke compareTo among them. To
720       * handle this, the tree is ordered primarily by hash value, then
721 <     * by getClass().getName() order, and then by Comparator order
722 <     * among elements of the same class.  On lookup at a node, if
723 <     * elements are not comparable or compare as 0, both left and
724 <     * right children may need to be searched in the case of tied hash
725 <     * values. (This corresponds to the full list search that would be
726 <     * necessary if all elements were non-Comparable and had tied
743 <     * hashes.)  The red-black balancing code is updated from
721 >     * by Comparable.compareTo order if applicable.  On lookup at a
722 >     * node, if elements are not comparable or compare as 0 then both
723 >     * left and right children may need to be searched in the case of
724 >     * tied hash values. (This corresponds to the full list search
725 >     * that would be necessary if all elements were non-Comparable and
726 >     * had tied hashes.)  The red-black balancing code is updated from
727       * pre-jdk-collections
728       * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
729       * based in turn on Cormen, Leiserson, and Rivest "Introduction to
# Line 749 | Line 732 | public class ConcurrentHashMap<K, V>
732       * TreeBins also maintain a separate locking discipline than
733       * regular bins. Because they are forwarded via special MOVED
734       * nodes at bin heads (which can never change once established),
735 <     * we cannot use those nodes as locks. Instead, TreeBin
736 <     * extends AbstractQueuedSynchronizer to support a simple form of
737 <     * read-write lock. For update operations and table validation,
738 <     * the exclusive form of lock behaves in the same way as bin-head
739 <     * locks. However, lookups use shared read-lock mechanics to allow
740 <     * multiple readers in the absence of writers.  Additionally,
741 <     * these lookups do not ever block: While the lock is not
742 <     * available, they proceed along the slow traversal path (via
743 <     * next-pointers) until the lock becomes available or the list is
744 <     * exhausted, whichever comes first. (These cases are not fast,
745 <     * but maximize aggregate expected throughput.)  The AQS mechanics
763 <     * for doing this are straightforward.  The lock state is held as
764 <     * AQS getState().  Read counts are negative; the write count (1)
765 <     * is positive.  There are no signalling preferences among readers
766 <     * and writers. Since we don't need to export full Lock API, we
767 <     * just override the minimal AQS methods and use them directly.
735 >     * we cannot use those nodes as locks. Instead, TreeBin extends
736 >     * StampedLock to support a form of read-write lock. For update
737 >     * operations and table validation, the exclusive form of lock
738 >     * behaves in the same way as bin-head locks. However, lookups use
739 >     * shared read-lock mechanics to allow multiple readers in the
740 >     * absence of writers.  Additionally, these lookups do not ever
741 >     * block: While the lock is not available, they proceed along the
742 >     * slow traversal path (via next-pointers) until the lock becomes
743 >     * available or the list is exhausted, whichever comes
744 >     * first. These cases are not fast, but maximize aggregate
745 >     * expected throughput.
746       */
747 <    static final class TreeBin extends AbstractQueuedSynchronizer {
747 >    static final class TreeBin<K,V> extends StampedLock {
748          private static final long serialVersionUID = 2249069246763182397L;
749 <        transient TreeNode root;  // root of tree
750 <        transient TreeNode first; // head of next-pointer list
773 <
774 <        /* AQS overrides */
775 <        public final boolean isHeldExclusively() { return getState() > 0; }
776 <        public final boolean tryAcquire(int ignore) {
777 <            if (compareAndSetState(0, 1)) {
778 <                setExclusiveOwnerThread(Thread.currentThread());
779 <                return true;
780 <            }
781 <            return false;
782 <        }
783 <        public final boolean tryRelease(int ignore) {
784 <            setExclusiveOwnerThread(null);
785 <            setState(0);
786 <            return true;
787 <        }
788 <        public final int tryAcquireShared(int ignore) {
789 <            for (int c;;) {
790 <                if ((c = getState()) > 0)
791 <                    return -1;
792 <                if (compareAndSetState(c, c -1))
793 <                    return 1;
794 <            }
795 <        }
796 <        public final boolean tryReleaseShared(int ignore) {
797 <            int c;
798 <            do {} while (!compareAndSetState(c = getState(), c + 1));
799 <            return c == -1;
800 <        }
749 >        transient TreeNode<K,V> root;  // root of tree
750 >        transient TreeNode<K,V> first; // head of next-pointer list
751  
752          /** From CLR */
753 <        private void rotateLeft(TreeNode p) {
753 >        private void rotateLeft(TreeNode<K,V> p) {
754              if (p != null) {
755 <                TreeNode r = p.right, pp, rl;
755 >                TreeNode<K,V> r = p.right, pp, rl;
756                  if ((rl = p.right = r.left) != null)
757                      rl.parent = p;
758                  if ((pp = r.parent = p.parent) == null)
# Line 817 | Line 767 | public class ConcurrentHashMap<K, V>
767          }
768  
769          /** From CLR */
770 <        private void rotateRight(TreeNode p) {
770 >        private void rotateRight(TreeNode<K,V> p) {
771              if (p != null) {
772 <                TreeNode l = p.left, pp, lr;
772 >                TreeNode<K,V> l = p.left, pp, lr;
773                  if ((lr = p.left = l.right) != null)
774                      lr.parent = p;
775                  if ((pp = l.parent = p.parent) == null)
# Line 837 | Line 787 | public class ConcurrentHashMap<K, V>
787           * Returns the TreeNode (or null if not found) for the given key
788           * starting at given root.
789           */
790 <        @SuppressWarnings("unchecked") final TreeNode getTreeNode
791 <            (int h, Object k, TreeNode p) {
842 <            Class<?> c = k.getClass();
790 >        final TreeNode<K,V> getTreeNode(int h, Object k, TreeNode<K,V> p,
791 >                                        Class<?> cc) {
792              while (p != null) {
793 <                int dir, ph;  Object pk; Class<?> pc;
794 <                if ((ph = p.hash) == h) {
846 <                    if ((pk = p.key) == k || k.equals(pk))
847 <                        return p;
848 <                    if (c != (pc = pk.getClass()) ||
849 <                        !(k instanceof Comparable) ||
850 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
851 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
852 <                        TreeNode r = null, s = null, pl, pr;
853 <                        if (dir >= 0) {
854 <                            if ((pl = p.left) != null && h <= pl.hash)
855 <                                s = pl;
856 <                        }
857 <                        else if ((pr = p.right) != null && h >= pr.hash)
858 <                            s = pr;
859 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
860 <                            return r;
861 <                    }
862 <                }
863 <                else
793 >                int dir, ph; Object pk;
794 >                if ((ph = p.hash) != h)
795                      dir = (h < ph) ? -1 : 1;
796 +                else if ((pk = p.key) == k || k.equals(pk))
797 +                    return p;
798 +                else if (cc == null || comparableClassFor(pk) != cc ||
799 +                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
800 +                    TreeNode<K,V> r, pr; // check both sides
801 +                    if ((pr = p.right) != null &&
802 +                        (r = getTreeNode(h, k, pr, cc)) != null)
803 +                        return r;
804 +                    else // continue left
805 +                        dir = -1;
806 +                }
807                  p = (dir > 0) ? p.right : p.left;
808              }
809              return null;
# Line 872 | Line 814 | public class ConcurrentHashMap<K, V>
814           * read-lock to call getTreeNode, but during failure to get
815           * lock, searches along next links.
816           */
817 <        final Object getValue(int h, Object k) {
818 <            Node r = null;
819 <            int c = getState(); // Must read lock state first
820 <            for (Node e = first; e != null; e = e.next) {
821 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
817 >        final V getValue(int h, Object k) {
818 >            Class<?> cc = comparableClassFor(k);
819 >            Node<K,V> r = null;
820 >            for (Node<K,V> e = first; e != null; e = e.next) {
821 >                long s;
822 >                if ((s = tryReadLock()) != 0L) {
823                      try {
824 <                        r = getTreeNode(h, k, root);
824 >                        r = getTreeNode(h, k, root, cc);
825                      } finally {
826 <                        releaseShared(0);
826 >                        unlockRead(s);
827                      }
828                      break;
829                  }
830 <                else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
830 >                else if (e.hash == h && k.equals(e.key)) {
831                      r = e;
832                      break;
833                  }
891                else
892                    c = getState();
834              }
835              return r == null ? null : r.val;
836          }
# Line 898 | Line 839 | public class ConcurrentHashMap<K, V>
839           * Finds or adds a node.
840           * @return null if added
841           */
842 <        @SuppressWarnings("unchecked") final TreeNode putTreeNode
843 <            (int h, Object k, Object v) {
844 <            Class<?> c = k.getClass();
904 <            TreeNode pp = root, p = null;
842 >        final TreeNode<K,V> putTreeNode(int h, Object k, V v) {
843 >            Class<?> cc = comparableClassFor(k);
844 >            TreeNode<K,V> pp = root, p = null;
845              int dir = 0;
846              while (pp != null) { // find existing node or leaf to insert at
847 <                int ph;  Object pk; Class<?> pc;
847 >                int ph; Object pk;
848                  p = pp;
849 <                if ((ph = p.hash) == h) {
910 <                    if ((pk = p.key) == k || k.equals(pk))
911 <                        return p;
912 <                    if (c != (pc = pk.getClass()) ||
913 <                        !(k instanceof Comparable) ||
914 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
915 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
916 <                        TreeNode r = null, s = null, pl, pr;
917 <                        if (dir >= 0) {
918 <                            if ((pl = p.left) != null && h <= pl.hash)
919 <                                s = pl;
920 <                        }
921 <                        else if ((pr = p.right) != null && h >= pr.hash)
922 <                            s = pr;
923 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
924 <                            return r;
925 <                    }
926 <                }
927 <                else
849 >                if ((ph = p.hash) != h)
850                      dir = (h < ph) ? -1 : 1;
851 +                else if ((pk = p.key) == k || k.equals(pk))
852 +                    return p;
853 +                else if (cc == null || comparableClassFor(pk) != cc ||
854 +                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
855 +                    TreeNode<K,V> r, pr;
856 +                    if ((pr = p.right) != null &&
857 +                        (r = getTreeNode(h, k, pr, cc)) != null)
858 +                        return r;
859 +                    else // continue left
860 +                        dir = -1;
861 +                }
862                  pp = (dir > 0) ? p.right : p.left;
863              }
864  
865 <            TreeNode f = first;
866 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
865 >            TreeNode<K,V> f = first;
866 >            TreeNode<K,V> x = first = new TreeNode<K,V>(h, k, v, f, p);
867              if (p == null)
868                  root = x;
869              else { // attach and rebalance; adapted from CLR
937                TreeNode xp, xpp;
870                  if (f != null)
871                      f.prev = x;
872                  if (dir <= 0)
# Line 942 | Line 874 | public class ConcurrentHashMap<K, V>
874                  else
875                      p.right = x;
876                  x.red = true;
877 <                while (x != null && (xp = x.parent) != null && xp.red &&
878 <                       (xpp = xp.parent) != null) {
879 <                    TreeNode xppl = xpp.left;
880 <                    if (xp == xppl) {
881 <                        TreeNode y = xpp.right;
882 <                        if (y != null && y.red) {
883 <                            y.red = false;
877 >                for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
878 >                    if ((xp = x.parent) == null) {
879 >                        (root = x).red = false;
880 >                        break;
881 >                    }
882 >                    else if (!xp.red || (xpp = xp.parent) == null) {
883 >                        TreeNode<K,V> r = root;
884 >                        if (r != null && r.red)
885 >                            r.red = false;
886 >                        break;
887 >                    }
888 >                    else if ((xppl = xpp.left) == xp) {
889 >                        if ((xppr = xpp.right) != null && xppr.red) {
890 >                            xppr.red = false;
891                              xp.red = false;
892                              xpp.red = true;
893                              x = xpp;
# Line 968 | Line 907 | public class ConcurrentHashMap<K, V>
907                          }
908                      }
909                      else {
910 <                        TreeNode y = xppl;
911 <                        if (y != null && y.red) {
973 <                            y.red = false;
910 >                        if (xppl != null && xppl.red) {
911 >                            xppl.red = false;
912                              xp.red = false;
913                              xpp.red = true;
914                              x = xpp;
# Line 990 | Line 928 | public class ConcurrentHashMap<K, V>
928                          }
929                      }
930                  }
993                TreeNode r = root;
994                if (r != null && r.red)
995                    r.red = false;
931              }
932 +            assert checkInvariants();
933              return null;
934          }
935  
# Line 1005 | Line 941 | public class ConcurrentHashMap<K, V>
941           * that are accessible independently of lock. So instead we
942           * swap the tree linkages.
943           */
944 <        final void deleteTreeNode(TreeNode p) {
945 <            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
946 <            TreeNode pred = p.prev;
944 >        final void deleteTreeNode(TreeNode<K,V> p) {
945 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
946 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
947              if (pred == null)
948                  first = next;
949              else
950                  pred.next = next;
951              if (next != null)
952                  next.prev = pred;
953 <            TreeNode replacement;
954 <            TreeNode pl = p.left;
955 <            TreeNode pr = p.right;
953 >            else if (pred == null) {
954 >                root = null;
955 >                return;
956 >            }
957 >            TreeNode<K,V> replacement;
958 >            TreeNode<K,V> pl = p.left;
959 >            TreeNode<K,V> pr = p.right;
960              if (pl != null && pr != null) {
961 <                TreeNode s = pr, sl;
961 >                TreeNode<K,V> s = pr, sl;
962                  while ((sl = s.left) != null) // find successor
963                      s = sl;
964                  boolean c = s.red; s.red = p.red; p.red = c; // swap colors
965 <                TreeNode sr = s.right;
966 <                TreeNode pp = p.parent;
965 >                TreeNode<K,V> sr = s.right;
966 >                TreeNode<K,V> pp = p.parent;
967                  if (s == pr) { // p was s's direct parent
968                      p.parent = s;
969                      s.right = p;
970                  }
971                  else {
972 <                    TreeNode sp = s.parent;
972 >                    TreeNode<K,V> sp = s.parent;
973                      if ((p.parent = sp) != null) {
974                          if (s == sp.left)
975                              sp.left = p;
# Line 1050 | Line 990 | public class ConcurrentHashMap<K, V>
990                      pp.left = s;
991                  else
992                      pp.right = s;
993 <                replacement = sr;
993 >                if (sr != null)
994 >                    replacement = sr;
995 >                else
996 >                    replacement = p;
997              }
998 +            else if (pl != null)
999 +                replacement = pl;
1000 +            else if (pr != null)
1001 +                replacement = pr;
1002              else
1056                replacement = (pl != null) ? pl : pr;
1057            TreeNode pp = p.parent;
1058            if (replacement == null) {
1059                if (pp == null) {
1060                    root = null;
1061                    return;
1062                }
1003                  replacement = p;
1004 <            }
1005 <            else {
1066 <                replacement.parent = pp;
1004 >            if (replacement != p) {
1005 >                TreeNode<K,V> pp = replacement.parent = p.parent;
1006                  if (pp == null)
1007                      root = replacement;
1008                  else if (p == pp.left)
# Line 1073 | Line 1012 | public class ConcurrentHashMap<K, V>
1012                  p.left = p.right = p.parent = null;
1013              }
1014              if (!p.red) { // rebalance, from CLR
1015 <                TreeNode x = replacement;
1016 <                while (x != null) {
1078 <                    TreeNode xp, xpl;
1015 >                for (TreeNode<K,V> x = replacement; x != null; ) {
1016 >                    TreeNode<K,V> xp, xpl, xpr;
1017                      if (x.red || (xp = x.parent) == null) {
1018                          x.red = false;
1019                          break;
1020                      }
1021 <                    if (x == (xpl = xp.left)) {
1022 <                        TreeNode sib = xp.right;
1023 <                        if (sib != null && sib.red) {
1086 <                            sib.red = false;
1021 >                    else if ((xpl = xp.left) == x) {
1022 >                        if ((xpr = xp.right) != null && xpr.red) {
1023 >                            xpr.red = false;
1024                              xp.red = true;
1025                              rotateLeft(xp);
1026 <                            sib = (xp = x.parent) == null ? null : xp.right;
1026 >                            xpr = (xp = x.parent) == null ? null : xp.right;
1027                          }
1028 <                        if (sib == null)
1028 >                        if (xpr == null)
1029                              x = xp;
1030                          else {
1031 <                            TreeNode sl = sib.left, sr = sib.right;
1031 >                            TreeNode<K,V> sl = xpr.left, sr = xpr.right;
1032                              if ((sr == null || !sr.red) &&
1033                                  (sl == null || !sl.red)) {
1034 <                                sib.red = true;
1034 >                                xpr.red = true;
1035                                  x = xp;
1036                              }
1037                              else {
1038                                  if (sr == null || !sr.red) {
1039                                      if (sl != null)
1040                                          sl.red = false;
1041 <                                    sib.red = true;
1042 <                                    rotateRight(sib);
1043 <                                    sib = (xp = x.parent) == null ? null : xp.right;
1041 >                                    xpr.red = true;
1042 >                                    rotateRight(xpr);
1043 >                                    xpr = (xp = x.parent) == null ?
1044 >                                        null : xp.right;
1045                                  }
1046 <                                if (sib != null) {
1047 <                                    sib.red = (xp == null) ? false : xp.red;
1048 <                                    if ((sr = sib.right) != null)
1046 >                                if (xpr != null) {
1047 >                                    xpr.red = (xp == null) ? false : xp.red;
1048 >                                    if ((sr = xpr.right) != null)
1049                                          sr.red = false;
1050                                  }
1051                                  if (xp != null) {
# Line 1119 | Line 1057 | public class ConcurrentHashMap<K, V>
1057                          }
1058                      }
1059                      else { // symmetric
1060 <                        TreeNode sib = xpl;
1061 <                        if (sib != null && sib.red) {
1124 <                            sib.red = false;
1060 >                        if (xpl != null && xpl.red) {
1061 >                            xpl.red = false;
1062                              xp.red = true;
1063                              rotateRight(xp);
1064 <                            sib = (xp = x.parent) == null ? null : xp.left;
1064 >                            xpl = (xp = x.parent) == null ? null : xp.left;
1065                          }
1066 <                        if (sib == null)
1066 >                        if (xpl == null)
1067                              x = xp;
1068                          else {
1069 <                            TreeNode sl = sib.left, sr = sib.right;
1069 >                            TreeNode<K,V> sl = xpl.left, sr = xpl.right;
1070                              if ((sl == null || !sl.red) &&
1071                                  (sr == null || !sr.red)) {
1072 <                                sib.red = true;
1072 >                                xpl.red = true;
1073                                  x = xp;
1074                              }
1075                              else {
1076                                  if (sl == null || !sl.red) {
1077                                      if (sr != null)
1078                                          sr.red = false;
1079 <                                    sib.red = true;
1080 <                                    rotateLeft(sib);
1081 <                                    sib = (xp = x.parent) == null ? null : xp.left;
1079 >                                    xpl.red = true;
1080 >                                    rotateLeft(xpl);
1081 >                                    xpl = (xp = x.parent) == null ?
1082 >                                        null : xp.left;
1083                                  }
1084 <                                if (sib != null) {
1085 <                                    sib.red = (xp == null) ? false : xp.red;
1086 <                                    if ((sl = sib.left) != null)
1084 >                                if (xpl != null) {
1085 >                                    xpl.red = (xp == null) ? false : xp.red;
1086 >                                    if ((sl = xpl.left) != null)
1087                                          sl.red = false;
1088                                  }
1089                                  if (xp != null) {
# Line 1158 | Line 1096 | public class ConcurrentHashMap<K, V>
1096                      }
1097                  }
1098              }
1099 <            if (p == replacement && (pp = p.parent) != null) {
1100 <                if (p == pp.left) // detach pointers
1101 <                    pp.left = null;
1102 <                else if (p == pp.right)
1103 <                    pp.right = null;
1104 <                p.parent = null;
1099 >            if (p == replacement) {  // detach pointers
1100 >                TreeNode<K,V> pp;
1101 >                if ((pp = p.parent) != null) {
1102 >                    if (p == pp.left)
1103 >                        pp.left = null;
1104 >                    else if (p == pp.right)
1105 >                        pp.right = null;
1106 >                    p.parent = null;
1107 >                }
1108              }
1109 +            assert checkInvariants();
1110 +        }
1111 +
1112 +        /**
1113 +         * Checks linkage and balance invariants at root
1114 +         */
1115 +        final boolean checkInvariants() {
1116 +            TreeNode<K,V> r = root;
1117 +            if (r == null)
1118 +                return (first == null);
1119 +            else
1120 +                return (first != null) && checkTreeNode(r);
1121 +        }
1122 +
1123 +        /**
1124 +         * Recursive invariant check
1125 +         */
1126 +        final boolean checkTreeNode(TreeNode<K,V> t) {
1127 +            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
1128 +                tb = t.prev, tn = (TreeNode<K,V>)t.next;
1129 +            if (tb != null && tb.next != t)
1130 +                return false;
1131 +            if (tn != null && tn.prev != t)
1132 +                return false;
1133 +            if (tp != null && t != tp.left && t != tp.right)
1134 +                return false;
1135 +            if (tl != null && (tl.parent != t || tl.hash > t.hash))
1136 +                return false;
1137 +            if (tr != null && (tr.parent != t || tr.hash < t.hash))
1138 +                return false;
1139 +            if (t.red && tl != null && tl.red && tr != null && tr.red)
1140 +                return false;
1141 +            if (tl != null && !checkTreeNode(tl))
1142 +                return false;
1143 +            if (tr != null && !checkTreeNode(tr))
1144 +                return false;
1145 +            return true;
1146          }
1147      }
1148  
1149      /* ---------------- Collision reduction methods -------------- */
1150  
1151      /**
1152 <     * Spreads higher bits to lower, and also forces top 2 bits to 0.
1152 >     * Spreads higher bits to lower, and also forces top bit to 0.
1153       * Because the table uses power-of-two masking, sets of hashes
1154       * that vary only in bits above the current mask will always
1155       * collide. (Among known examples are sets of Float keys holding
# Line 1189 | Line 1167 | public class ConcurrentHashMap<K, V>
1167      }
1168  
1169      /**
1170 <     * Replaces a list bin with a tree bin. Call only when locked.
1171 <     * Fails to replace if the given key is non-comparable or table
1172 <     * is, or needs, resizing.
1173 <     */
1174 <    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1175 <        if ((key instanceof Comparable) &&
1176 <            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
1177 <            TreeBin t = new TreeBin();
1178 <            for (Node e = tabAt(tab, index); e != null; e = e.next)
1201 <                t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
1202 <            setTabAt(tab, index, new Node(MOVED, t, null, null));
1170 >     * Replaces a list bin with a tree bin if key is comparable.  Call
1171 >     * only when locked.
1172 >     */
1173 >    private final void replaceWithTreeBin(Node<K,V>[] tab, int index, Object key) {
1174 >        if (tab != null && comparableClassFor(key) != null) {
1175 >            TreeBin<K,V> t = new TreeBin<K,V>();
1176 >            for (Node<K,V> e = tabAt(tab, index); e != null; e = e.next)
1177 >                t.putTreeNode(e.hash, e.key, e.val);
1178 >            setTabAt(tab, index, new Node<K,V>(MOVED, t, null, null));
1179          }
1180      }
1181  
1182      /* ---------------- Internal access and update methods -------------- */
1183  
1184      /** Implementation for get and containsKey */
1185 <    private final Object internalGet(Object k) {
1185 >    private final V internalGet(Object k) {
1186          int h = spread(k.hashCode());
1187 <        retry: for (Node[] tab = table; tab != null;) {
1188 <            Node e, p; Object ek, ev; int eh;      // locals to read fields once
1189 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1190 <                if ((eh = e.hash) == MOVED) {
1191 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1192 <                        return ((TreeBin)ek).getValue(h, k);
1193 <                    else {                        // restart with new table
1194 <                        tab = (Node[])ek;
1195 <                        continue retry;
1196 <                    }
1197 <                }
1198 <                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1199 <                         ((ek = e.key) == k || k.equals(ek)))
1200 <                    return ev;
1187 >        V v = null;
1188 >        Node<K,V>[] tab; Node<K,V> e;
1189 >        if ((tab = table) != null &&
1190 >            (e = tabAt(tab, (tab.length - 1) & h)) != null) {
1191 >            for (;;) {
1192 >                int eh; Object ek;
1193 >                if ((eh = e.hash) < 0) {
1194 >                    if ((ek = e.key) instanceof TreeBin) { // search TreeBin
1195 >                        v = ((TreeBin<K,V>)ek).getValue(h, k);
1196 >                        break;
1197 >                    }
1198 >                    else if (!(ek instanceof Node[]) ||    // try new table
1199 >                             (e = tabAt(tab = (Node<K,V>[])ek,
1200 >                                        (tab.length - 1) & h)) == null)
1201 >                        break;
1202 >                }
1203 >                else if (eh == h && ((ek = e.key) == k || k.equals(ek))) {
1204 >                    v = e.val;
1205 >                    break;
1206 >                }
1207 >                else if ((e = e.next) == null)
1208 >                    break;
1209              }
1226            break;
1210          }
1211 <        return null;
1211 >        return v;
1212      }
1213  
1214      /**
# Line 1233 | Line 1216 | public class ConcurrentHashMap<K, V>
1216       * Replaces node value with v, conditional upon match of cv if
1217       * non-null.  If resulting value is null, delete.
1218       */
1219 <    private final Object internalReplace(Object k, Object v, Object cv) {
1219 >    private final V internalReplace(Object k, V v, Object cv) {
1220          int h = spread(k.hashCode());
1221 <        Object oldVal = null;
1222 <        for (Node[] tab = table;;) {
1223 <            Node f; int i, fh; Object fk;
1221 >        V oldVal = null;
1222 >        for (Node<K,V>[] tab = table;;) {
1223 >            Node<K,V> f; int i, fh; Object fk;
1224              if (tab == null ||
1225                  (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1226                  break;
1227 <            else if ((fh = f.hash) == MOVED) {
1227 >            else if ((fh = f.hash) < 0) {
1228                  if ((fk = f.key) instanceof TreeBin) {
1229 <                    TreeBin t = (TreeBin)fk;
1229 >                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1230 >                    long stamp = t.writeLock();
1231                      boolean validated = false;
1232                      boolean deleted = false;
1249                    t.acquire(0);
1233                      try {
1234                          if (tabAt(tab, i) == f) {
1235                              validated = true;
1236 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1236 >                            Class<?> cc = comparableClassFor(k);
1237 >                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
1238                              if (p != null) {
1239 <                                Object pv = p.val;
1239 >                                V pv = p.val;
1240                                  if (cv == null || cv == pv || cv.equals(pv)) {
1241                                      oldVal = pv;
1242 <                                    if ((p.val = v) == null) {
1242 >                                    if (v != null)
1243 >                                        p.val = v;
1244 >                                    else {
1245                                          deleted = true;
1246                                          t.deleteTreeNode(p);
1247                                      }
# Line 1263 | Line 1249 | public class ConcurrentHashMap<K, V>
1249                              }
1250                          }
1251                      } finally {
1252 <                        t.release(0);
1252 >                        t.unlockWrite(stamp);
1253                      }
1254                      if (validated) {
1255                          if (deleted)
1256 <                            counter.add(-1L);
1256 >                            addCount(-1L, -1);
1257                          break;
1258                      }
1259                  }
1260                  else
1261 <                    tab = (Node[])fk;
1276 <            }
1277 <            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
1278 <                break;                          // rules out possible existence
1279 <            else if ((fh & LOCKED) != 0) {
1280 <                checkForResize();               // try resizing if can't get lock
1281 <                f.tryAwaitLock(tab, i);
1261 >                    tab = (Node<K,V>[])fk;
1262              }
1263 <            else if (f.casHash(fh, fh | LOCKED)) {
1263 >            else {
1264                  boolean validated = false;
1265                  boolean deleted = false;
1266 <                try {
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 & HASH_BITS) == h &&
1292 <                                ((ev = e.val) != null) &&
1269 >                        for (Node<K,V> e = f, pred = null;;) {
1270 >                            Object ek;
1271 >                            if (e.hash == h &&
1272                                  ((ek = e.key) == k || k.equals(ek))) {
1273 +                                V ev = e.val;
1274                                  if (cv == null || cv == ev || cv.equals(ev)) {
1275                                      oldVal = ev;
1276 <                                    if ((e.val = v) == null) {
1276 >                                    if (v != null)
1277 >                                        e.val = v;
1278 >                                    else {
1279                                          deleted = true;
1280 <                                        Node en = e.next;
1280 >                                        Node<K,V> en = e.next;
1281                                          if (pred != null)
1282                                              pred.next = en;
1283                                          else
# Line 1309 | Line 1291 | public class ConcurrentHashMap<K, V>
1291                                  break;
1292                          }
1293                      }
1312                } finally {
1313                    if (!f.casHash(fh | LOCKED, fh)) {
1314                        f.hash = fh;
1315                        synchronized (f) { f.notifyAll(); };
1316                    }
1294                  }
1295                  if (validated) {
1296                      if (deleted)
1297 <                        counter.add(-1L);
1297 >                        addCount(-1L, -1);
1298                      break;
1299                  }
1300              }
# Line 1326 | Line 1303 | public class ConcurrentHashMap<K, V>
1303      }
1304  
1305      /*
1306 <     * Internal versions of the six insertion methods, each a
1307 <     * little more complicated than the last. All have
1331 <     * the same basic structure as the first (internalPut):
1306 >     * Internal versions of insertion methods
1307 >     * All have the same basic structure as the first (internalPut):
1308       *  1. If table uninitialized, create
1309       *  2. If bin empty, try to CAS new node
1310       *  3. If bin stale, use new table
1311       *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1312       *  5. Lock and validate; if valid, scan and add or update
1313       *
1314 <     * The others interweave other checks and/or alternative actions:
1315 <     *  * Plain put checks for and performs resize after insertion.
1316 <     *  * putIfAbsent prescans for mapping without lock (and fails to add
1317 <     *    if present), which also makes pre-emptive resize checks worthwhile.
1318 <     *  * computeIfAbsent extends form used in putIfAbsent with additional
1319 <     *    mechanics to deal with, calls, potential exceptions and null
1320 <     *    returns from function call.
1345 <     *  * compute uses the same function-call mechanics, but without
1346 <     *    the prescans
1347 <     *  * merge acts as putIfAbsent in the absent case, but invokes the
1348 <     *    update function if present
1349 <     *  * putAll attempts to pre-allocate enough table space
1350 <     *    and more lazily performs count updates and checks.
1351 <     *
1352 <     * Someday when details settle down a bit more, it might be worth
1353 <     * some factoring to reduce sprawl.
1314 >     * The putAll method differs mainly in attempting to pre-allocate
1315 >     * enough table space, and also more lazily performs count updates
1316 >     * and checks.
1317 >     *
1318 >     * Most of the function-accepting methods can't be factored nicely
1319 >     * because they require different functional forms, so instead
1320 >     * sprawl out similar mechanics.
1321       */
1322  
1323 <    /** Implementation for put */
1324 <    private final Object internalPut(Object k, Object v) {
1323 >    /** Implementation for put and putIfAbsent */
1324 >    private final V internalPut(K k, V v, boolean onlyIfAbsent) {
1325 >        if (k == null || v == null) throw new NullPointerException();
1326          int h = spread(k.hashCode());
1327 <        int count = 0;
1328 <        for (Node[] tab = table;;) {
1329 <            int i; Node f; int fh; Object fk;
1327 >        int len = 0;
1328 >        for (Node<K,V>[] tab = table;;) {
1329 >            int i, fh; Node<K,V> f; Object fk;
1330              if (tab == null)
1331                  tab = initTable();
1332              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1333 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1333 >                if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null)))
1334                      break;                   // no lock when adding to empty bin
1335              }
1336 <            else if ((fh = f.hash) == MOVED) {
1336 >            else if ((fh = f.hash) < 0) {
1337                  if ((fk = f.key) instanceof TreeBin) {
1338 <                    TreeBin t = (TreeBin)fk;
1339 <                    Object oldVal = null;
1340 <                    t.acquire(0);
1338 >                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1339 >                    long stamp = t.writeLock();
1340 >                    V oldVal = null;
1341                      try {
1342                          if (tabAt(tab, i) == f) {
1343 <                            count = 2;
1344 <                            TreeNode p = t.putTreeNode(h, k, v);
1343 >                            len = 2;
1344 >                            TreeNode<K,V> p = t.putTreeNode(h, k, v);
1345                              if (p != null) {
1346                                  oldVal = p.val;
1347 <                                p.val = v;
1347 >                                if (!onlyIfAbsent)
1348 >                                    p.val = v;
1349                              }
1350                          }
1351                      } finally {
1352 <                        t.release(0);
1352 >                        t.unlockWrite(stamp);
1353                      }
1354 <                    if (count != 0) {
1354 >                    if (len != 0) {
1355                          if (oldVal != null)
1356                              return oldVal;
1357                          break;
1358                      }
1359                  }
1360                  else
1361 <                    tab = (Node[])fk;
1361 >                    tab = (Node<K,V>[])fk;
1362              }
1363 <            else if ((fh & LOCKED) != 0) {
1364 <                checkForResize();
1365 <                f.tryAwaitLock(tab, i);
1397 <            }
1398 <            else if (f.casHash(fh, fh | LOCKED)) {
1399 <                Object oldVal = null;
1400 <                try {                        // needed in case equals() throws
1363 >            else {
1364 >                V oldVal = null;
1365 >                synchronized (f) {
1366                      if (tabAt(tab, i) == f) {
1367 <                        count = 1;
1368 <                        for (Node e = f;; ++count) {
1369 <                            Object ek, ev;
1370 <                            if ((e.hash & HASH_BITS) == h &&
1406 <                                (ev = e.val) != null &&
1367 >                        len = 1;
1368 >                        for (Node<K,V> e = f;; ++len) {
1369 >                            Object ek;
1370 >                            if (e.hash == h &&
1371                                  ((ek = e.key) == k || k.equals(ek))) {
1372 <                                oldVal = ev;
1373 <                                e.val = v;
1372 >                                oldVal = e.val;
1373 >                                if (!onlyIfAbsent)
1374 >                                    e.val = v;
1375                                  break;
1376                              }
1377 <                            Node last = e;
1377 >                            Node<K,V> last = e;
1378                              if ((e = e.next) == null) {
1379 <                                last.next = new Node(h, k, v, null);
1380 <                                if (count >= TREE_THRESHOLD)
1379 >                                last.next = new Node<K,V>(h, k, v, null);
1380 >                                if (len > TREE_THRESHOLD)
1381                                      replaceWithTreeBin(tab, i, k);
1382                                  break;
1383                              }
1384                          }
1385                      }
1421                } finally {                  // unlock and signal if needed
1422                    if (!f.casHash(fh | LOCKED, fh)) {
1423                        f.hash = fh;
1424                        synchronized (f) { f.notifyAll(); };
1425                    }
1386                  }
1387 <                if (count != 0) {
1387 >                if (len != 0) {
1388                      if (oldVal != null)
1389                          return oldVal;
1430                    if (tab.length <= 64)
1431                        count = 2;
1390                      break;
1391                  }
1392              }
1393          }
1394 <        counter.add(1L);
1437 <        if (count > 1)
1438 <            checkForResize();
1439 <        return null;
1440 <    }
1441 <
1442 <    /** Implementation for putIfAbsent */
1443 <    private final Object internalPutIfAbsent(Object k, Object v) {
1444 <        int h = spread(k.hashCode());
1445 <        int count = 0;
1446 <        for (Node[] tab = table;;) {
1447 <            int i; Node f; int fh; Object fk, fv;
1448 <            if (tab == null)
1449 <                tab = initTable();
1450 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1451 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1452 <                    break;
1453 <            }
1454 <            else if ((fh = f.hash) == MOVED) {
1455 <                if ((fk = f.key) instanceof TreeBin) {
1456 <                    TreeBin t = (TreeBin)fk;
1457 <                    Object oldVal = null;
1458 <                    t.acquire(0);
1459 <                    try {
1460 <                        if (tabAt(tab, i) == f) {
1461 <                            count = 2;
1462 <                            TreeNode p = t.putTreeNode(h, k, v);
1463 <                            if (p != null)
1464 <                                oldVal = p.val;
1465 <                        }
1466 <                    } finally {
1467 <                        t.release(0);
1468 <                    }
1469 <                    if (count != 0) {
1470 <                        if (oldVal != null)
1471 <                            return oldVal;
1472 <                        break;
1473 <                    }
1474 <                }
1475 <                else
1476 <                    tab = (Node[])fk;
1477 <            }
1478 <            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1479 <                     ((fk = f.key) == k || k.equals(fk)))
1480 <                return fv;
1481 <            else {
1482 <                Node g = f.next;
1483 <                if (g != null) { // at least 2 nodes -- search and maybe resize
1484 <                    for (Node e = g;;) {
1485 <                        Object ek, ev;
1486 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1487 <                            ((ek = e.key) == k || k.equals(ek)))
1488 <                            return ev;
1489 <                        if ((e = e.next) == null) {
1490 <                            checkForResize();
1491 <                            break;
1492 <                        }
1493 <                    }
1494 <                }
1495 <                if (((fh = f.hash) & LOCKED) != 0) {
1496 <                    checkForResize();
1497 <                    f.tryAwaitLock(tab, i);
1498 <                }
1499 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1500 <                    Object oldVal = null;
1501 <                    try {
1502 <                        if (tabAt(tab, i) == f) {
1503 <                            count = 1;
1504 <                            for (Node e = f;; ++count) {
1505 <                                Object ek, ev;
1506 <                                if ((e.hash & HASH_BITS) == h &&
1507 <                                    (ev = e.val) != null &&
1508 <                                    ((ek = e.key) == k || k.equals(ek))) {
1509 <                                    oldVal = ev;
1510 <                                    break;
1511 <                                }
1512 <                                Node last = e;
1513 <                                if ((e = e.next) == null) {
1514 <                                    last.next = new Node(h, k, v, null);
1515 <                                    if (count >= TREE_THRESHOLD)
1516 <                                        replaceWithTreeBin(tab, i, k);
1517 <                                    break;
1518 <                                }
1519 <                            }
1520 <                        }
1521 <                    } finally {
1522 <                        if (!f.casHash(fh | LOCKED, fh)) {
1523 <                            f.hash = fh;
1524 <                            synchronized (f) { f.notifyAll(); };
1525 <                        }
1526 <                    }
1527 <                    if (count != 0) {
1528 <                        if (oldVal != null)
1529 <                            return oldVal;
1530 <                        if (tab.length <= 64)
1531 <                            count = 2;
1532 <                        break;
1533 <                    }
1534 <                }
1535 <            }
1536 <        }
1537 <        counter.add(1L);
1538 <        if (count > 1)
1539 <            checkForResize();
1394 >        addCount(1L, len);
1395          return null;
1396      }
1397  
1398      /** Implementation for computeIfAbsent */
1399 <    private final Object internalComputeIfAbsent(K k,
1400 <                                                 Fun<? super K, ?> mf) {
1399 >    private final V internalComputeIfAbsent(K k, Function<? super K, ? extends V> mf) {
1400 >        if (k == null || mf == null)
1401 >            throw new NullPointerException();
1402          int h = spread(k.hashCode());
1403 <        Object val = null;
1404 <        int count = 0;
1405 <        for (Node[] tab = table;;) {
1406 <            Node f; int i, fh; Object fk, fv;
1403 >        V val = null;
1404 >        int len = 0;
1405 >        for (Node<K,V>[] tab = table;;) {
1406 >            Node<K,V> f; int i; Object fk;
1407              if (tab == null)
1408                  tab = initTable();
1409              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1410 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1411 <                if (casTabAt(tab, i, null, node)) {
1412 <                    count = 1;
1413 <                    try {
1414 <                        if ((val = mf.apply(k)) != null)
1415 <                            node.val = val;
1416 <                    } finally {
1417 <                        if (val == null)
1418 <                            setTabAt(tab, i, null);
1419 <                        if (!node.casHash(fh, h)) {
1564 <                            node.hash = h;
1565 <                            synchronized (node) { node.notifyAll(); };
1410 >                Node<K,V> node = new Node<K,V>(h, k, null, null);
1411 >                synchronized (node) {
1412 >                    if (casTabAt(tab, i, null, node)) {
1413 >                        len = 1;
1414 >                        try {
1415 >                            if ((val = mf.apply(k)) != null)
1416 >                                node.val = val;
1417 >                        } finally {
1418 >                            if (val == null)
1419 >                                setTabAt(tab, i, null);
1420                          }
1421                      }
1422                  }
1423 <                if (count != 0)
1423 >                if (len != 0)
1424                      break;
1425              }
1426 <            else if ((fh = f.hash) == MOVED) {
1426 >            else if (f.hash < 0) {
1427                  if ((fk = f.key) instanceof TreeBin) {
1428 <                    TreeBin t = (TreeBin)fk;
1428 >                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1429 >                    long stamp = t.writeLock();
1430                      boolean added = false;
1576                    t.acquire(0);
1431                      try {
1432                          if (tabAt(tab, i) == f) {
1433 <                            count = 1;
1434 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1433 >                            len = 2;
1434 >                            Class<?> cc = comparableClassFor(k);
1435 >                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
1436                              if (p != null)
1437                                  val = p.val;
1438                              else if ((val = mf.apply(k)) != null) {
1439                                  added = true;
1585                                count = 2;
1440                                  t.putTreeNode(h, k, val);
1441                              }
1442                          }
1443                      } finally {
1444 <                        t.release(0);
1444 >                        t.unlockWrite(stamp);
1445                      }
1446 <                    if (count != 0) {
1446 >                    if (len != 0) {
1447                          if (!added)
1448                              return val;
1449                          break;
1450                      }
1451                  }
1452                  else
1453 <                    tab = (Node[])fk;
1453 >                    tab = (Node<K,V>[])fk;
1454              }
1601            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1602                     ((fk = f.key) == k || k.equals(fk)))
1603                return fv;
1455              else {
1456 <                Node g = f.next;
1457 <                if (g != null) {
1458 <                    for (Node e = g;;) {
1459 <                        Object ek, ev;
1460 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1461 <                            ((ek = e.key) == k || k.equals(ek)))
1462 <                            return ev;
1463 <                        if ((e = e.next) == null) {
1464 <                            checkForResize();
1465 <                            break;
1466 <                        }
1467 <                    }
1468 <                }
1469 <                if (((fh = f.hash) & LOCKED) != 0) {
1470 <                    checkForResize();
1471 <                    f.tryAwaitLock(tab, i);
1472 <                }
1473 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1623 <                    boolean added = false;
1624 <                    try {
1625 <                        if (tabAt(tab, i) == f) {
1626 <                            count = 1;
1627 <                            for (Node e = f;; ++count) {
1628 <                                Object ek, ev;
1629 <                                if ((e.hash & HASH_BITS) == h &&
1630 <                                    (ev = e.val) != null &&
1631 <                                    ((ek = e.key) == k || k.equals(ek))) {
1632 <                                    val = ev;
1633 <                                    break;
1634 <                                }
1635 <                                Node last = e;
1636 <                                if ((e = e.next) == null) {
1637 <                                    if ((val = mf.apply(k)) != null) {
1638 <                                        added = true;
1639 <                                        last.next = new Node(h, k, val, null);
1640 <                                        if (count >= TREE_THRESHOLD)
1641 <                                            replaceWithTreeBin(tab, i, k);
1642 <                                    }
1643 <                                    break;
1456 >                boolean added = false;
1457 >                synchronized (f) {
1458 >                    if (tabAt(tab, i) == f) {
1459 >                        len = 1;
1460 >                        for (Node<K,V> e = f;; ++len) {
1461 >                            Object ek; V ev;
1462 >                            if (e.hash == h &&
1463 >                                ((ek = e.key) == k || k.equals(ek))) {
1464 >                                val = e.val;
1465 >                                break;
1466 >                            }
1467 >                            Node<K,V> last = e;
1468 >                            if ((e = e.next) == null) {
1469 >                                if ((val = mf.apply(k)) != null) {
1470 >                                    added = true;
1471 >                                    last.next = new Node<K,V>(h, k, val, null);
1472 >                                    if (len > TREE_THRESHOLD)
1473 >                                        replaceWithTreeBin(tab, i, k);
1474                                  }
1475 +                                break;
1476                              }
1477                          }
1647                    } finally {
1648                        if (!f.casHash(fh | LOCKED, fh)) {
1649                            f.hash = fh;
1650                            synchronized (f) { f.notifyAll(); };
1651                        }
1652                    }
1653                    if (count != 0) {
1654                        if (!added)
1655                            return val;
1656                        if (tab.length <= 64)
1657                            count = 2;
1658                        break;
1478                      }
1479                  }
1480 +                if (len != 0) {
1481 +                    if (!added)
1482 +                        return val;
1483 +                    break;
1484 +                }
1485              }
1486          }
1487 <        if (val != null) {
1488 <            counter.add(1L);
1665 <            if (count > 1)
1666 <                checkForResize();
1667 <        }
1487 >        if (val != null)
1488 >            addCount(1L, len);
1489          return val;
1490      }
1491  
1492      /** Implementation for compute */
1493 <    @SuppressWarnings("unchecked") private final Object internalCompute
1494 <        (K k, boolean onlyIfPresent, BiFun<? super K, ? super V, ? extends V> mf) {
1493 >    private final V internalCompute(K k, boolean onlyIfPresent,
1494 >                                    BiFunction<? super K, ? super V, ? extends V> mf) {
1495 >        if (k == null || mf == null)
1496 >            throw new NullPointerException();
1497          int h = spread(k.hashCode());
1498 <        Object val = null;
1498 >        V val = null;
1499          int delta = 0;
1500 <        int count = 0;
1501 <        for (Node[] tab = table;;) {
1502 <            Node f; int i, fh; Object fk;
1500 >        int len = 0;
1501 >        for (Node<K,V>[] tab = table;;) {
1502 >            Node<K,V> f; int i, fh; Object fk;
1503              if (tab == null)
1504                  tab = initTable();
1505              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1506                  if (onlyIfPresent)
1507                      break;
1508 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1509 <                if (casTabAt(tab, i, null, node)) {
1510 <                    try {
1511 <                        count = 1;
1512 <                        if ((val = mf.apply(k, null)) != null) {
1513 <                            node.val = val;
1514 <                            delta = 1;
1515 <                        }
1516 <                    } finally {
1517 <                        if (delta == 0)
1518 <                            setTabAt(tab, i, null);
1519 <                        if (!node.casHash(fh, h)) {
1697 <                            node.hash = h;
1698 <                            synchronized (node) { node.notifyAll(); };
1508 >                Node<K,V> node = new Node<K,V>(h, k, null, null);
1509 >                synchronized (node) {
1510 >                    if (casTabAt(tab, i, null, node)) {
1511 >                        try {
1512 >                            len = 1;
1513 >                            if ((val = mf.apply(k, null)) != null) {
1514 >                                node.val = val;
1515 >                                delta = 1;
1516 >                            }
1517 >                        } finally {
1518 >                            if (delta == 0)
1519 >                                setTabAt(tab, i, null);
1520                          }
1521                      }
1522                  }
1523 <                if (count != 0)
1523 >                if (len != 0)
1524                      break;
1525              }
1526 <            else if ((fh = f.hash) == MOVED) {
1526 >            else if ((fh = f.hash) < 0) {
1527                  if ((fk = f.key) instanceof TreeBin) {
1528 <                    TreeBin t = (TreeBin)fk;
1529 <                    t.acquire(0);
1528 >                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1529 >                    long stamp = t.writeLock();
1530                      try {
1531                          if (tabAt(tab, i) == f) {
1532 <                            count = 1;
1533 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1534 <                            Object pv = (p == null) ? null : p.val;
1535 <                            if ((val = mf.apply(k, (V)pv)) != null) {
1536 <                                if (p != null)
1537 <                                    p.val = val;
1538 <                                else {
1539 <                                    count = 2;
1540 <                                    delta = 1;
1541 <                                    t.putTreeNode(h, k, val);
1532 >                            len = 2;
1533 >                            Class<?> cc = comparableClassFor(k);
1534 >                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
1535 >                            if (p != null || !onlyIfPresent) {
1536 >                                V pv = (p == null) ? null : p.val;
1537 >                                if ((val = mf.apply(k, pv)) != null) {
1538 >                                    if (p != null)
1539 >                                        p.val = val;
1540 >                                    else {
1541 >                                        delta = 1;
1542 >                                        t.putTreeNode(h, k, val);
1543 >                                    }
1544 >                                }
1545 >                                else if (p != null) {
1546 >                                    delta = -1;
1547 >                                    t.deleteTreeNode(p);
1548                                  }
1722                            }
1723                            else if (p != null) {
1724                                delta = -1;
1725                                t.deleteTreeNode(p);
1549                              }
1550                          }
1551                      } finally {
1552 <                        t.release(0);
1552 >                        t.unlockWrite(stamp);
1553                      }
1554 <                    if (count != 0)
1554 >                    if (len != 0)
1555                          break;
1556                  }
1557                  else
1558 <                    tab = (Node[])fk;
1736 <            }
1737 <            else if ((fh & LOCKED) != 0) {
1738 <                checkForResize();
1739 <                f.tryAwaitLock(tab, i);
1558 >                    tab = (Node<K,V>[])fk;
1559              }
1560 <            else if (f.casHash(fh, fh | LOCKED)) {
1561 <                try {
1560 >            else {
1561 >                synchronized (f) {
1562                      if (tabAt(tab, i) == f) {
1563 <                        count = 1;
1564 <                        for (Node e = f, pred = null;; ++count) {
1565 <                            Object ek, ev;
1566 <                            if ((e.hash & HASH_BITS) == h &&
1748 <                                (ev = e.val) != null &&
1563 >                        len = 1;
1564 >                        for (Node<K,V> e = f, pred = null;; ++len) {
1565 >                            Object ek;
1566 >                            if (e.hash == h &&
1567                                  ((ek = e.key) == k || k.equals(ek))) {
1568 <                                val = mf.apply(k, (V)ev);
1568 >                                val = mf.apply(k, e.val);
1569                                  if (val != null)
1570                                      e.val = val;
1571                                  else {
1572                                      delta = -1;
1573 <                                    Node en = e.next;
1573 >                                    Node<K,V> en = e.next;
1574                                      if (pred != null)
1575                                          pred.next = en;
1576                                      else
# Line 1762 | Line 1580 | public class ConcurrentHashMap<K, V>
1580                              }
1581                              pred = e;
1582                              if ((e = e.next) == null) {
1583 <                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1584 <                                    pred.next = new Node(h, k, val, null);
1583 >                                if (!onlyIfPresent &&
1584 >                                    (val = mf.apply(k, null)) != null) {
1585 >                                    pred.next = new Node<K,V>(h, k, val, null);
1586                                      delta = 1;
1587 <                                    if (count >= TREE_THRESHOLD)
1587 >                                    if (len > TREE_THRESHOLD)
1588                                          replaceWithTreeBin(tab, i, k);
1589                                  }
1590                                  break;
1591                              }
1592                          }
1593                      }
1775                } finally {
1776                    if (!f.casHash(fh | LOCKED, fh)) {
1777                        f.hash = fh;
1778                        synchronized (f) { f.notifyAll(); };
1779                    }
1594                  }
1595 <                if (count != 0) {
1782 <                    if (tab.length <= 64)
1783 <                        count = 2;
1595 >                if (len != 0)
1596                      break;
1785                }
1597              }
1598          }
1599 <        if (delta != 0) {
1600 <            counter.add((long)delta);
1790 <            if (count > 1)
1791 <                checkForResize();
1792 <        }
1599 >        if (delta != 0)
1600 >            addCount((long)delta, len);
1601          return val;
1602      }
1603  
1604      /** Implementation for merge */
1605 <    @SuppressWarnings("unchecked") private final Object internalMerge
1606 <        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1605 >    private final V internalMerge(K k, V v,
1606 >                                  BiFunction<? super V, ? super V, ? extends V> mf) {
1607 >        if (k == null || v == null || mf == null)
1608 >            throw new NullPointerException();
1609          int h = spread(k.hashCode());
1610 <        Object val = null;
1610 >        V val = null;
1611          int delta = 0;
1612 <        int count = 0;
1613 <        for (Node[] tab = table;;) {
1614 <            int i; Node f; int fh; Object fk, fv;
1612 >        int len = 0;
1613 >        for (Node<K,V>[] tab = table;;) {
1614 >            int i; Node<K,V> f; Object fk;
1615              if (tab == null)
1616                  tab = initTable();
1617              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1618 <                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1618 >                if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null))) {
1619                      delta = 1;
1620                      val = v;
1621                      break;
1622                  }
1623              }
1624 <            else if ((fh = f.hash) == MOVED) {
1624 >            else if (f.hash < 0) {
1625                  if ((fk = f.key) instanceof TreeBin) {
1626 <                    TreeBin t = (TreeBin)fk;
1627 <                    t.acquire(0);
1626 >                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1627 >                    long stamp = t.writeLock();
1628                      try {
1629                          if (tabAt(tab, i) == f) {
1630 <                            count = 1;
1631 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1632 <                            val = (p == null) ? v : mf.apply((V)p.val, v);
1630 >                            len = 2;
1631 >                            Class<?> cc = comparableClassFor(k);
1632 >                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
1633 >                            val = (p == null) ? v : mf.apply(p.val, v);
1634                              if (val != null) {
1635                                  if (p != null)
1636                                      p.val = val;
1637                                  else {
1827                                    count = 2;
1638                                      delta = 1;
1639                                      t.putTreeNode(h, k, val);
1640                                  }
# Line 1835 | Line 1645 | public class ConcurrentHashMap<K, V>
1645                              }
1646                          }
1647                      } finally {
1648 <                        t.release(0);
1648 >                        t.unlockWrite(stamp);
1649                      }
1650 <                    if (count != 0)
1650 >                    if (len != 0)
1651                          break;
1652                  }
1653                  else
1654 <                    tab = (Node[])fk;
1654 >                    tab = (Node<K,V>[])fk;
1655              }
1656 <            else if ((fh & LOCKED) != 0) {
1657 <                checkForResize();
1848 <                f.tryAwaitLock(tab, i);
1849 <            }
1850 <            else if (f.casHash(fh, fh | LOCKED)) {
1851 <                try {
1656 >            else {
1657 >                synchronized (f) {
1658                      if (tabAt(tab, i) == f) {
1659 <                        count = 1;
1660 <                        for (Node e = f, pred = null;; ++count) {
1661 <                            Object ek, ev;
1662 <                            if ((e.hash & HASH_BITS) == h &&
1857 <                                (ev = e.val) != null &&
1659 >                        len = 1;
1660 >                        for (Node<K,V> e = f, pred = null;; ++len) {
1661 >                            Object ek;
1662 >                            if (e.hash == h &&
1663                                  ((ek = e.key) == k || k.equals(ek))) {
1664 <                                val = mf.apply(v, (V)ev);
1664 >                                val = mf.apply(e.val, v);
1665                                  if (val != null)
1666                                      e.val = val;
1667                                  else {
1668                                      delta = -1;
1669 <                                    Node en = e.next;
1669 >                                    Node<K,V> en = e.next;
1670                                      if (pred != null)
1671                                          pred.next = en;
1672                                      else
# Line 1871 | Line 1676 | public class ConcurrentHashMap<K, V>
1676                              }
1677                              pred = e;
1678                              if ((e = e.next) == null) {
1874                                val = v;
1875                                pred.next = new Node(h, k, val, null);
1679                                  delta = 1;
1680 <                                if (count >= TREE_THRESHOLD)
1680 >                                val = v;
1681 >                                pred.next = new Node<K,V>(h, k, val, null);
1682 >                                if (len > TREE_THRESHOLD)
1683                                      replaceWithTreeBin(tab, i, k);
1684                                  break;
1685                              }
1686                          }
1687                      }
1883                } finally {
1884                    if (!f.casHash(fh | LOCKED, fh)) {
1885                        f.hash = fh;
1886                        synchronized (f) { f.notifyAll(); };
1887                    }
1688                  }
1689 <                if (count != 0) {
1890 <                    if (tab.length <= 64)
1891 <                        count = 2;
1689 >                if (len != 0)
1690                      break;
1893                }
1691              }
1692          }
1693 <        if (delta != 0) {
1694 <            counter.add((long)delta);
1898 <            if (count > 1)
1899 <                checkForResize();
1900 <        }
1693 >        if (delta != 0)
1694 >            addCount((long)delta, len);
1695          return val;
1696      }
1697  
1698      /** Implementation for putAll */
1699 <    private final void internalPutAll(Map<?, ?> m) {
1699 >    private final void internalPutAll(Map<? extends K, ? extends V> m) {
1700          tryPresize(m.size());
1701          long delta = 0L;     // number of uncommitted additions
1702          boolean npe = false; // to throw exception on exit for nulls
1703          try {                // to clean up counts on other exceptions
1704 <            for (Map.Entry<?, ?> entry : m.entrySet()) {
1705 <                Object k, v;
1704 >            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
1705 >                Object k; V v;
1706                  if (entry == null || (k = entry.getKey()) == null ||
1707                      (v = entry.getValue()) == null) {
1708                      npe = true;
1709                      break;
1710                  }
1711                  int h = spread(k.hashCode());
1712 <                for (Node[] tab = table;;) {
1713 <                    int i; Node f; int fh; Object fk;
1712 >                for (Node<K,V>[] tab = table;;) {
1713 >                    int i; Node<K,V> f; int fh; Object fk;
1714                      if (tab == null)
1715                          tab = initTable();
1716                      else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1717 <                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1717 >                        if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null))) {
1718                              ++delta;
1719                              break;
1720                          }
1721                      }
1722 <                    else if ((fh = f.hash) == MOVED) {
1722 >                    else if ((fh = f.hash) < 0) {
1723                          if ((fk = f.key) instanceof TreeBin) {
1724 <                            TreeBin t = (TreeBin)fk;
1724 >                            TreeBin<K,V> t = (TreeBin<K,V>)fk;
1725 >                            long stamp = t.writeLock();
1726                              boolean validated = false;
1932                            t.acquire(0);
1727                              try {
1728                                  if (tabAt(tab, i) == f) {
1729                                      validated = true;
1730 <                                    TreeNode p = t.getTreeNode(h, k, t.root);
1730 >                                    Class<?> cc = comparableClassFor(k);
1731 >                                    TreeNode<K,V> p = t.getTreeNode(h, k,
1732 >                                                                    t.root, cc);
1733                                      if (p != null)
1734                                          p.val = v;
1735                                      else {
1940                                        t.putTreeNode(h, k, v);
1736                                          ++delta;
1737 +                                        t.putTreeNode(h, k, v);
1738                                      }
1739                                  }
1740                              } finally {
1741 <                                t.release(0);
1741 >                                t.unlockWrite(stamp);
1742                              }
1743                              if (validated)
1744                                  break;
1745                          }
1746                          else
1747 <                            tab = (Node[])fk;
1952 <                    }
1953 <                    else if ((fh & LOCKED) != 0) {
1954 <                        counter.add(delta);
1955 <                        delta = 0L;
1956 <                        checkForResize();
1957 <                        f.tryAwaitLock(tab, i);
1747 >                            tab = (Node<K,V>[])fk;
1748                      }
1749 <                    else if (f.casHash(fh, fh | LOCKED)) {
1750 <                        int count = 0;
1751 <                        try {
1749 >                    else {
1750 >                        int len = 0;
1751 >                        synchronized (f) {
1752                              if (tabAt(tab, i) == f) {
1753 <                                count = 1;
1754 <                                for (Node e = f;; ++count) {
1755 <                                    Object ek, ev;
1756 <                                    if ((e.hash & HASH_BITS) == h &&
1967 <                                        (ev = e.val) != null &&
1753 >                                len = 1;
1754 >                                for (Node<K,V> e = f;; ++len) {
1755 >                                    Object ek;
1756 >                                    if (e.hash == h &&
1757                                          ((ek = e.key) == k || k.equals(ek))) {
1758                                          e.val = v;
1759                                          break;
1760                                      }
1761 <                                    Node last = e;
1761 >                                    Node<K,V> last = e;
1762                                      if ((e = e.next) == null) {
1763                                          ++delta;
1764 <                                        last.next = new Node(h, k, v, null);
1765 <                                        if (count >= TREE_THRESHOLD)
1764 >                                        last.next = new Node<K,V>(h, k, v, null);
1765 >                                        if (len > TREE_THRESHOLD)
1766                                              replaceWithTreeBin(tab, i, k);
1767                                          break;
1768                                      }
1769                                  }
1770                              }
1982                        } finally {
1983                            if (!f.casHash(fh | LOCKED, fh)) {
1984                                f.hash = fh;
1985                                synchronized (f) { f.notifyAll(); };
1986                            }
1771                          }
1772 <                        if (count != 0) {
1773 <                            if (count > 1) {
1774 <                                counter.add(delta);
1772 >                        if (len != 0) {
1773 >                            if (len > 1) {
1774 >                                addCount(delta, len);
1775                                  delta = 0L;
1992                                checkForResize();
1776                              }
1777                              break;
1778                          }
# Line 1997 | Line 1780 | public class ConcurrentHashMap<K, V>
1780                  }
1781              }
1782          } finally {
1783 <            if (delta != 0)
1784 <                counter.add(delta);
1783 >            if (delta != 0L)
1784 >                addCount(delta, 2);
1785          }
1786          if (npe)
1787              throw new NullPointerException();
1788      }
1789  
1790 +    /**
1791 +     * Implementation for clear. Steps through each bin, removing all
1792 +     * nodes.
1793 +     */
1794 +    private final void internalClear() {
1795 +        long delta = 0L; // negative number of deletions
1796 +        int i = 0;
1797 +        Node<K,V>[] tab = table;
1798 +        while (tab != null && i < tab.length) {
1799 +            Node<K,V> f = tabAt(tab, i);
1800 +            if (f == null)
1801 +                ++i;
1802 +            else if (f.hash < 0) {
1803 +                Object fk;
1804 +                if ((fk = f.key) instanceof TreeBin) {
1805 +                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1806 +                    long stamp = t.writeLock();
1807 +                    try {
1808 +                        if (tabAt(tab, i) == f) {
1809 +                            for (Node<K,V> p = t.first; p != null; p = p.next)
1810 +                                --delta;
1811 +                            t.first = null;
1812 +                            t.root = null;
1813 +                            ++i;
1814 +                        }
1815 +                    } finally {
1816 +                        t.unlockWrite(stamp);
1817 +                    }
1818 +                }
1819 +                else
1820 +                    tab = (Node<K,V>[])fk;
1821 +            }
1822 +            else {
1823 +                synchronized (f) {
1824 +                    if (tabAt(tab, i) == f) {
1825 +                        for (Node<K,V> e = f; e != null; e = e.next)
1826 +                            --delta;
1827 +                        setTabAt(tab, i, null);
1828 +                        ++i;
1829 +                    }
1830 +                }
1831 +            }
1832 +        }
1833 +        if (delta != 0L)
1834 +            addCount(delta, -1);
1835 +    }
1836 +
1837      /* ---------------- Table Initialization and Resizing -------------- */
1838  
1839      /**
# Line 2023 | Line 1853 | public class ConcurrentHashMap<K, V>
1853      /**
1854       * Initializes table, using the size recorded in sizeCtl.
1855       */
1856 <    private final Node[] initTable() {
1857 <        Node[] tab; int sc;
1856 >    private final Node<K,V>[] initTable() {
1857 >        Node<K,V>[] tab; int sc;
1858          while ((tab = table) == null) {
1859              if ((sc = sizeCtl) < 0)
1860                  Thread.yield(); // lost initialization race; just spin
1861 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1861 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1862                  try {
1863                      if ((tab = table) == null) {
1864                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1865 <                        tab = table = new Node[n];
1865 >                        table = tab = (Node<K,V>[])new Node[n];
1866                          sc = n - (n >>> 2);
1867                      }
1868                  } finally {
# Line 2045 | Line 1875 | public class ConcurrentHashMap<K, V>
1875      }
1876  
1877      /**
1878 <     * If table is too small and not already resizing, creates next
1879 <     * table and transfers bins.  Rechecks occupancy after a transfer
1880 <     * to see if another resize is already needed because resizings
1881 <     * are lagging additions.
1882 <     */
1883 <    private final void checkForResize() {
1884 <        Node[] tab; int n, sc;
1885 <        while ((tab = table) != null &&
1886 <               (n = tab.length) < MAXIMUM_CAPACITY &&
1887 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1888 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1889 <            try {
1890 <                if (tab == table) {
1891 <                    table = rebuild(tab);
1892 <                    sc = (n << 1) - (n >>> 1);
1878 >     * Adds to count, and if table is too small and not already
1879 >     * resizing, initiates transfer. If already resizing, helps
1880 >     * perform transfer if work is available.  Rechecks occupancy
1881 >     * after a transfer to see if another resize is already needed
1882 >     * because resizings are lagging additions.
1883 >     *
1884 >     * @param x the count to add
1885 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
1886 >     */
1887 >    private final void addCount(long x, int check) {
1888 >        Cell[] as; long b, s;
1889 >        if ((as = counterCells) != null ||
1890 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
1891 >            Cell a; long v; int m;
1892 >            boolean uncontended = true;
1893 >            if (as == null || (m = as.length - 1) < 0 ||
1894 >                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
1895 >                !(uncontended =
1896 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
1897 >                fullAddCount(x, uncontended);
1898 >                return;
1899 >            }
1900 >            if (check <= 1)
1901 >                return;
1902 >            s = sumCount();
1903 >        }
1904 >        if (check >= 0) {
1905 >            Node<K,V>[] tab, nt; int sc;
1906 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
1907 >                   tab.length < MAXIMUM_CAPACITY) {
1908 >                if (sc < 0) {
1909 >                    if (sc == -1 || transferIndex <= transferOrigin ||
1910 >                        (nt = nextTable) == null)
1911 >                        break;
1912 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
1913 >                        transfer(tab, nt);
1914                  }
1915 <            } finally {
1916 <                sizeCtl = sc;
1915 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
1916 >                    transfer(tab, null);
1917 >                s = sumCount();
1918              }
1919          }
1920      }
# Line 2077 | Line 1929 | public class ConcurrentHashMap<K, V>
1929              tableSizeFor(size + (size >>> 1) + 1);
1930          int sc;
1931          while ((sc = sizeCtl) >= 0) {
1932 <            Node[] tab = table; int n;
1932 >            Node<K,V>[] tab = table; int n;
1933              if (tab == null || (n = tab.length) == 0) {
1934                  n = (sc > c) ? sc : c;
1935 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1935 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1936                      try {
1937                          if (table == tab) {
1938 <                            table = new Node[n];
1938 >                            table = (Node<K,V>[])new Node[n];
1939                              sc = n - (n >>> 2);
1940                          }
1941                      } finally {
# Line 2093 | Line 1945 | public class ConcurrentHashMap<K, V>
1945              }
1946              else if (c <= sc || n >= MAXIMUM_CAPACITY)
1947                  break;
1948 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1949 <                try {
1950 <                    if (table == tab) {
2099 <                        table = rebuild(tab);
2100 <                        sc = (n << 1) - (n >>> 1);
2101 <                    }
2102 <                } finally {
2103 <                    sizeCtl = sc;
2104 <                }
2105 <            }
1948 >            else if (tab == table &&
1949 >                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
1950 >                transfer(tab, null);
1951          }
1952      }
1953  
1954 <    /*
1954 >    /**
1955       * Moves and/or copies the nodes in each bin to new table. See
1956       * above for explanation.
2112     *
2113     * @return the new table
1957       */
1958 <    private static final Node[] rebuild(Node[] tab) {
1959 <        int n = tab.length;
1960 <        Node[] nextTab = new Node[n << 1];
1961 <        Node fwd = new Node(MOVED, nextTab, null, null);
1962 <        int[] buffer = null;       // holds bins to revisit; null until needed
1963 <        Node rev = null;           // reverse forwarder; null until needed
1964 <        int nbuffered = 0;         // the number of bins in buffer list
1965 <        int bufferIndex = 0;       // buffer index of current buffered bin
1966 <        int bin = n - 1;           // current non-buffered bin or -1 if none
1967 <
1968 <        for (int i = bin;;) {      // start upwards sweep
1969 <            int fh; Node f;
1970 <            if ((f = tabAt(tab, i)) == null) {
1971 <                if (bin >= 0) {    // Unbuffered; no lock needed (or available)
1972 <                    if (!casTabAt(tab, i, f, fwd))
1973 <                        continue;
1958 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
1959 >        int n = tab.length, stride;
1960 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
1961 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
1962 >        if (nextTab == null) {            // initiating
1963 >            try {
1964 >                nextTab = (Node<K,V>[])new Node[n << 1];
1965 >            } catch (Throwable ex) {      // try to cope with OOME
1966 >                sizeCtl = Integer.MAX_VALUE;
1967 >                return;
1968 >            }
1969 >            nextTable = nextTab;
1970 >            transferOrigin = n;
1971 >            transferIndex = n;
1972 >            Node<K,V> rev = new Node<K,V>(MOVED, tab, null, null);
1973 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
1974 >                int nextk = (k > stride) ? k - stride : 0;
1975 >                for (int m = nextk; m < k; ++m)
1976 >                    nextTab[m] = rev;
1977 >                for (int m = n + nextk; m < n + k; ++m)
1978 >                    nextTab[m] = rev;
1979 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
1980 >            }
1981 >        }
1982 >        int nextn = nextTab.length;
1983 >        Node<K,V> fwd = new Node<K,V>(MOVED, nextTab, null, null);
1984 >        boolean advance = true;
1985 >        for (int i = 0, bound = 0;;) {
1986 >            int nextIndex, nextBound; Node<K,V> f; Object fk;
1987 >            while (advance) {
1988 >                if (--i >= bound)
1989 >                    advance = false;
1990 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
1991 >                    i = -1;
1992 >                    advance = false;
1993 >                }
1994 >                else if (U.compareAndSwapInt
1995 >                         (this, TRANSFERINDEX, nextIndex,
1996 >                          nextBound = (nextIndex > stride ?
1997 >                                       nextIndex - stride : 0))) {
1998 >                    bound = nextBound;
1999 >                    i = nextIndex - 1;
2000 >                    advance = false;
2001 >                }
2002 >            }
2003 >            if (i < 0 || i >= n || i + n >= nextn) {
2004 >                for (int sc;;) {
2005 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2006 >                        if (sc == -1) {
2007 >                            nextTable = null;
2008 >                            table = nextTab;
2009 >                            sizeCtl = (n << 1) - (n >>> 1);
2010 >                        }
2011 >                        return;
2012 >                    }
2013                  }
2014 <                else {             // transiently use a locked forwarding node
2015 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2016 <                    if (!casTabAt(tab, i, f, g))
2135 <                        continue;
2014 >            }
2015 >            else if ((f = tabAt(tab, i)) == null) {
2016 >                if (casTabAt(tab, i, null, fwd)) {
2017                      setTabAt(nextTab, i, null);
2018                      setTabAt(nextTab, i + n, null);
2019 <                    setTabAt(tab, i, fwd);
2139 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2140 <                        g.hash = MOVED;
2141 <                        synchronized (g) { g.notifyAll(); }
2142 <                    }
2019 >                    advance = true;
2020                  }
2021              }
2022 <            else if ((fh = f.hash) == MOVED) {
2023 <                Object fk = f.key;
2024 <                if (fk instanceof TreeBin) {
2025 <                    TreeBin t = (TreeBin)fk;
2026 <                    boolean validated = false;
2027 <                    t.acquire(0);
2028 <                    try {
2029 <                        if (tabAt(tab, i) == f) {
2030 <                            validated = true;
2031 <                            splitTreeBin(nextTab, i, t);
2032 <                            setTabAt(tab, i, fwd);
2022 >            else if (f.hash >= 0) {
2023 >                synchronized (f) {
2024 >                    if (tabAt(tab, i) == f) {
2025 >                        int runBit = f.hash & n;
2026 >                        Node<K,V> lastRun = f, lo = null, hi = null;
2027 >                        for (Node<K,V> p = f.next; p != null; p = p.next) {
2028 >                            int b = p.hash & n;
2029 >                            if (b != runBit) {
2030 >                                runBit = b;
2031 >                                lastRun = p;
2032 >                            }
2033                          }
2034 <                    } finally {
2035 <                        t.release(0);
2034 >                        if (runBit == 0)
2035 >                            lo = lastRun;
2036 >                        else
2037 >                            hi = lastRun;
2038 >                        for (Node<K,V> p = f; p != lastRun; p = p.next) {
2039 >                            int ph = p.hash; Object pk = p.key; V pv = p.val;
2040 >                            if ((ph & n) == 0)
2041 >                                lo = new Node<K,V>(ph, pk, pv, lo);
2042 >                            else
2043 >                                hi = new Node<K,V>(ph, pk, pv, hi);
2044 >                        }
2045 >                        setTabAt(nextTab, i, lo);
2046 >                        setTabAt(nextTab, i + n, hi);
2047 >                        setTabAt(tab, i, fwd);
2048 >                        advance = true;
2049                      }
2160                    if (!validated)
2161                        continue;
2050                  }
2051              }
2052 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2053 <                boolean validated = false;
2054 <                try {              // split to lo and hi lists; copying as needed
2052 >            else if ((fk = f.key) instanceof TreeBin) {
2053 >                TreeBin<K,V> t = (TreeBin<K,V>)fk;
2054 >                long stamp = t.writeLock();
2055 >                try {
2056                      if (tabAt(tab, i) == f) {
2057 <                        validated = true;
2058 <                        splitBin(nextTab, i, f);
2057 >                        TreeNode<K,V> root;
2058 >                        Node<K,V> ln = null, hn = null;
2059 >                        if ((root = t.root) != null) {
2060 >                            Node<K,V> e, p; TreeNode<K,V> lr, rr; int lh;
2061 >                            TreeBin<K,V> lt = null, ht = null;
2062 >                            for (lr = root; lr.left != null; lr = lr.left);
2063 >                            for (rr = root; rr.right != null; rr = rr.right);
2064 >                            if ((lh = lr.hash) == rr.hash) { // move entire tree
2065 >                                if ((lh & n) == 0)
2066 >                                    lt = t;
2067 >                                else
2068 >                                    ht = t;
2069 >                            }
2070 >                            else {
2071 >                                lt = new TreeBin<K,V>();
2072 >                                ht = new TreeBin<K,V>();
2073 >                                int lc = 0, hc = 0;
2074 >                                for (e = t.first; e != null; e = e.next) {
2075 >                                    int h = e.hash;
2076 >                                    Object k = e.key; V v = e.val;
2077 >                                    if ((h & n) == 0) {
2078 >                                        ++lc;
2079 >                                        lt.putTreeNode(h, k, v);
2080 >                                    }
2081 >                                    else {
2082 >                                        ++hc;
2083 >                                        ht.putTreeNode(h, k, v);
2084 >                                    }
2085 >                                }
2086 >                                if (lc < TREE_THRESHOLD) { // throw away
2087 >                                    for (p = lt.first; p != null; p = p.next)
2088 >                                        ln = new Node<K,V>(p.hash, p.key,
2089 >                                                           p.val, ln);
2090 >                                    lt = null;
2091 >                                }
2092 >                                if (hc < TREE_THRESHOLD) {
2093 >                                    for (p = ht.first; p != null; p = p.next)
2094 >                                        hn = new Node<K,V>(p.hash, p.key,
2095 >                                                           p.val, hn);
2096 >                                    ht = null;
2097 >                                }
2098 >                            }
2099 >                            if (ln == null && lt != null)
2100 >                                ln = new Node<K,V>(MOVED, lt, null, null);
2101 >                            if (hn == null && ht != null)
2102 >                                hn = new Node<K,V>(MOVED, ht, null, null);
2103 >                        }
2104 >                        setTabAt(nextTab, i, ln);
2105 >                        setTabAt(nextTab, i + n, hn);
2106                          setTabAt(tab, i, fwd);
2107 +                        advance = true;
2108                      }
2109                  } finally {
2110 <                    if (!f.casHash(fh | LOCKED, fh)) {
2174 <                        f.hash = fh;
2175 <                        synchronized (f) { f.notifyAll(); };
2176 <                    }
2110 >                    t.unlockWrite(stamp);
2111                  }
2178                if (!validated)
2179                    continue;
2180            }
2181            else {
2182                if (buffer == null) // initialize buffer for revisits
2183                    buffer = new int[TRANSFER_BUFFER_SIZE];
2184                if (bin < 0 && bufferIndex > 0) {
2185                    int j = buffer[--bufferIndex];
2186                    buffer[bufferIndex] = i;
2187                    i = j;         // swap with another bin
2188                    continue;
2189                }
2190                if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
2191                    f.tryAwaitLock(tab, i);
2192                    continue;      // no other options -- block
2193                }
2194                if (rev == null)   // initialize reverse-forwarder
2195                    rev = new Node(MOVED, tab, null, null);
2196                if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
2197                    continue;      // recheck before adding to list
2198                buffer[nbuffered++] = i;
2199                setTabAt(nextTab, i, rev);     // install place-holders
2200                setTabAt(nextTab, i + n, rev);
2201            }
2202
2203            if (bin > 0)
2204                i = --bin;
2205            else if (buffer != null && nbuffered > 0) {
2206                bin = -1;
2207                i = buffer[bufferIndex = --nbuffered];
2112              }
2113              else
2114 <                return nextTab;
2114 >                advance = true; // already processed
2115          }
2116      }
2117  
2118 <    /**
2215 <     * Splits a normal bin with list headed by e into lo and hi parts;
2216 <     * installs in given table.
2217 <     */
2218 <    private static void splitBin(Node[] nextTab, int i, Node e) {
2219 <        int bit = nextTab.length >>> 1; // bit to split on
2220 <        int runBit = e.hash & bit;
2221 <        Node lastRun = e, lo = null, hi = null;
2222 <        for (Node p = e.next; p != null; p = p.next) {
2223 <            int b = p.hash & bit;
2224 <            if (b != runBit) {
2225 <                runBit = b;
2226 <                lastRun = p;
2227 <            }
2228 <        }
2229 <        if (runBit == 0)
2230 <            lo = lastRun;
2231 <        else
2232 <            hi = lastRun;
2233 <        for (Node p = e; p != lastRun; p = p.next) {
2234 <            int ph = p.hash & HASH_BITS;
2235 <            Object pk = p.key, pv = p.val;
2236 <            if ((ph & bit) == 0)
2237 <                lo = new Node(ph, pk, pv, lo);
2238 <            else
2239 <                hi = new Node(ph, pk, pv, hi);
2240 <        }
2241 <        setTabAt(nextTab, i, lo);
2242 <        setTabAt(nextTab, i + bit, hi);
2243 <    }
2118 >    /* ---------------- Counter support -------------- */
2119  
2120 <    /**
2121 <     * Splits a tree bin into lo and hi parts; installs in given table.
2122 <     */
2123 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2124 <        int bit = nextTab.length >>> 1;
2125 <        TreeBin lt = new TreeBin();
2126 <        TreeBin ht = new TreeBin();
2252 <        int lc = 0, hc = 0;
2253 <        for (Node e = t.first; e != null; e = e.next) {
2254 <            int h = e.hash & HASH_BITS;
2255 <            Object k = e.key, v = e.val;
2256 <            if ((h & bit) == 0) {
2257 <                ++lc;
2258 <                lt.putTreeNode(h, k, v);
2259 <            }
2260 <            else {
2261 <                ++hc;
2262 <                ht.putTreeNode(h, k, v);
2120 >    final long sumCount() {
2121 >        Cell[] as = counterCells; Cell a;
2122 >        long sum = baseCount;
2123 >        if (as != null) {
2124 >            for (int i = 0; i < as.length; ++i) {
2125 >                if ((a = as[i]) != null)
2126 >                    sum += a.value;
2127              }
2128          }
2129 <        Node ln, hn; // throw away trees if too small
2266 <        if (lc <= (TREE_THRESHOLD >>> 1)) {
2267 <            ln = null;
2268 <            for (Node p = lt.first; p != null; p = p.next)
2269 <                ln = new Node(p.hash, p.key, p.val, ln);
2270 <        }
2271 <        else
2272 <            ln = new Node(MOVED, lt, null, null);
2273 <        setTabAt(nextTab, i, ln);
2274 <        if (hc <= (TREE_THRESHOLD >>> 1)) {
2275 <            hn = null;
2276 <            for (Node p = ht.first; p != null; p = p.next)
2277 <                hn = new Node(p.hash, p.key, p.val, hn);
2278 <        }
2279 <        else
2280 <            hn = new Node(MOVED, ht, null, null);
2281 <        setTabAt(nextTab, i + bit, hn);
2129 >        return sum;
2130      }
2131  
2132 <    /**
2133 <     * Implementation for clear. Steps through each bin, removing all
2134 <     * nodes.
2135 <     */
2136 <    private final void internalClear() {
2137 <        long delta = 0L; // negative number of deletions
2138 <        int i = 0;
2139 <        Node[] tab = table;
2140 <        while (tab != null && i < tab.length) {
2141 <            int fh; Object fk;
2142 <            Node f = tabAt(tab, i);
2143 <            if (f == null)
2144 <                ++i;
2145 <            else if ((fh = f.hash) == MOVED) {
2146 <                if ((fk = f.key) instanceof TreeBin) {
2147 <                    TreeBin t = (TreeBin)fk;
2148 <                    t.acquire(0);
2149 <                    try {
2150 <                        if (tabAt(tab, i) == f) {
2151 <                            for (Node p = t.first; p != null; p = p.next) {
2152 <                                if (p.val != null) { // (currently always true)
2153 <                                    p.val = null;
2154 <                                    --delta;
2132 >    // See LongAdder version for explanation
2133 >    private final void fullAddCount(long x, boolean wasUncontended) {
2134 >        int h;
2135 >        if ((h = ThreadLocalRandom.getProbe()) == 0) {
2136 >            ThreadLocalRandom.localInit();      // force initialization
2137 >            h = ThreadLocalRandom.getProbe();
2138 >            wasUncontended = true;
2139 >        }
2140 >        boolean collide = false;                // True if last slot nonempty
2141 >        for (;;) {
2142 >            Cell[] as; Cell a; int n; long v;
2143 >            if ((as = counterCells) != null && (n = as.length) > 0) {
2144 >                if ((a = as[(n - 1) & h]) == null) {
2145 >                    if (cellsBusy == 0) {            // Try to attach new Cell
2146 >                        Cell r = new Cell(x); // Optimistic create
2147 >                        if (cellsBusy == 0 &&
2148 >                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2149 >                            boolean created = false;
2150 >                            try {               // Recheck under lock
2151 >                                Cell[] rs; int m, j;
2152 >                                if ((rs = counterCells) != null &&
2153 >                                    (m = rs.length) > 0 &&
2154 >                                    rs[j = (m - 1) & h] == null) {
2155 >                                    rs[j] = r;
2156 >                                    created = true;
2157                                  }
2158 +                            } finally {
2159 +                                cellsBusy = 0;
2160                              }
2161 <                            t.first = null;
2162 <                            t.root = null;
2163 <                            ++i;
2161 >                            if (created)
2162 >                                break;
2163 >                            continue;           // Slot is now non-empty
2164 >                        }
2165 >                    }
2166 >                    collide = false;
2167 >                }
2168 >                else if (!wasUncontended)       // CAS already known to fail
2169 >                    wasUncontended = true;      // Continue after rehash
2170 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2171 >                    break;
2172 >                else if (counterCells != as || n >= NCPU)
2173 >                    collide = false;            // At max size or stale
2174 >                else if (!collide)
2175 >                    collide = true;
2176 >                else if (cellsBusy == 0 &&
2177 >                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2178 >                    try {
2179 >                        if (counterCells == as) {// Expand table unless stale
2180 >                            Cell[] rs = new Cell[n << 1];
2181 >                            for (int i = 0; i < n; ++i)
2182 >                                rs[i] = as[i];
2183 >                            counterCells = rs;
2184                          }
2185                      } finally {
2186 <                        t.release(0);
2186 >                        cellsBusy = 0;
2187                      }
2188 +                    collide = false;
2189 +                    continue;                   // Retry with expanded table
2190                  }
2191 <                else
2318 <                    tab = (Node[])fk;
2319 <            }
2320 <            else if ((fh & LOCKED) != 0) {
2321 <                counter.add(delta); // opportunistically update count
2322 <                delta = 0L;
2323 <                f.tryAwaitLock(tab, i);
2191 >                h = ThreadLocalRandom.advanceProbe(h);
2192              }
2193 <            else if (f.casHash(fh, fh | LOCKED)) {
2194 <                try {
2195 <                    if (tabAt(tab, i) == f) {
2196 <                        for (Node e = f; e != null; e = e.next) {
2197 <                            if (e.val != null) {  // (currently always true)
2198 <                                e.val = null;
2199 <                                --delta;
2200 <                            }
2201 <                        }
2334 <                        setTabAt(tab, i, null);
2335 <                        ++i;
2193 >            else if (cellsBusy == 0 && counterCells == as &&
2194 >                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2195 >                boolean init = false;
2196 >                try {                           // Initialize table
2197 >                    if (counterCells == as) {
2198 >                        Cell[] rs = new Cell[2];
2199 >                        rs[h & 1] = new Cell(x);
2200 >                        counterCells = rs;
2201 >                        init = true;
2202                      }
2203                  } finally {
2204 <                    if (!f.casHash(fh | LOCKED, fh)) {
2339 <                        f.hash = fh;
2340 <                        synchronized (f) { f.notifyAll(); };
2341 <                    }
2204 >                    cellsBusy = 0;
2205                  }
2206 +                if (init)
2207 +                    break;
2208              }
2209 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2210 +                break;                          // Fall back on using base
2211          }
2345        if (delta != 0)
2346            counter.add(delta);
2212      }
2213  
2214      /* ----------------Table Traversal -------------- */
2215  
2216      /**
2217       * Encapsulates traversal for methods such as containsValue; also
2218 <     * serves as a base class for other iterators and bulk tasks.
2218 >     * serves as a base class for other iterators and spliterators.
2219       *
2220 <     * At each step, the iterator snapshots the key ("nextKey") and
2356 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2357 <     * snapshot, has a non-null user value). Because val fields can
2358 <     * change (including to null, indicating deletion), field nextVal
2359 <     * might not be accurate at point of use, but still maintains the
2360 <     * weak consistency property of holding a value that was once
2361 <     * valid. To support iterator.remove, the nextKey field is not
2362 <     * updated (nulled out) when the iterator cannot advance.
2363 <     *
2364 <     * Internal traversals directly access these fields, as in:
2365 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2366 <     *
2367 <     * Exported iterators must track whether the iterator has advanced
2368 <     * (in hasNext vs next) (by setting/checking/nulling field
2369 <     * nextVal), and then extract key, value, or key-value pairs as
2370 <     * return values of next().
2371 <     *
2372 <     * The iterator visits once each still-valid node that was
2220 >     * Method advance visits once each still-valid node that was
2221       * reachable upon iterator construction. It might miss some that
2222       * were added to a bin after the bin was visited, which is OK wrt
2223       * consistency guarantees. Maintaining this property in the face
# Line 2385 | Line 2233 | public class ConcurrentHashMap<K, V>
2233       * paranoically cope with potential sharing by users of iterators
2234       * across threads, iteration terminates if a bounds checks fails
2235       * for a table read.
2236 <     *
2237 <     * This class extends ForkJoinTask to streamline parallel
2238 <     * iteration in bulk operations (see BulkTask). This adds only an
2239 <     * int of space overhead, which is close enough to negligible in
2240 <     * cases where it is not needed to not worry about it.  Because
2241 <     * ForkJoinTask is Serializable, but iterators need not be, we
2242 <     * need to add warning suppressions.
2243 <     */
2244 <    @SuppressWarnings("serial") static class Traverser<K,V,R> extends ForkJoinTask<R> {
2245 <        final ConcurrentHashMap<K, V> map;
2246 <        Node next;           // the next entry to use
2247 <        Object nextKey;      // cached key field of next
2248 <        Object nextVal;      // cached val field of next
2249 <        Node[] tab;          // current table; updated if resized
2250 <        int index;           // index of bin to use next
2403 <        int baseIndex;       // current index of initial table
2404 <        int baseLimit;       // index bound for initial table
2405 <        int baseSize;        // initial table size
2406 <
2407 <        /** Creates iterator for all entries in the table. */
2408 <        Traverser(ConcurrentHashMap<K, V> map) {
2409 <            this.map = map;
2410 <        }
2411 <
2412 <        /** Creates iterator for split() methods */
2413 <        Traverser(Traverser<K,V,?> it) {
2414 <            ConcurrentHashMap<K, V> m; Node[] t;
2415 <            if ((m = this.map = it.map) == null)
2416 <                t = null;
2417 <            else if ((t = it.tab) == null && // force parent tab initialization
2418 <                     (t = it.tab = m.table) != null)
2419 <                it.baseLimit = it.baseSize = t.length;
2420 <            this.tab = t;
2421 <            this.baseSize = it.baseSize;
2422 <            it.baseLimit = this.index = this.baseIndex =
2423 <                ((this.baseLimit = it.baseLimit) + it.baseIndex + 1) >>> 1;
2236 >     */
2237 >    static class Traverser<K,V> {
2238 >        Node<K,V>[] tab;        // current table; updated if resized
2239 >        Node<K,V> next;         // the next entry to use
2240 >        int index;              // index of bin to use next
2241 >        int baseIndex;          // current index of initial table
2242 >        int baseLimit;          // index bound for initial table
2243 >        final int baseSize;     // initial table size
2244 >
2245 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
2246 >            this.tab = tab;
2247 >            this.baseSize = size;
2248 >            this.baseIndex = this.index = index;
2249 >            this.baseLimit = limit;
2250 >            this.next = null;
2251          }
2252  
2253          /**
2254 <         * Advances next; returns nextVal or null if terminated.
2255 <         * See above for explanation.
2256 <         */
2257 <        final Object advance() {
2258 <            Node e = next;
2259 <            Object ev = null;
2260 <            outer: do {
2261 <                if (e != null)                  // advance past used/skipped node
2262 <                    e = e.next;
2263 <                while (e == null) {             // get to next non-null bin
2264 <                    ConcurrentHashMap<K, V> m;
2265 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2266 <                    if ((t = tab) != null)
2267 <                        n = t.length;
2268 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2269 <                        n = baseLimit = baseSize = t.length;
2270 <                    else
2271 <                        break outer;
2272 <                    if ((b = baseIndex) >= baseLimit ||
2273 <                        (i = index) < 0 || i >= n)
2274 <                        break outer;
2448 <                    if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2449 <                        if ((ek = e.key) instanceof TreeBin)
2450 <                            e = ((TreeBin)ek).first;
2451 <                        else {
2452 <                            tab = (Node[])ek;
2453 <                            continue;           // restarts due to null val
2454 <                        }
2455 <                    }                           // visit upper slots if present
2456 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2254 >         * Advances if possible, returning next valid node, or null if none.
2255 >         */
2256 >        final Node<K,V> advance() {
2257 >            Node<K,V> e;
2258 >            if ((e = next) != null)
2259 >                e = e.next;
2260 >            for (;;) {
2261 >                Node<K,V>[] t; int i, n; Object ek;  // must use locals in checks
2262 >                if (e != null)
2263 >                    return next = e;
2264 >                if (baseIndex >= baseLimit || (t = tab) == null ||
2265 >                    (n = t.length) <= (i = index) || i < 0)
2266 >                    return next = null;
2267 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
2268 >                    if ((ek = e.key) instanceof TreeBin)
2269 >                        e = ((TreeBin<K,V>)ek).first;
2270 >                    else {
2271 >                        tab = (Node<K,V>[])ek;
2272 >                        e = null;
2273 >                        continue;
2274 >                    }
2275                  }
2276 <                nextKey = e.key;
2277 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2278 <            next = e;
2461 <            return nextVal = ev;
2276 >                if ((index += baseSize) >= n)
2277 >                    index = ++baseIndex;    // visit upper slots if present
2278 >            }
2279          }
2280 +    }
2281 +
2282 +    /**
2283 +     * Base of key, value, and entry Iterators. Adds fields to
2284 +     * Traverser to support iterator.remove
2285 +     */
2286 +    static class BaseIterator<K,V> extends Traverser<K,V> {
2287 +        final ConcurrentHashMap<K,V> map;
2288 +        Node<K,V> lastReturned;
2289 +        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
2290 +                    ConcurrentHashMap<K,V> map) {
2291 +            super(tab, size, index, limit);
2292 +            this.map = map;
2293 +            advance();
2294 +        }
2295 +
2296 +        public final boolean hasNext() { return next != null; }
2297 +        public final boolean hasMoreElements() { return next != null; }
2298  
2299          public final void remove() {
2300 <            Object k = nextKey;
2301 <            if (k == null && (advance() == null || (k = nextKey) == null))
2300 >            Node<K,V> p;
2301 >            if ((p = lastReturned) == null)
2302                  throw new IllegalStateException();
2303 <            map.internalReplace(k, null, null);
2303 >            lastReturned = null;
2304 >            map.internalReplace((K)p.key, null, null);
2305 >        }
2306 >    }
2307 >
2308 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
2309 >        implements Iterator<K>, Enumeration<K> {
2310 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
2311 >                    ConcurrentHashMap<K,V> map) {
2312 >            super(tab, index, size, limit, map);
2313 >        }
2314 >
2315 >        public final K next() {
2316 >            Node<K,V> p;
2317 >            if ((p = next) == null)
2318 >                throw new NoSuchElementException();
2319 >            K k = (K)p.key;
2320 >            lastReturned = p;
2321 >            advance();
2322 >            return k;
2323 >        }
2324 >
2325 >        public final K nextElement() { return next(); }
2326 >    }
2327 >
2328 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
2329 >        implements Iterator<V>, Enumeration<V> {
2330 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
2331 >                      ConcurrentHashMap<K,V> map) {
2332 >            super(tab, index, size, limit, map);
2333 >        }
2334 >
2335 >        public final V next() {
2336 >            Node<K,V> p;
2337 >            if ((p = next) == null)
2338 >                throw new NoSuchElementException();
2339 >            V v = p.val;
2340 >            lastReturned = p;
2341 >            advance();
2342 >            return v;
2343 >        }
2344 >
2345 >        public final V nextElement() { return next(); }
2346 >    }
2347 >
2348 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
2349 >        implements Iterator<Map.Entry<K,V>> {
2350 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
2351 >                      ConcurrentHashMap<K,V> map) {
2352 >            super(tab, index, size, limit, map);
2353 >        }
2354 >
2355 >        public final Map.Entry<K,V> next() {
2356 >            Node<K,V> p;
2357 >            if ((p = next) == null)
2358 >                throw new NoSuchElementException();
2359 >            K k = (K)p.key;
2360 >            V v = p.val;
2361 >            lastReturned = p;
2362 >            advance();
2363 >            return new MapEntry<K,V>(k, v, map);
2364 >        }
2365 >    }
2366 >
2367 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
2368 >        implements Spliterator<K> {
2369 >        long est;               // size estimate
2370 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
2371 >                       long est) {
2372 >            super(tab, size, index, limit);
2373 >            this.est = est;
2374 >        }
2375 >
2376 >        public Spliterator<K> trySplit() {
2377 >            int i, f, h;
2378 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
2379 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
2380 >                                        f, est >>>= 1);
2381 >        }
2382 >
2383 >        public void forEachRemaining(Consumer<? super K> action) {
2384 >            if (action == null) throw new NullPointerException();
2385 >            for (Node<K,V> p; (p = advance()) != null;)
2386 >                action.accept((K)p.key);
2387 >        }
2388 >
2389 >        public boolean tryAdvance(Consumer<? super K> action) {
2390 >            if (action == null) throw new NullPointerException();
2391 >            Node<K,V> p;
2392 >            if ((p = advance()) == null)
2393 >                return false;
2394 >            action.accept((K)p.key);
2395 >            return true;
2396 >        }
2397 >
2398 >        public long estimateSize() { return est; }
2399 >
2400 >        public int characteristics() {
2401 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
2402 >                Spliterator.NONNULL;
2403 >        }
2404 >    }
2405 >
2406 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
2407 >        implements Spliterator<V> {
2408 >        long est;               // size estimate
2409 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
2410 >                         long est) {
2411 >            super(tab, size, index, limit);
2412 >            this.est = est;
2413 >        }
2414 >
2415 >        public Spliterator<V> trySplit() {
2416 >            int i, f, h;
2417 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
2418 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
2419 >                                          f, est >>>= 1);
2420 >        }
2421 >
2422 >        public void forEachRemaining(Consumer<? super V> action) {
2423 >            if (action == null) throw new NullPointerException();
2424 >            for (Node<K,V> p; (p = advance()) != null;)
2425 >                action.accept(p.val);
2426 >        }
2427 >
2428 >        public boolean tryAdvance(Consumer<? super V> action) {
2429 >            if (action == null) throw new NullPointerException();
2430 >            Node<K,V> p;
2431 >            if ((p = advance()) == null)
2432 >                return false;
2433 >            action.accept(p.val);
2434 >            return true;
2435 >        }
2436 >
2437 >        public long estimateSize() { return est; }
2438 >
2439 >        public int characteristics() {
2440 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
2441 >        }
2442 >    }
2443 >
2444 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
2445 >        implements Spliterator<Map.Entry<K,V>> {
2446 >        final ConcurrentHashMap<K,V> map; // To export MapEntry
2447 >        long est;               // size estimate
2448 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
2449 >                         long est, ConcurrentHashMap<K,V> map) {
2450 >            super(tab, size, index, limit);
2451 >            this.map = map;
2452 >            this.est = est;
2453          }
2454  
2455 <        public final boolean hasNext() {
2456 <            return nextVal != null || advance() != null;
2455 >        public Spliterator<Map.Entry<K,V>> trySplit() {
2456 >            int i, f, h;
2457 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
2458 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
2459 >                                          f, est >>>= 1, map);
2460          }
2461  
2462 <        public final boolean hasMoreElements() { return hasNext(); }
2463 <        public final void setRawResult(Object x) { }
2464 <        public R getRawResult() { return null; }
2465 <        public boolean exec() { return true; }
2462 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
2463 >            if (action == null) throw new NullPointerException();
2464 >            for (Node<K,V> p; (p = advance()) != null; )
2465 >                action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
2466 >        }
2467 >
2468 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
2469 >            if (action == null) throw new NullPointerException();
2470 >            Node<K,V> p;
2471 >            if ((p = advance()) == null)
2472 >                return false;
2473 >            action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
2474 >            return true;
2475 >        }
2476 >
2477 >        public long estimateSize() { return est; }
2478 >
2479 >        public int characteristics() {
2480 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
2481 >                Spliterator.NONNULL;
2482 >        }
2483      }
2484  
2485 +
2486      /* ---------------- Public operations -------------- */
2487  
2488      /**
2489       * Creates a new, empty map with the default initial table size (16).
2490       */
2491      public ConcurrentHashMap() {
2487        this.counter = new LongAdder();
2492      }
2493  
2494      /**
# Line 2503 | Line 2507 | public class ConcurrentHashMap<K, V>
2507          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2508                     MAXIMUM_CAPACITY :
2509                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2506        this.counter = new LongAdder();
2510          this.sizeCtl = cap;
2511      }
2512  
# Line 2513 | Line 2516 | public class ConcurrentHashMap<K, V>
2516       * @param m the map
2517       */
2518      public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2516        this.counter = new LongAdder();
2519          this.sizeCtl = DEFAULT_CAPACITY;
2520          internalPutAll(m);
2521      }
# Line 2556 | Line 2558 | public class ConcurrentHashMap<K, V>
2558       * nonpositive
2559       */
2560      public ConcurrentHashMap(int initialCapacity,
2561 <                               float loadFactor, int concurrencyLevel) {
2561 >                             float loadFactor, int concurrencyLevel) {
2562          if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2563              throw new IllegalArgumentException();
2564          if (initialCapacity < concurrencyLevel)   // Use at least as many bins
# Line 2564 | Line 2566 | public class ConcurrentHashMap<K, V>
2566          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2567          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2568              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2567        this.counter = new LongAdder();
2569          this.sizeCtl = cap;
2570      }
2571  
# Line 2575 | Line 2576 | public class ConcurrentHashMap<K, V>
2576       * @return the new set
2577       */
2578      public static <K> KeySetView<K,Boolean> newKeySet() {
2579 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(),
2580 <                                      Boolean.TRUE);
2579 >        return new KeySetView<K,Boolean>
2580 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2581      }
2582  
2583      /**
# Line 2590 | Line 2591 | public class ConcurrentHashMap<K, V>
2591       * @return the new set
2592       */
2593      public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2594 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(initialCapacity),
2595 <                                      Boolean.TRUE);
2594 >        return new KeySetView<K,Boolean>
2595 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2596      }
2597  
2598      /**
2599       * {@inheritDoc}
2600       */
2601      public boolean isEmpty() {
2602 <        return counter.sum() <= 0L; // ignore transient negative values
2602 >        return sumCount() <= 0L; // ignore transient negative values
2603      }
2604  
2605      /**
2606       * {@inheritDoc}
2607       */
2608      public int size() {
2609 <        long n = counter.sum();
2609 >        long n = sumCount();
2610          return ((n < 0L) ? 0 :
2611                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2612                  (int)n);
# Line 2615 | Line 2616 | public class ConcurrentHashMap<K, V>
2616       * Returns the number of mappings. This method should be used
2617       * instead of {@link #size} because a ConcurrentHashMap may
2618       * contain more mappings than can be represented as an int. The
2619 <     * value returned is a snapshot; the actual count may differ if
2620 <     * there are ongoing concurrent insertions or removals.
2619 >     * value returned is an estimate; the actual count may differ if
2620 >     * there are concurrent insertions or removals.
2621       *
2622       * @return the number of mappings
2623       */
2624      public long mappingCount() {
2625 <        long n = counter.sum();
2625 >        long n = sumCount();
2626          return (n < 0L) ? 0L : n; // ignore transient negative values
2627      }
2628  
# Line 2636 | Line 2637 | public class ConcurrentHashMap<K, V>
2637       *
2638       * @throws NullPointerException if the specified key is null
2639       */
2640 <    @SuppressWarnings("unchecked") public V get(Object key) {
2641 <        if (key == null)
2641 <            throw new NullPointerException();
2642 <        return (V)internalGet(key);
2640 >    public V get(Object key) {
2641 >        return internalGet(key);
2642      }
2643  
2644      /**
2645 <     * Returns the value to which the specified key is mapped,
2646 <     * or the given defaultValue if this map contains no mapping for the key.
2645 >     * Returns the value to which the specified key is mapped, or the
2646 >     * given default value if this map contains no mapping for the
2647 >     * key.
2648       *
2649 <     * @param key the key
2649 >     * @param @param key the key whose associated value is to be returned
2650       * @param defaultValue the value to return if this map contains
2651       * no mapping for the given key
2652 <     * @return the mapping for the key, if present; else the defaultValue
2652 >     * @return the mapping for the key, if present; else the default value
2653       * @throws NullPointerException if the specified key is null
2654       */
2655 <    @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) {
2656 <        if (key == null)
2657 <            throw new NullPointerException();
2658 <        V v = (V) internalGet(key);
2659 <        return v == null ? defaultValue : v;
2655 >    public V getOrDefault(Object key, V defaultValue) {
2656 >        V v;
2657 >        return (v = internalGet(key)) == null ? defaultValue : v;
2658      }
2659  
2660      /**
2661       * Tests if the specified object is a key in this table.
2662       *
2663 <     * @param  key   possible key
2663 >     * @param  key possible key
2664       * @return {@code true} if and only if the specified object
2665       *         is a key in this table, as determined by the
2666       *         {@code equals} method; {@code false} otherwise
2667       * @throws NullPointerException if the specified key is null
2668       */
2669      public boolean containsKey(Object key) {
2672        if (key == null)
2673            throw new NullPointerException();
2670          return internalGet(key) != null;
2671      }
2672  
# Line 2687 | Line 2683 | public class ConcurrentHashMap<K, V>
2683      public boolean containsValue(Object value) {
2684          if (value == null)
2685              throw new NullPointerException();
2686 <        Object v;
2687 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2688 <        while ((v = it.advance()) != null) {
2689 <            if (v == value || value.equals(v))
2690 <                return true;
2686 >        Node<K,V>[] t;
2687 >        if ((t = table) != null) {
2688 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
2689 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
2690 >                V v;
2691 >                if ((v = p.val) == value || value.equals(v))
2692 >                    return true;
2693 >            }
2694          }
2695          return false;
2696      }
# Line 2699 | Line 2698 | public class ConcurrentHashMap<K, V>
2698      /**
2699       * Legacy method testing if some key maps into the specified value
2700       * in this table.  This method is identical in functionality to
2701 <     * {@link #containsValue}, and exists solely to ensure
2701 >     * {@link #containsValue(Object)}, and exists solely to ensure
2702       * full compatibility with class {@link java.util.Hashtable},
2703       * which supported this method prior to introduction of the
2704       * Java Collections framework.
# Line 2711 | Line 2710 | public class ConcurrentHashMap<K, V>
2710       *         {@code false} otherwise
2711       * @throws NullPointerException if the specified value is null
2712       */
2713 <    public boolean contains(Object value) {
2713 >    @Deprecated public boolean contains(Object value) {
2714          return containsValue(value);
2715      }
2716  
# Line 2719 | Line 2718 | public class ConcurrentHashMap<K, V>
2718       * Maps the specified key to the specified value in this table.
2719       * Neither the key nor the value can be null.
2720       *
2721 <     * <p> The value can be retrieved by calling the {@code get} method
2721 >     * <p>The value can be retrieved by calling the {@code get} method
2722       * with a key that is equal to the original key.
2723       *
2724       * @param key key with which the specified value is to be associated
# Line 2728 | Line 2727 | public class ConcurrentHashMap<K, V>
2727       *         {@code null} if there was no mapping for {@code key}
2728       * @throws NullPointerException if the specified key or value is null
2729       */
2730 <    @SuppressWarnings("unchecked") public V put(K key, V value) {
2731 <        if (key == null || value == null)
2733 <            throw new NullPointerException();
2734 <        return (V)internalPut(key, value);
2730 >    public V put(K key, V value) {
2731 >        return internalPut(key, value, false);
2732      }
2733  
2734      /**
# Line 2741 | Line 2738 | public class ConcurrentHashMap<K, V>
2738       *         or {@code null} if there was no mapping for the key
2739       * @throws NullPointerException if the specified key or value is null
2740       */
2741 <    @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) {
2742 <        if (key == null || value == null)
2746 <            throw new NullPointerException();
2747 <        return (V)internalPutIfAbsent(key, value);
2741 >    public V putIfAbsent(K key, V value) {
2742 >        return internalPut(key, value, true);
2743      }
2744  
2745      /**
# Line 2760 | Line 2755 | public class ConcurrentHashMap<K, V>
2755  
2756      /**
2757       * If the specified key is not already associated with a value,
2758 <     * computes its value using the given mappingFunction and enters
2759 <     * it into the map unless null.  This is equivalent to
2760 <     * <pre> {@code
2761 <     * if (map.containsKey(key))
2762 <     *   return map.get(key);
2763 <     * value = mappingFunction.apply(key);
2764 <     * if (value != null)
2770 <     *   map.put(key, value);
2771 <     * return value;}</pre>
2772 <     *
2773 <     * except that the action is performed atomically.  If the
2774 <     * function returns {@code null} no mapping is recorded. If the
2775 <     * function itself throws an (unchecked) exception, the exception
2776 <     * is rethrown to its caller, and no mapping is recorded.  Some
2777 <     * attempted update operations on this map by other threads may be
2778 <     * blocked while computation is in progress, so the computation
2779 <     * should be short and simple, and must not attempt to update any
2780 <     * other mappings of this Map. The most appropriate usage is to
2781 <     * construct a new object serving as an initial mapped value, or
2782 <     * memoized result, as in:
2783 <     *
2784 <     *  <pre> {@code
2785 <     * map.computeIfAbsent(key, new Fun<K, V>() {
2786 <     *   public V map(K k) { return new Value(f(k)); }});}</pre>
2758 >     * attempts to compute its value using the given mapping function
2759 >     * and enters it into this map unless {@code null}.  The entire
2760 >     * method invocation is performed atomically, so the function is
2761 >     * applied at most once per key.  Some attempted update operations
2762 >     * on this map by other threads may be blocked while computation
2763 >     * is in progress, so the computation should be short and simple,
2764 >     * and must not attempt to update any other mappings of this map.
2765       *
2766       * @param key key with which the specified value is to be associated
2767       * @param mappingFunction the function to compute a value
# Line 2797 | Line 2775 | public class ConcurrentHashMap<K, V>
2775       * @throws RuntimeException or Error if the mappingFunction does so,
2776       *         in which case the mapping is left unestablished
2777       */
2778 <    @SuppressWarnings("unchecked") public V computeIfAbsent
2779 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
2802 <        if (key == null || mappingFunction == null)
2803 <            throw new NullPointerException();
2804 <        return (V)internalComputeIfAbsent(key, mappingFunction);
2778 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
2779 >        return internalComputeIfAbsent(key, mappingFunction);
2780      }
2781  
2782      /**
2783 <     * If the given key is present, computes a new mapping value given a key and
2784 <     * its current mapped value. This is equivalent to
2785 <     *  <pre> {@code
2786 <     *   if (map.containsKey(key)) {
2787 <     *     value = remappingFunction.apply(key, map.get(key));
2788 <     *     if (value != null)
2789 <     *       map.put(key, value);
2815 <     *     else
2816 <     *       map.remove(key);
2817 <     *   }
2818 <     * }</pre>
2819 <     *
2820 <     * except that the action is performed atomically.  If the
2821 <     * function returns {@code null}, the mapping is removed.  If the
2822 <     * function itself throws an (unchecked) exception, the exception
2823 <     * is rethrown to its caller, and the current mapping is left
2824 <     * unchanged.  Some attempted update operations on this map by
2825 <     * other threads may be blocked while computation is in progress,
2826 <     * so the computation should be short and simple, and must not
2827 <     * attempt to update any other mappings of this Map. For example,
2828 <     * to either create or append new messages to a value mapping:
2783 >     * If the value for the specified key is present, attempts to
2784 >     * compute a new mapping given the key and its current mapped
2785 >     * value.  The entire method invocation is performed atomically.
2786 >     * Some attempted update operations on this map by other threads
2787 >     * may be blocked while computation is in progress, so the
2788 >     * computation should be short and simple, and must not attempt to
2789 >     * update any other mappings of this map.
2790       *
2791 <     * @param key key with which the specified value is to be associated
2791 >     * @param key key with which a value may be associated
2792       * @param remappingFunction the function to compute a value
2793       * @return the new value associated with the specified key, or null if none
2794       * @throws NullPointerException if the specified key or remappingFunction
# Line 2838 | Line 2799 | public class ConcurrentHashMap<K, V>
2799       * @throws RuntimeException or Error if the remappingFunction does so,
2800       *         in which case the mapping is unchanged
2801       */
2802 <    @SuppressWarnings("unchecked") public V computeIfPresent
2803 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2843 <        if (key == null || remappingFunction == null)
2844 <            throw new NullPointerException();
2845 <        return (V)internalCompute(key, true, remappingFunction);
2802 >    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2803 >        return internalCompute(key, true, remappingFunction);
2804      }
2805  
2806      /**
2807 <     * Computes a new mapping value given a key and
2808 <     * its current mapped value (or {@code null} if there is no current
2809 <     * mapping). This is equivalent to
2810 <     *  <pre> {@code
2811 <     *   value = remappingFunction.apply(key, map.get(key));
2812 <     *   if (value != null)
2813 <     *     map.put(key, value);
2856 <     *   else
2857 <     *     map.remove(key);
2858 <     * }</pre>
2859 <     *
2860 <     * except that the action is performed atomically.  If the
2861 <     * function returns {@code null}, the mapping is removed.  If the
2862 <     * function itself throws an (unchecked) exception, the exception
2863 <     * is rethrown to its caller, and the current mapping is left
2864 <     * unchanged.  Some attempted update operations on this map by
2865 <     * other threads may be blocked while computation is in progress,
2866 <     * so the computation should be short and simple, and must not
2867 <     * attempt to update any other mappings of this Map. For example,
2868 <     * to either create or append new messages to a value mapping:
2869 <     *
2870 <     * <pre> {@code
2871 <     * Map<Key, String> map = ...;
2872 <     * final String msg = ...;
2873 <     * map.compute(key, new BiFun<Key, String, String>() {
2874 <     *   public String apply(Key k, String v) {
2875 <     *    return (v == null) ? msg : v + msg;});}}</pre>
2807 >     * Attempts to compute a mapping for the specified key and its
2808 >     * current mapped value (or {@code null} if there is no current
2809 >     * mapping). The entire method invocation is performed atomically.
2810 >     * Some attempted update operations on this map by other threads
2811 >     * may be blocked while computation is in progress, so the
2812 >     * computation should be short and simple, and must not attempt to
2813 >     * update any other mappings of this Map.
2814       *
2815       * @param key key with which the specified value is to be associated
2816       * @param remappingFunction the function to compute a value
# Line 2885 | Line 2823 | public class ConcurrentHashMap<K, V>
2823       * @throws RuntimeException or Error if the remappingFunction does so,
2824       *         in which case the mapping is unchanged
2825       */
2826 <    @SuppressWarnings("unchecked") public V compute
2827 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2890 <        if (key == null || remappingFunction == null)
2891 <            throw new NullPointerException();
2892 <        return (V)internalCompute(key, false, remappingFunction);
2826 >    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2827 >        return internalCompute(key, false, remappingFunction);
2828      }
2829  
2830      /**
2831 <     * If the specified key is not already associated
2832 <     * with a value, associate it with the given value.
2833 <     * Otherwise, replace the value with the results of
2834 <     * the given remapping function. This is equivalent to:
2835 <     *  <pre> {@code
2836 <     *   if (!map.containsKey(key))
2837 <     *     map.put(value);
2838 <     *   else {
2839 <     *     newValue = remappingFunction.apply(map.get(key), value);
2840 <     *     if (value != null)
2841 <     *       map.put(key, value);
2842 <     *     else
2843 <     *       map.remove(key);
2844 <     *   }
2845 <     * }</pre>
2846 <     * except that the action is performed atomically.  If the
2847 <     * function returns {@code null}, the mapping is removed.  If the
2848 <     * function itself throws an (unchecked) exception, the exception
2849 <     * is rethrown to its caller, and the current mapping is left
2850 <     * unchanged.  Some attempted update operations on this map by
2851 <     * other threads may be blocked while computation is in progress,
2917 <     * so the computation should be short and simple, and must not
2918 <     * attempt to update any other mappings of this Map.
2919 <     */
2920 <    @SuppressWarnings("unchecked") public V merge
2921 <        (K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2922 <        if (key == null || value == null || remappingFunction == null)
2923 <            throw new NullPointerException();
2924 <        return (V)internalMerge(key, value, remappingFunction);
2831 >     * If the specified key is not already associated with a
2832 >     * (non-null) value, associates it with the given value.
2833 >     * Otherwise, replaces the value with the results of the given
2834 >     * remapping function, or removes if {@code null}. The entire
2835 >     * method invocation is performed atomically.  Some attempted
2836 >     * update operations on this map by other threads may be blocked
2837 >     * while computation is in progress, so the computation should be
2838 >     * short and simple, and must not attempt to update any other
2839 >     * mappings of this Map.
2840 >     *
2841 >     * @param key key with which the specified value is to be associated
2842 >     * @param value the value to use if absent
2843 >     * @param remappingFunction the function to recompute a value if present
2844 >     * @return the new value associated with the specified key, or null if none
2845 >     * @throws NullPointerException if the specified key or the
2846 >     *         remappingFunction is null
2847 >     * @throws RuntimeException or Error if the remappingFunction does so,
2848 >     *         in which case the mapping is unchanged
2849 >     */
2850 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2851 >        return internalMerge(key, value, remappingFunction);
2852      }
2853  
2854      /**
# Line 2933 | Line 2860 | public class ConcurrentHashMap<K, V>
2860       *         {@code null} if there was no mapping for {@code key}
2861       * @throws NullPointerException if the specified key is null
2862       */
2863 <    @SuppressWarnings("unchecked") public V remove(Object key) {
2864 <        if (key == null)
2938 <            throw new NullPointerException();
2939 <        return (V)internalReplace(key, null, null);
2863 >    public V remove(Object key) {
2864 >        return internalReplace(key, null, null);
2865      }
2866  
2867      /**
# Line 2947 | Line 2872 | public class ConcurrentHashMap<K, V>
2872      public boolean remove(Object key, Object value) {
2873          if (key == null)
2874              throw new NullPointerException();
2875 <        if (value == null)
2951 <            return false;
2952 <        return internalReplace(key, null, value) != null;
2875 >        return value != null && internalReplace(key, null, value) != null;
2876      }
2877  
2878      /**
# Line 2970 | Line 2893 | public class ConcurrentHashMap<K, V>
2893       *         or {@code null} if there was no mapping for the key
2894       * @throws NullPointerException if the specified key or value is null
2895       */
2896 <    @SuppressWarnings("unchecked") public V replace(K key, V value) {
2896 >    public V replace(K key, V value) {
2897          if (key == null || value == null)
2898              throw new NullPointerException();
2899 <        return (V)internalReplace(key, value, null);
2899 >        return internalReplace(key, value, null);
2900      }
2901  
2902      /**
# Line 2986 | Line 2909 | public class ConcurrentHashMap<K, V>
2909      /**
2910       * Returns a {@link Set} view of the keys contained in this map.
2911       * The set is backed by the map, so changes to the map are
2912 <     * reflected in the set, and vice-versa.
2912 >     * reflected in the set, and vice-versa. The set supports element
2913 >     * removal, which removes the corresponding mapping from this map,
2914 >     * via the {@code Iterator.remove}, {@code Set.remove},
2915 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
2916 >     * operations.  It does not support the {@code add} or
2917 >     * {@code addAll} operations.
2918 >     *
2919 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2920 >     * that will never throw {@link ConcurrentModificationException},
2921 >     * and guarantees to traverse elements as they existed upon
2922 >     * construction of the iterator, and may (but is not guaranteed to)
2923 >     * reflect any modifications subsequent to construction.
2924       *
2925       * @return the set view
2926       */
# Line 2998 | Line 2932 | public class ConcurrentHashMap<K, V>
2932      /**
2933       * Returns a {@link Set} view of the keys in this map, using the
2934       * given common mapped value for any additions (i.e., {@link
2935 <     * Collection#add} and {@link Collection#addAll}). This is of
2936 <     * course only appropriate if it is acceptable to use the same
2937 <     * value for all additions from this view.
2935 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2936 >     * This is of course only appropriate if it is acceptable to use
2937 >     * the same value for all additions from this view.
2938       *
2939 <     * @param mappedValue the mapped value to use for any
3006 <     * additions.
2939 >     * @param mappedValue the mapped value to use for any additions
2940       * @return the set view
2941       * @throws NullPointerException if the mappedValue is null
2942       */
# Line 3016 | Line 2949 | public class ConcurrentHashMap<K, V>
2949      /**
2950       * Returns a {@link Collection} view of the values contained in this map.
2951       * The collection is backed by the map, so changes to the map are
2952 <     * reflected in the collection, and vice-versa.
2952 >     * reflected in the collection, and vice-versa.  The collection
2953 >     * supports element removal, which removes the corresponding
2954 >     * mapping from this map, via the {@code Iterator.remove},
2955 >     * {@code Collection.remove}, {@code removeAll},
2956 >     * {@code retainAll}, and {@code clear} operations.  It does not
2957 >     * support the {@code add} or {@code addAll} operations.
2958 >     *
2959 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2960 >     * that will never throw {@link ConcurrentModificationException},
2961 >     * and guarantees to traverse elements as they existed upon
2962 >     * construction of the iterator, and may (but is not guaranteed to)
2963 >     * reflect any modifications subsequent to construction.
2964 >     *
2965 >     * @return the collection view
2966       */
2967 <    public ValuesView<K,V> values() {
2967 >    public Collection<V> values() {
2968          ValuesView<K,V> vs = values;
2969          return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2970      }
# Line 3030 | Line 2976 | public class ConcurrentHashMap<K, V>
2976       * removal, which removes the corresponding mapping from the map,
2977       * via the {@code Iterator.remove}, {@code Set.remove},
2978       * {@code removeAll}, {@code retainAll}, and {@code clear}
2979 <     * operations.  It does not support the {@code add} or
3034 <     * {@code addAll} operations.
2979 >     * operations.
2980       *
2981       * <p>The view's {@code iterator} is a "weakly consistent" iterator
2982       * that will never throw {@link ConcurrentModificationException},
2983       * and guarantees to traverse elements as they existed upon
2984       * construction of the iterator, and may (but is not guaranteed to)
2985       * reflect any modifications subsequent to construction.
2986 +     *
2987 +     * @return the set view
2988       */
2989      public Set<Map.Entry<K,V>> entrySet() {
2990          EntrySetView<K,V> es = entrySet;
# Line 3051 | Line 2998 | public class ConcurrentHashMap<K, V>
2998       * @see #keySet()
2999       */
3000      public Enumeration<K> keys() {
3001 <        return new KeyIterator<K,V>(this);
3001 >        Node<K,V>[] t;
3002 >        int f = (t = table) == null ? 0 : t.length;
3003 >        return new KeyIterator<K,V>(t, f, 0, f, this);
3004      }
3005  
3006      /**
# Line 3061 | Line 3010 | public class ConcurrentHashMap<K, V>
3010       * @see #values()
3011       */
3012      public Enumeration<V> elements() {
3013 <        return new ValueIterator<K,V>(this);
3014 <    }
3015 <
3067 <    /**
3068 <     * Returns a partitionable iterator of the keys in this map.
3069 <     *
3070 <     * @return a partitionable iterator of the keys in this map
3071 <     */
3072 <    public Spliterator<K> keySpliterator() {
3073 <        return new KeyIterator<K,V>(this);
3074 <    }
3075 <
3076 <    /**
3077 <     * Returns a partitionable iterator of the values in this map.
3078 <     *
3079 <     * @return a partitionable iterator of the values in this map
3080 <     */
3081 <    public Spliterator<V> valueSpliterator() {
3082 <        return new ValueIterator<K,V>(this);
3083 <    }
3084 <
3085 <    /**
3086 <     * Returns a partitionable iterator of the entries in this map.
3087 <     *
3088 <     * @return a partitionable iterator of the entries in this map
3089 <     */
3090 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
3091 <        return new EntryIterator<K,V>(this);
3013 >        Node<K,V>[] t;
3014 >        int f = (t = table) == null ? 0 : t.length;
3015 >        return new ValueIterator<K,V>(t, f, 0, f, this);
3016      }
3017  
3018      /**
# Line 3100 | Line 3024 | public class ConcurrentHashMap<K, V>
3024       */
3025      public int hashCode() {
3026          int h = 0;
3027 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3028 <        Object v;
3029 <        while ((v = it.advance()) != null) {
3030 <            h += it.nextKey.hashCode() ^ v.hashCode();
3027 >        Node<K,V>[] t;
3028 >        if ((t = table) != null) {
3029 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3030 >            for (Node<K,V> p; (p = it.advance()) != null; )
3031 >                h += p.key.hashCode() ^ p.val.hashCode();
3032          }
3033          return h;
3034      }
# Line 3120 | Line 3045 | public class ConcurrentHashMap<K, V>
3045       * @return a string representation of this map
3046       */
3047      public String toString() {
3048 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3048 >        Node<K,V>[] t;
3049 >        int f = (t = table) == null ? 0 : t.length;
3050 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
3051          StringBuilder sb = new StringBuilder();
3052          sb.append('{');
3053 <        Object v;
3054 <        if ((v = it.advance()) != null) {
3053 >        Node<K,V> p;
3054 >        if ((p = it.advance()) != null) {
3055              for (;;) {
3056 <                Object k = it.nextKey;
3056 >                K k = (K)p.key;
3057 >                V v = p.val;
3058                  sb.append(k == this ? "(this Map)" : k);
3059                  sb.append('=');
3060                  sb.append(v == this ? "(this Map)" : v);
3061 <                if ((v = it.advance()) == null)
3061 >                if ((p = it.advance()) == null)
3062                      break;
3063                  sb.append(',').append(' ');
3064              }
# Line 3153 | Line 3081 | public class ConcurrentHashMap<K, V>
3081              if (!(o instanceof Map))
3082                  return false;
3083              Map<?,?> m = (Map<?,?>) o;
3084 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3085 <            Object val;
3086 <            while ((val = it.advance()) != null) {
3087 <                Object v = m.get(it.nextKey);
3084 >            Node<K,V>[] t;
3085 >            int f = (t = table) == null ? 0 : t.length;
3086 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
3087 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
3088 >                V val = p.val;
3089 >                Object v = m.get(p.key);
3090                  if (v == null || (v != val && !v.equals(val)))
3091                      return false;
3092              }
# Line 3172 | Line 3102 | public class ConcurrentHashMap<K, V>
3102          return true;
3103      }
3104  
3175    /* ----------------Iterators -------------- */
3176
3177    @SuppressWarnings("serial") static final class KeyIterator<K,V> extends Traverser<K,V,Object>
3178        implements Spliterator<K>, Enumeration<K> {
3179        KeyIterator(ConcurrentHashMap<K, V> map) { super(map); }
3180        KeyIterator(Traverser<K,V,Object> it) {
3181            super(it);
3182        }
3183        public KeyIterator<K,V> split() {
3184            if (nextKey != null)
3185                throw new IllegalStateException();
3186            return new KeyIterator<K,V>(this);
3187        }
3188        @SuppressWarnings("unchecked") public final K next() {
3189            if (nextVal == null && advance() == null)
3190                throw new NoSuchElementException();
3191            Object k = nextKey;
3192            nextVal = null;
3193            return (K) k;
3194        }
3195
3196        public final K nextElement() { return next(); }
3197    }
3198
3199    @SuppressWarnings("serial") static final class ValueIterator<K,V> extends Traverser<K,V,Object>
3200        implements Spliterator<V>, Enumeration<V> {
3201        ValueIterator(ConcurrentHashMap<K, V> map) { super(map); }
3202        ValueIterator(Traverser<K,V,Object> it) {
3203            super(it);
3204        }
3205        public ValueIterator<K,V> split() {
3206            if (nextKey != null)
3207                throw new IllegalStateException();
3208            return new ValueIterator<K,V>(this);
3209        }
3210
3211        @SuppressWarnings("unchecked") public final V next() {
3212            Object v;
3213            if ((v = nextVal) == null && (v = advance()) == null)
3214                throw new NoSuchElementException();
3215            nextVal = null;
3216            return (V) v;
3217        }
3218
3219        public final V nextElement() { return next(); }
3220    }
3221
3222    @SuppressWarnings("serial") static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3223        implements Spliterator<Map.Entry<K,V>> {
3224        EntryIterator(ConcurrentHashMap<K, V> map) { super(map); }
3225        EntryIterator(Traverser<K,V,Object> it) {
3226            super(it);
3227        }
3228        public EntryIterator<K,V> split() {
3229            if (nextKey != null)
3230                throw new IllegalStateException();
3231            return new EntryIterator<K,V>(this);
3232        }
3233
3234        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3235            Object v;
3236            if ((v = nextVal) == null && (v = advance()) == null)
3237                throw new NoSuchElementException();
3238            Object k = nextKey;
3239            nextVal = null;
3240            return new MapEntry<K,V>((K)k, (V)v, map);
3241        }
3242    }
3243
3244    /**
3245     * Exported Entry for iterators
3246     */
3247    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3248        final K key; // non-null
3249        V val;       // non-null
3250        final ConcurrentHashMap<K, V> map;
3251        MapEntry(K key, V val, ConcurrentHashMap<K, V> map) {
3252            this.key = key;
3253            this.val = val;
3254            this.map = map;
3255        }
3256        public final K getKey()       { return key; }
3257        public final V getValue()     { return val; }
3258        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3259        public final String toString(){ return key + "=" + val; }
3260
3261        public final boolean equals(Object o) {
3262            Object k, v; Map.Entry<?,?> e;
3263            return ((o instanceof Map.Entry) &&
3264                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3265                    (v = e.getValue()) != null &&
3266                    (k == key || k.equals(key)) &&
3267                    (v == val || v.equals(val)));
3268        }
3269
3270        /**
3271         * Sets our entry's value and writes through to the map. The
3272         * value to return is somewhat arbitrary here. Since we do not
3273         * necessarily track asynchronous changes, the most recent
3274         * "previous" value could be different from what we return (or
3275         * could even have been removed in which case the put will
3276         * re-establish). We do not and cannot guarantee more.
3277         */
3278        public final V setValue(V value) {
3279            if (value == null) throw new NullPointerException();
3280            V v = val;
3281            val = value;
3282            map.put(key, value);
3283            return v;
3284        }
3285    }
3286
3105      /* ---------------- Serialization Support -------------- */
3106  
3107      /**
3108       * Stripped-down version of helper class used in previous version,
3109       * declared for the sake of serialization compatibility
3110       */
3111 <    static class Segment<K,V> implements Serializable {
3111 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
3112          private static final long serialVersionUID = 2249069246763182397L;
3113          final float loadFactor;
3114          Segment(float lf) { this.loadFactor = lf; }
# Line 3305 | Line 3123 | public class ConcurrentHashMap<K, V>
3123       * for each key-value mapping, followed by a null pair.
3124       * The key-value mappings are emitted in no particular order.
3125       */
3126 <    @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s)
3126 >    private void writeObject(java.io.ObjectOutputStream s)
3127          throws java.io.IOException {
3128 <        if (segments == null) { // for serialization compatibility
3129 <            segments = (Segment<K,V>[])
3130 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3131 <            for (int i = 0; i < segments.length; ++i)
3132 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3133 <        }
3134 <        s.defaultWriteObject();
3135 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3136 <        Object v;
3137 <        while ((v = it.advance()) != null) {
3138 <            s.writeObject(it.nextKey);
3139 <            s.writeObject(v);
3128 >        // For serialization compatibility
3129 >        // Emulate segment calculation from previous version of this class
3130 >        int sshift = 0;
3131 >        int ssize = 1;
3132 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
3133 >            ++sshift;
3134 >            ssize <<= 1;
3135 >        }
3136 >        int segmentShift = 32 - sshift;
3137 >        int segmentMask = ssize - 1;
3138 >        Segment<K,V>[] segments = (Segment<K,V>[])
3139 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3140 >        for (int i = 0; i < segments.length; ++i)
3141 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
3142 >        s.putFields().put("segments", segments);
3143 >        s.putFields().put("segmentShift", segmentShift);
3144 >        s.putFields().put("segmentMask", segmentMask);
3145 >        s.writeFields();
3146 >
3147 >        Node<K,V>[] t;
3148 >        if ((t = table) != null) {
3149 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3150 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
3151 >                s.writeObject(p.key);
3152 >                s.writeObject(p.val);
3153 >            }
3154          }
3155          s.writeObject(null);
3156          s.writeObject(null);
# Line 3329 | Line 3161 | public class ConcurrentHashMap<K, V>
3161       * Reconstitutes the instance from a stream (that is, deserializes it).
3162       * @param s the stream
3163       */
3164 <    @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
3164 >    private void readObject(java.io.ObjectInputStream s)
3165          throws java.io.IOException, ClassNotFoundException {
3166          s.defaultReadObject();
3335        this.segments = null; // unneeded
3336        // initialize transient final field
3337        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
3167  
3168          // Create all nodes, then place in table once size is known
3169          long size = 0L;
3170 <        Node p = null;
3170 >        Node<K,V> p = null;
3171          for (;;) {
3172              K k = (K) s.readObject();
3173              V v = (V) s.readObject();
3174              if (k != null && v != null) {
3175                  int h = spread(k.hashCode());
3176 <                p = new Node(h, k, v, p);
3176 >                p = new Node<K,V>(h, k, v, p);
3177                  ++size;
3178              }
3179              else
# Line 3362 | Line 3191 | public class ConcurrentHashMap<K, V>
3191              int sc = sizeCtl;
3192              boolean collide = false;
3193              if (n > sc &&
3194 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3194 >                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3195                  try {
3196                      if (table == null) {
3197                          init = true;
3198 <                        Node[] tab = new Node[n];
3198 >                        Node<K,V>[] tab = (Node<K,V>[])new Node[n];
3199                          int mask = n - 1;
3200                          while (p != null) {
3201                              int j = p.hash & mask;
3202 <                            Node next = p.next;
3203 <                            Node q = p.next = tabAt(tab, j);
3202 >                            Node<K,V> next = p.next;
3203 >                            Node<K,V> q = p.next = tabAt(tab, j);
3204                              setTabAt(tab, j, p);
3205                              if (!collide && q != null && q.hash == p.hash)
3206                                  collide = true;
3207                              p = next;
3208                          }
3209                          table = tab;
3210 <                        counter.add(size);
3210 >                        addCount(size, -1);
3211                          sc = n - (n >>> 2);
3212                      }
3213                  } finally {
3214                      sizeCtl = sc;
3215                  }
3216                  if (collide) { // rescan and convert to TreeBins
3217 <                    Node[] tab = table;
3217 >                    Node<K,V>[] tab = table;
3218                      for (int i = 0; i < tab.length; ++i) {
3219                          int c = 0;
3220 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3220 >                        for (Node<K,V> e = tabAt(tab, i); e != null; e = e.next) {
3221                              if (++c > TREE_THRESHOLD &&
3222                                  (e.key instanceof Comparable)) {
3223                                  replaceWithTreeBin(tab, i, e.key);
# Line 3400 | Line 3229 | public class ConcurrentHashMap<K, V>
3229              }
3230              if (!init) { // Can only happen if unsafely published.
3231                  while (p != null) {
3232 <                    internalPut(p.key, p.val);
3232 >                    internalPut((K)p.key, p.val, false);
3233                      p = p.next;
3234                  }
3235              }
3236          }
3237      }
3238  
3410
3239      // -------------------------------------------------------
3240  
3241 <    // Sams
3414 <    /** Interface describing a void action of one argument */
3415 <    public interface Action<A> { void apply(A a); }
3416 <    /** Interface describing a void action of two arguments */
3417 <    public interface BiAction<A,B> { void apply(A a, B b); }
3418 <    /** Interface describing a function of one argument */
3419 <    public interface Fun<A,T> { T apply(A a); }
3420 <    /** Interface describing a function of two arguments */
3421 <    public interface BiFun<A,B,T> { T apply(A a, B b); }
3422 <    /** Interface describing a function of no arguments */
3423 <    public interface Generator<T> { T apply(); }
3424 <    /** Interface describing a function mapping its argument to a double */
3425 <    public interface ObjectToDouble<A> { double apply(A a); }
3426 <    /** Interface describing a function mapping its argument to a long */
3427 <    public interface ObjectToLong<A> { long apply(A a); }
3428 <    /** Interface describing a function mapping its argument to an int */
3429 <    public interface ObjectToInt<A> {int apply(A a); }
3430 <    /** Interface describing a function mapping two arguments to a double */
3431 <    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
3432 <    /** Interface describing a function mapping two arguments to a long */
3433 <    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
3434 <    /** Interface describing a function mapping two arguments to an int */
3435 <    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
3436 <    /** Interface describing a function mapping a double to a double */
3437 <    public interface DoubleToDouble { double apply(double a); }
3438 <    /** Interface describing a function mapping a long to a long */
3439 <    public interface LongToLong { long apply(long a); }
3440 <    /** Interface describing a function mapping an int to an int */
3441 <    public interface IntToInt { int apply(int a); }
3442 <    /** Interface describing a function mapping two doubles to a double */
3443 <    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3444 <    /** Interface describing a function mapping two longs to a long */
3445 <    public interface LongByLongToLong { long apply(long a, long b); }
3446 <    /** Interface describing a function mapping two ints to an int */
3447 <    public interface IntByIntToInt { int apply(int a, int b); }
3241 >    // Overrides of other default Map methods
3242  
3243 +    public void forEach(BiConsumer<? super K, ? super V> action) {
3244 +        if (action == null) throw new NullPointerException();
3245 +        Node<K,V>[] t;
3246 +        if ((t = table) != null) {
3247 +            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3248 +            for (Node<K,V> p; (p = it.advance()) != null; ) {
3249 +                action.accept((K)p.key, p.val);
3250 +            }
3251 +        }
3252 +    }
3253 +
3254 +    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3255 +        if (function == null) throw new NullPointerException();
3256 +        Node<K,V>[] t;
3257 +        if ((t = table) != null) {
3258 +            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3259 +            for (Node<K,V> p; (p = it.advance()) != null; ) {
3260 +                K k = (K)p.key;
3261 +                internalPut(k, function.apply(k, p.val), false);
3262 +            }
3263 +        }
3264 +    }
3265  
3266      // -------------------------------------------------------
3267  
3268 +    // Parallel bulk operations
3269 +
3270 +    /**
3271 +     * Computes initial batch value for bulk tasks. The returned value
3272 +     * is approximately exp2 of the number of times (minus one) to
3273 +     * split task by two before executing leaf action. This value is
3274 +     * faster to compute and more convenient to use as a guide to
3275 +     * splitting than is the depth, since it is used while dividing by
3276 +     * two anyway.
3277 +     */
3278 +    final int batchFor(long b) {
3279 +        long n;
3280 +        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3281 +            return 0;
3282 +        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3283 +        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3284 +    }
3285 +
3286      /**
3287       * Performs the given action for each (key, value).
3288       *
3289 +     * @param parallelismThreshold the (estimated) number of elements
3290 +     * needed for this operation to be executed in parallel
3291       * @param action the action
3292       */
3293 <    public void forEach(BiAction<K,V> action) {
3294 <        ForkJoinTasks.forEach
3295 <            (this, action).invoke();
3293 >    public void forEach(long parallelismThreshold,
3294 >                        BiConsumer<? super K,? super V> action) {
3295 >        if (action == null) throw new NullPointerException();
3296 >        new ForEachMappingTask<K,V>
3297 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3298 >             action).invoke();
3299      }
3300  
3301      /**
3302       * Performs the given action for each non-null transformation
3303       * of each (key, value).
3304       *
3305 +     * @param parallelismThreshold the (estimated) number of elements
3306 +     * needed for this operation to be executed in parallel
3307       * @param transformer a function returning the transformation
3308 <     * for an element, or null of there is no transformation (in
3309 <     * which case the action is not applied).
3308 >     * for an element, or null if there is no transformation (in
3309 >     * which case the action is not applied)
3310       * @param action the action
3311       */
3312 <    public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3313 <                            Action<U> action) {
3314 <        ForkJoinTasks.forEach
3315 <            (this, transformer, action).invoke();
3312 >    public <U> void forEach(long parallelismThreshold,
3313 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3314 >                            Consumer<? super U> action) {
3315 >        if (transformer == null || action == null)
3316 >            throw new NullPointerException();
3317 >        new ForEachTransformedMappingTask<K,V,U>
3318 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3319 >             transformer, action).invoke();
3320      }
3321  
3322      /**
# Line 3481 | Line 3326 | public class ConcurrentHashMap<K, V>
3326       * results of any other parallel invocations of the search
3327       * function are ignored.
3328       *
3329 +     * @param parallelismThreshold the (estimated) number of elements
3330 +     * needed for this operation to be executed in parallel
3331       * @param searchFunction a function returning a non-null
3332       * result on success, else null
3333       * @return a non-null result from applying the given search
3334       * function on each (key, value), or null if none
3335       */
3336 <    public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3337 <        return ForkJoinTasks.search
3338 <            (this, searchFunction).invoke();
3336 >    public <U> U search(long parallelismThreshold,
3337 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3338 >        if (searchFunction == null) throw new NullPointerException();
3339 >        return new SearchMappingsTask<K,V,U>
3340 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3341 >             searchFunction, new AtomicReference<U>()).invoke();
3342      }
3343  
3344      /**
# Line 3496 | Line 3346 | public class ConcurrentHashMap<K, V>
3346       * of all (key, value) pairs using the given reducer to
3347       * combine values, or null if none.
3348       *
3349 +     * @param parallelismThreshold the (estimated) number of elements
3350 +     * needed for this operation to be executed in parallel
3351       * @param transformer a function returning the transformation
3352 <     * for an element, or null of there is no transformation (in
3353 <     * which case it is not combined).
3352 >     * for an element, or null if there is no transformation (in
3353 >     * which case it is not combined)
3354       * @param reducer a commutative associative combining function
3355       * @return the result of accumulating the given transformation
3356       * of all (key, value) pairs
3357       */
3358 <    public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3359 <                        BiFun<? super U, ? super U, ? extends U> reducer) {
3360 <        return ForkJoinTasks.reduce
3361 <            (this, transformer, reducer).invoke();
3358 >    public <U> U reduce(long parallelismThreshold,
3359 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3360 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3361 >        if (transformer == null || reducer == null)
3362 >            throw new NullPointerException();
3363 >        return new MapReduceMappingsTask<K,V,U>
3364 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3365 >             null, transformer, reducer).invoke();
3366      }
3367  
3368      /**
# Line 3514 | Line 3370 | public class ConcurrentHashMap<K, V>
3370       * of all (key, value) pairs using the given reducer to
3371       * combine values, and the given basis as an identity value.
3372       *
3373 +     * @param parallelismThreshold the (estimated) number of elements
3374 +     * needed for this operation to be executed in parallel
3375       * @param transformer a function returning the transformation
3376       * for an element
3377       * @param basis the identity (initial default value) for the reduction
# Line 3521 | Line 3379 | public class ConcurrentHashMap<K, V>
3379       * @return the result of accumulating the given transformation
3380       * of all (key, value) pairs
3381       */
3382 <    public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
3383 <                                 double basis,
3384 <                                 DoubleByDoubleToDouble reducer) {
3385 <        return ForkJoinTasks.reduceToDouble
3386 <            (this, transformer, basis, reducer).invoke();
3382 >    public double reduceToDoubleIn(long parallelismThreshold,
3383 >                                   ToDoubleBiFunction<? super K, ? super V> transformer,
3384 >                                   double basis,
3385 >                                   DoubleBinaryOperator reducer) {
3386 >        if (transformer == null || reducer == null)
3387 >            throw new NullPointerException();
3388 >        return new MapReduceMappingsToDoubleTask<K,V>
3389 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3390 >             null, transformer, basis, reducer).invoke();
3391      }
3392  
3393      /**
# Line 3533 | Line 3395 | public class ConcurrentHashMap<K, V>
3395       * of all (key, value) pairs using the given reducer to
3396       * combine values, and the given basis as an identity value.
3397       *
3398 +     * @param parallelismThreshold the (estimated) number of elements
3399 +     * needed for this operation to be executed in parallel
3400       * @param transformer a function returning the transformation
3401       * for an element
3402       * @param basis the identity (initial default value) for the reduction
# Line 3540 | Line 3404 | public class ConcurrentHashMap<K, V>
3404       * @return the result of accumulating the given transformation
3405       * of all (key, value) pairs
3406       */
3407 <    public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
3407 >    public long reduceToLong(long parallelismThreshold,
3408 >                             ToLongBiFunction<? super K, ? super V> transformer,
3409                               long basis,
3410 <                             LongByLongToLong reducer) {
3411 <        return ForkJoinTasks.reduceToLong
3412 <            (this, transformer, basis, reducer).invoke();
3410 >                             LongBinaryOperator reducer) {
3411 >        if (transformer == null || reducer == null)
3412 >            throw new NullPointerException();
3413 >        return new MapReduceMappingsToLongTask<K,V>
3414 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3415 >             null, transformer, basis, reducer).invoke();
3416      }
3417  
3418      /**
# Line 3552 | Line 3420 | public class ConcurrentHashMap<K, V>
3420       * of all (key, value) pairs using the given reducer to
3421       * combine values, and the given basis as an identity value.
3422       *
3423 +     * @param parallelismThreshold the (estimated) number of elements
3424 +     * needed for this operation to be executed in parallel
3425       * @param transformer a function returning the transformation
3426       * for an element
3427       * @param basis the identity (initial default value) for the reduction
# Line 3559 | Line 3429 | public class ConcurrentHashMap<K, V>
3429       * @return the result of accumulating the given transformation
3430       * of all (key, value) pairs
3431       */
3432 <    public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
3432 >    public int reduceToInt(long parallelismThreshold,
3433 >                           ToIntBiFunction<? super K, ? super V> transformer,
3434                             int basis,
3435 <                           IntByIntToInt reducer) {
3436 <        return ForkJoinTasks.reduceToInt
3437 <            (this, transformer, basis, reducer).invoke();
3435 >                           IntBinaryOperator reducer) {
3436 >        if (transformer == null || reducer == null)
3437 >            throw new NullPointerException();
3438 >        return new MapReduceMappingsToIntTask<K,V>
3439 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3440 >             null, transformer, basis, reducer).invoke();
3441      }
3442  
3443      /**
3444       * Performs the given action for each key.
3445       *
3446 +     * @param parallelismThreshold the (estimated) number of elements
3447 +     * needed for this operation to be executed in parallel
3448       * @param action the action
3449       */
3450 <    public void forEachKey(Action<K> action) {
3451 <        ForkJoinTasks.forEachKey
3452 <            (this, action).invoke();
3450 >    public void forEachKey(long parallelismThreshold,
3451 >                           Consumer<? super K> action) {
3452 >        if (action == null) throw new NullPointerException();
3453 >        new ForEachKeyTask<K,V>
3454 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3455 >             action).invoke();
3456      }
3457  
3458      /**
3459       * Performs the given action for each non-null transformation
3460       * of each key.
3461       *
3462 +     * @param parallelismThreshold the (estimated) number of elements
3463 +     * needed for this operation to be executed in parallel
3464       * @param transformer a function returning the transformation
3465 <     * for an element, or null of there is no transformation (in
3466 <     * which case the action is not applied).
3465 >     * for an element, or null if there is no transformation (in
3466 >     * which case the action is not applied)
3467       * @param action the action
3468       */
3469 <    public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
3470 <                               Action<U> action) {
3471 <        ForkJoinTasks.forEachKey
3472 <            (this, transformer, action).invoke();
3469 >    public <U> void forEachKey(long parallelismThreshold,
3470 >                               Function<? super K, ? extends U> transformer,
3471 >                               Consumer<? super U> action) {
3472 >        if (transformer == null || action == null)
3473 >            throw new NullPointerException();
3474 >        new ForEachTransformedKeyTask<K,V,U>
3475 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3476 >             transformer, action).invoke();
3477      }
3478  
3479      /**
# Line 3598 | Line 3483 | public class ConcurrentHashMap<K, V>
3483       * any other parallel invocations of the search function are
3484       * ignored.
3485       *
3486 +     * @param parallelismThreshold the (estimated) number of elements
3487 +     * needed for this operation to be executed in parallel
3488       * @param searchFunction a function returning a non-null
3489       * result on success, else null
3490       * @return a non-null result from applying the given search
3491       * function on each key, or null if none
3492       */
3493 <    public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
3494 <        return ForkJoinTasks.searchKeys
3495 <            (this, searchFunction).invoke();
3493 >    public <U> U searchKeys(long parallelismThreshold,
3494 >                            Function<? super K, ? extends U> searchFunction) {
3495 >        if (searchFunction == null) throw new NullPointerException();
3496 >        return new SearchKeysTask<K,V,U>
3497 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3498 >             searchFunction, new AtomicReference<U>()).invoke();
3499      }
3500  
3501      /**
3502       * Returns the result of accumulating all keys using the given
3503       * reducer to combine values, or null if none.
3504       *
3505 +     * @param parallelismThreshold the (estimated) number of elements
3506 +     * needed for this operation to be executed in parallel
3507       * @param reducer a commutative associative combining function
3508       * @return the result of accumulating all keys using the given
3509       * reducer to combine values, or null if none
3510       */
3511 <    public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
3512 <        return ForkJoinTasks.reduceKeys
3513 <            (this, reducer).invoke();
3511 >    public K reduceKeys(long parallelismThreshold,
3512 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3513 >        if (reducer == null) throw new NullPointerException();
3514 >        return new ReduceKeysTask<K,V>
3515 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3516 >             null, reducer).invoke();
3517      }
3518  
3519      /**
# Line 3626 | Line 3521 | public class ConcurrentHashMap<K, V>
3521       * of all keys using the given reducer to combine values, or
3522       * null if none.
3523       *
3524 +     * @param parallelismThreshold the (estimated) number of elements
3525 +     * needed for this operation to be executed in parallel
3526       * @param transformer a function returning the transformation
3527 <     * for an element, or null of there is no transformation (in
3528 <     * which case it is not combined).
3527 >     * for an element, or null if there is no transformation (in
3528 >     * which case it is not combined)
3529       * @param reducer a commutative associative combining function
3530       * @return the result of accumulating the given transformation
3531       * of all keys
3532       */
3533 <    public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
3534 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
3535 <        return ForkJoinTasks.reduceKeys
3536 <            (this, transformer, reducer).invoke();
3533 >    public <U> U reduceKeys(long parallelismThreshold,
3534 >                            Function<? super K, ? extends U> transformer,
3535 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3536 >        if (transformer == null || reducer == null)
3537 >            throw new NullPointerException();
3538 >        return new MapReduceKeysTask<K,V,U>
3539 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3540 >             null, transformer, reducer).invoke();
3541      }
3542  
3543      /**
# Line 3644 | Line 3545 | public class ConcurrentHashMap<K, V>
3545       * of all keys using the given reducer to combine values, and
3546       * the given basis as an identity value.
3547       *
3548 +     * @param parallelismThreshold the (estimated) number of elements
3549 +     * needed for this operation to be executed in parallel
3550       * @param transformer a function returning the transformation
3551       * for an element
3552       * @param basis the identity (initial default value) for the reduction
3553       * @param reducer a commutative associative combining function
3554 <     * @return  the result of accumulating the given transformation
3554 >     * @return the result of accumulating the given transformation
3555       * of all keys
3556       */
3557 <    public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
3557 >    public double reduceKeysToDouble(long parallelismThreshold,
3558 >                                     ToDoubleFunction<? super K> transformer,
3559                                       double basis,
3560 <                                     DoubleByDoubleToDouble reducer) {
3561 <        return ForkJoinTasks.reduceKeysToDouble
3562 <            (this, transformer, basis, reducer).invoke();
3560 >                                     DoubleBinaryOperator reducer) {
3561 >        if (transformer == null || reducer == null)
3562 >            throw new NullPointerException();
3563 >        return new MapReduceKeysToDoubleTask<K,V>
3564 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3565 >             null, transformer, basis, reducer).invoke();
3566      }
3567  
3568      /**
# Line 3663 | Line 3570 | public class ConcurrentHashMap<K, V>
3570       * of all keys using the given reducer to combine values, and
3571       * the given basis as an identity value.
3572       *
3573 +     * @param parallelismThreshold the (estimated) number of elements
3574 +     * needed for this operation to be executed in parallel
3575       * @param transformer a function returning the transformation
3576       * for an element
3577       * @param basis the identity (initial default value) for the reduction
# Line 3670 | Line 3579 | public class ConcurrentHashMap<K, V>
3579       * @return the result of accumulating the given transformation
3580       * of all keys
3581       */
3582 <    public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3582 >    public long reduceKeysToLong(long parallelismThreshold,
3583 >                                 ToLongFunction<? super K> transformer,
3584                                   long basis,
3585 <                                 LongByLongToLong reducer) {
3586 <        return ForkJoinTasks.reduceKeysToLong
3587 <            (this, transformer, basis, reducer).invoke();
3585 >                                 LongBinaryOperator reducer) {
3586 >        if (transformer == null || reducer == null)
3587 >            throw new NullPointerException();
3588 >        return new MapReduceKeysToLongTask<K,V>
3589 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3590 >             null, transformer, basis, reducer).invoke();
3591      }
3592  
3593      /**
# Line 3682 | Line 3595 | public class ConcurrentHashMap<K, V>
3595       * of all keys using the given reducer to combine values, and
3596       * the given basis as an identity value.
3597       *
3598 +     * @param parallelismThreshold the (estimated) number of elements
3599 +     * needed for this operation to be executed in parallel
3600       * @param transformer a function returning the transformation
3601       * for an element
3602       * @param basis the identity (initial default value) for the reduction
# Line 3689 | Line 3604 | public class ConcurrentHashMap<K, V>
3604       * @return the result of accumulating the given transformation
3605       * of all keys
3606       */
3607 <    public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3607 >    public int reduceKeysToInt(long parallelismThreshold,
3608 >                               ToIntFunction<? super K> transformer,
3609                                 int basis,
3610 <                               IntByIntToInt reducer) {
3611 <        return ForkJoinTasks.reduceKeysToInt
3612 <            (this, transformer, basis, reducer).invoke();
3610 >                               IntBinaryOperator reducer) {
3611 >        if (transformer == null || reducer == null)
3612 >            throw new NullPointerException();
3613 >        return new MapReduceKeysToIntTask<K,V>
3614 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3615 >             null, transformer, basis, reducer).invoke();
3616      }
3617  
3618      /**
3619       * Performs the given action for each value.
3620       *
3621 +     * @param parallelismThreshold the (estimated) number of elements
3622 +     * needed for this operation to be executed in parallel
3623       * @param action the action
3624       */
3625 <    public void forEachValue(Action<V> action) {
3626 <        ForkJoinTasks.forEachValue
3627 <            (this, action).invoke();
3625 >    public void forEachValue(long parallelismThreshold,
3626 >                             Consumer<? super V> action) {
3627 >        if (action == null)
3628 >            throw new NullPointerException();
3629 >        new ForEachValueTask<K,V>
3630 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3631 >             action).invoke();
3632      }
3633  
3634      /**
3635       * Performs the given action for each non-null transformation
3636       * of each value.
3637       *
3638 +     * @param parallelismThreshold the (estimated) number of elements
3639 +     * needed for this operation to be executed in parallel
3640       * @param transformer a function returning the transformation
3641 <     * for an element, or null of there is no transformation (in
3642 <     * which case the action is not applied).
3641 >     * for an element, or null if there is no transformation (in
3642 >     * which case the action is not applied)
3643 >     * @param action the action
3644       */
3645 <    public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
3646 <                                 Action<U> action) {
3647 <        ForkJoinTasks.forEachValue
3648 <            (this, transformer, action).invoke();
3645 >    public <U> void forEachValue(long parallelismThreshold,
3646 >                                 Function<? super V, ? extends U> transformer,
3647 >                                 Consumer<? super U> action) {
3648 >        if (transformer == null || action == null)
3649 >            throw new NullPointerException();
3650 >        new ForEachTransformedValueTask<K,V,U>
3651 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3652 >             transformer, action).invoke();
3653      }
3654  
3655      /**
# Line 3727 | Line 3659 | public class ConcurrentHashMap<K, V>
3659       * any other parallel invocations of the search function are
3660       * ignored.
3661       *
3662 +     * @param parallelismThreshold the (estimated) number of elements
3663 +     * needed for this operation to be executed in parallel
3664       * @param searchFunction a function returning a non-null
3665       * result on success, else null
3666       * @return a non-null result from applying the given search
3667       * function on each value, or null if none
3734     *
3668       */
3669 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
3670 <        return ForkJoinTasks.searchValues
3671 <            (this, searchFunction).invoke();
3669 >    public <U> U searchValues(long parallelismThreshold,
3670 >                              Function<? super V, ? extends U> searchFunction) {
3671 >        if (searchFunction == null) throw new NullPointerException();
3672 >        return new SearchValuesTask<K,V,U>
3673 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3674 >             searchFunction, new AtomicReference<U>()).invoke();
3675      }
3676  
3677      /**
3678       * Returns the result of accumulating all values using the
3679       * given reducer to combine values, or null if none.
3680       *
3681 +     * @param parallelismThreshold the (estimated) number of elements
3682 +     * needed for this operation to be executed in parallel
3683       * @param reducer a commutative associative combining function
3684 <     * @return  the result of accumulating all values
3684 >     * @return the result of accumulating all values
3685       */
3686 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
3687 <        return ForkJoinTasks.reduceValues
3688 <            (this, reducer).invoke();
3686 >    public V reduceValues(long parallelismThreshold,
3687 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
3688 >        if (reducer == null) throw new NullPointerException();
3689 >        return new ReduceValuesTask<K,V>
3690 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3691 >             null, reducer).invoke();
3692      }
3693  
3694      /**
# Line 3755 | Line 3696 | public class ConcurrentHashMap<K, V>
3696       * of all values using the given reducer to combine values, or
3697       * null if none.
3698       *
3699 +     * @param parallelismThreshold the (estimated) number of elements
3700 +     * needed for this operation to be executed in parallel
3701       * @param transformer a function returning the transformation
3702 <     * for an element, or null of there is no transformation (in
3703 <     * which case it is not combined).
3702 >     * for an element, or null if there is no transformation (in
3703 >     * which case it is not combined)
3704       * @param reducer a commutative associative combining function
3705       * @return the result of accumulating the given transformation
3706       * of all values
3707       */
3708 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
3709 <                              BiFun<? super U, ? super U, ? extends U> reducer) {
3710 <        return ForkJoinTasks.reduceValues
3711 <            (this, transformer, reducer).invoke();
3708 >    public <U> U reduceValues(long parallelismThreshold,
3709 >                              Function<? super V, ? extends U> transformer,
3710 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
3711 >        if (transformer == null || reducer == null)
3712 >            throw new NullPointerException();
3713 >        return new MapReduceValuesTask<K,V,U>
3714 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3715 >             null, transformer, reducer).invoke();
3716      }
3717  
3718      /**
# Line 3773 | Line 3720 | public class ConcurrentHashMap<K, V>
3720       * of all values using the given reducer to combine values,
3721       * and the given basis as an identity value.
3722       *
3723 +     * @param parallelismThreshold the (estimated) number of elements
3724 +     * needed for this operation to be executed in parallel
3725       * @param transformer a function returning the transformation
3726       * for an element
3727       * @param basis the identity (initial default value) for the reduction
# Line 3780 | Line 3729 | public class ConcurrentHashMap<K, V>
3729       * @return the result of accumulating the given transformation
3730       * of all values
3731       */
3732 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
3732 >    public double reduceValuesToDouble(long parallelismThreshold,
3733 >                                       ToDoubleFunction<? super V> transformer,
3734                                         double basis,
3735 <                                       DoubleByDoubleToDouble reducer) {
3736 <        return ForkJoinTasks.reduceValuesToDouble
3737 <            (this, transformer, basis, reducer).invoke();
3735 >                                       DoubleBinaryOperator reducer) {
3736 >        if (transformer == null || reducer == null)
3737 >            throw new NullPointerException();
3738 >        return new MapReduceValuesToDoubleTask<K,V>
3739 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3740 >             null, transformer, basis, reducer).invoke();
3741      }
3742  
3743      /**
# Line 3792 | Line 3745 | public class ConcurrentHashMap<K, V>
3745       * of all values using the given reducer to combine values,
3746       * 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
# Line 3799 | Line 3754 | public class ConcurrentHashMap<K, V>
3754       * @return the result of accumulating the given transformation
3755       * of all values
3756       */
3757 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
3757 >    public long reduceValuesToLong(long parallelismThreshold,
3758 >                                   ToLongFunction<? super V> transformer,
3759                                     long basis,
3760 <                                   LongByLongToLong reducer) {
3761 <        return ForkJoinTasks.reduceValuesToLong
3762 <            (this, transformer, basis, reducer).invoke();
3760 >                                   LongBinaryOperator reducer) {
3761 >        if (transformer == null || reducer == null)
3762 >            throw new NullPointerException();
3763 >        return new MapReduceValuesToLongTask<K,V>
3764 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3765 >             null, transformer, basis, reducer).invoke();
3766      }
3767  
3768      /**
# Line 3811 | Line 3770 | public class ConcurrentHashMap<K, V>
3770       * of all values using the given reducer to combine values,
3771       * and the given basis as an identity value.
3772       *
3773 +     * @param parallelismThreshold the (estimated) number of elements
3774 +     * needed for this operation to be executed in parallel
3775       * @param transformer a function returning the transformation
3776       * for an element
3777       * @param basis the identity (initial default value) for the reduction
# Line 3818 | Line 3779 | public class ConcurrentHashMap<K, V>
3779       * @return the result of accumulating the given transformation
3780       * of all values
3781       */
3782 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
3782 >    public int reduceValuesToInt(long parallelismThreshold,
3783 >                                 ToIntFunction<? super V> transformer,
3784                                   int basis,
3785 <                                 IntByIntToInt reducer) {
3786 <        return ForkJoinTasks.reduceValuesToInt
3787 <            (this, transformer, basis, reducer).invoke();
3785 >                                 IntBinaryOperator reducer) {
3786 >        if (transformer == null || reducer == null)
3787 >            throw new NullPointerException();
3788 >        return new MapReduceValuesToIntTask<K,V>
3789 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3790 >             null, transformer, basis, reducer).invoke();
3791      }
3792  
3793      /**
3794       * Performs the given action for each entry.
3795       *
3796 +     * @param parallelismThreshold the (estimated) number of elements
3797 +     * needed for this operation to be executed in parallel
3798       * @param action the action
3799       */
3800 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
3801 <        ForkJoinTasks.forEachEntry
3802 <            (this, action).invoke();
3800 >    public void forEachEntry(long parallelismThreshold,
3801 >                             Consumer<? super Map.Entry<K,V>> action) {
3802 >        if (action == null) throw new NullPointerException();
3803 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
3804 >                                  action).invoke();
3805      }
3806  
3807      /**
3808       * Performs the given action for each non-null transformation
3809       * of each entry.
3810       *
3811 +     * @param parallelismThreshold the (estimated) number of elements
3812 +     * needed for this operation to be executed in parallel
3813       * @param transformer a function returning the transformation
3814 <     * for an element, or null of there is no transformation (in
3815 <     * which case the action is not applied).
3814 >     * for an element, or null if there is no transformation (in
3815 >     * which case the action is not applied)
3816       * @param action the action
3817       */
3818 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
3819 <                                 Action<U> action) {
3820 <        ForkJoinTasks.forEachEntry
3821 <            (this, transformer, action).invoke();
3818 >    public <U> void forEachEntry(long parallelismThreshold,
3819 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
3820 >                                 Consumer<? super U> action) {
3821 >        if (transformer == null || action == null)
3822 >            throw new NullPointerException();
3823 >        new ForEachTransformedEntryTask<K,V,U>
3824 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3825 >             transformer, action).invoke();
3826      }
3827  
3828      /**
# Line 3857 | Line 3832 | public class ConcurrentHashMap<K, V>
3832       * any other parallel invocations of the search function are
3833       * ignored.
3834       *
3835 +     * @param parallelismThreshold the (estimated) number of elements
3836 +     * needed for this operation to be executed in parallel
3837       * @param searchFunction a function returning a non-null
3838       * result on success, else null
3839       * @return a non-null result from applying the given search
3840       * function on each entry, or null if none
3841       */
3842 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
3843 <        return ForkJoinTasks.searchEntries
3844 <            (this, searchFunction).invoke();
3842 >    public <U> U searchEntries(long parallelismThreshold,
3843 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
3844 >        if (searchFunction == null) throw new NullPointerException();
3845 >        return new SearchEntriesTask<K,V,U>
3846 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3847 >             searchFunction, new AtomicReference<U>()).invoke();
3848      }
3849  
3850      /**
3851       * Returns the result of accumulating all entries using the
3852       * given reducer to combine values, or null if none.
3853       *
3854 +     * @param parallelismThreshold the (estimated) number of elements
3855 +     * needed for this operation to be executed in parallel
3856       * @param reducer a commutative associative combining function
3857       * @return the result of accumulating all entries
3858       */
3859 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3860 <        return ForkJoinTasks.reduceEntries
3861 <            (this, reducer).invoke();
3859 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
3860 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3861 >        if (reducer == null) throw new NullPointerException();
3862 >        return new ReduceEntriesTask<K,V>
3863 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3864 >             null, reducer).invoke();
3865      }
3866  
3867      /**
# Line 3884 | Line 3869 | public class ConcurrentHashMap<K, V>
3869       * of all entries using the given reducer to combine values,
3870       * or null if none.
3871       *
3872 +     * @param parallelismThreshold the (estimated) number of elements
3873 +     * needed for this operation to be executed in parallel
3874       * @param transformer a function returning the transformation
3875 <     * for an element, or null of there is no transformation (in
3876 <     * which case it is not combined).
3875 >     * for an element, or null if there is no transformation (in
3876 >     * which case it is not combined)
3877       * @param reducer a commutative associative combining function
3878       * @return the result of accumulating the given transformation
3879       * of all entries
3880       */
3881 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
3882 <                               BiFun<? super U, ? super U, ? extends U> reducer) {
3883 <        return ForkJoinTasks.reduceEntries
3884 <            (this, transformer, reducer).invoke();
3881 >    public <U> U reduceEntries(long parallelismThreshold,
3882 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
3883 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
3884 >        if (transformer == null || reducer == null)
3885 >            throw new NullPointerException();
3886 >        return new MapReduceEntriesTask<K,V,U>
3887 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3888 >             null, transformer, reducer).invoke();
3889      }
3890  
3891      /**
# Line 3902 | Line 3893 | public class ConcurrentHashMap<K, V>
3893       * of all entries using the given reducer to combine values,
3894       * and the given basis as an identity value.
3895       *
3896 +     * @param parallelismThreshold the (estimated) number of elements
3897 +     * needed for this operation to be executed in parallel
3898       * @param transformer a function returning the transformation
3899       * for an element
3900       * @param basis the identity (initial default value) for the reduction
# Line 3909 | Line 3902 | public class ConcurrentHashMap<K, V>
3902       * @return the result of accumulating the given transformation
3903       * of all entries
3904       */
3905 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
3905 >    public double reduceEntriesToDouble(long parallelismThreshold,
3906 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
3907                                          double basis,
3908 <                                        DoubleByDoubleToDouble reducer) {
3909 <        return ForkJoinTasks.reduceEntriesToDouble
3910 <            (this, transformer, basis, reducer).invoke();
3908 >                                        DoubleBinaryOperator reducer) {
3909 >        if (transformer == null || reducer == null)
3910 >            throw new NullPointerException();
3911 >        return new MapReduceEntriesToDoubleTask<K,V>
3912 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3913 >             null, transformer, basis, reducer).invoke();
3914      }
3915  
3916      /**
# Line 3921 | Line 3918 | public class ConcurrentHashMap<K, V>
3918       * of all entries using the given reducer to combine values,
3919       * and the given basis as an identity value.
3920       *
3921 +     * @param parallelismThreshold the (estimated) number of elements
3922 +     * needed for this operation to be executed in parallel
3923       * @param transformer a function returning the transformation
3924       * for an element
3925       * @param basis the identity (initial default value) for the reduction
3926       * @param reducer a commutative associative combining function
3927 <     * @return  the result of accumulating the given transformation
3927 >     * @return the result of accumulating the given transformation
3928       * of all entries
3929       */
3930 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
3930 >    public long reduceEntriesToLong(long parallelismThreshold,
3931 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
3932                                      long basis,
3933 <                                    LongByLongToLong reducer) {
3934 <        return ForkJoinTasks.reduceEntriesToLong
3935 <            (this, transformer, basis, reducer).invoke();
3933 >                                    LongBinaryOperator reducer) {
3934 >        if (transformer == null || reducer == null)
3935 >            throw new NullPointerException();
3936 >        return new MapReduceEntriesToLongTask<K,V>
3937 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3938 >             null, transformer, basis, reducer).invoke();
3939      }
3940  
3941      /**
# Line 3940 | Line 3943 | public class ConcurrentHashMap<K, V>
3943       * of all entries using the given reducer to combine values,
3944       * and the given basis as an identity value.
3945       *
3946 +     * @param parallelismThreshold the (estimated) number of elements
3947 +     * needed for this operation to be executed in parallel
3948       * @param transformer a function returning the transformation
3949       * for an element
3950       * @param basis the identity (initial default value) for the reduction
# Line 3947 | Line 3952 | public class ConcurrentHashMap<K, V>
3952       * @return the result of accumulating the given transformation
3953       * of all entries
3954       */
3955 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
3955 >    public int reduceEntriesToInt(long parallelismThreshold,
3956 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
3957                                    int basis,
3958 <                                  IntByIntToInt reducer) {
3959 <        return ForkJoinTasks.reduceEntriesToInt
3960 <            (this, transformer, basis, reducer).invoke();
3958 >                                  IntBinaryOperator reducer) {
3959 >        if (transformer == null || reducer == null)
3960 >            throw new NullPointerException();
3961 >        return new MapReduceEntriesToIntTask<K,V>
3962 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3963 >             null, transformer, basis, reducer).invoke();
3964      }
3965  
3966 +
3967      /* ----------------Views -------------- */
3968  
3969      /**
3970       * Base class for views.
3971       */
3972 <    static abstract class CHMView<K, V> {
3973 <        final ConcurrentHashMap<K, V> map;
3974 <        CHMView(ConcurrentHashMap<K, V> map)  { this.map = map; }
3972 >    abstract static class CollectionView<K,V,E>
3973 >        implements Collection<E>, java.io.Serializable {
3974 >        private static final long serialVersionUID = 7249069246763182397L;
3975 >        final ConcurrentHashMap<K,V> map;
3976 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
3977  
3978          /**
3979           * Returns the map backing this view.
# Line 3970 | Line 3982 | public class ConcurrentHashMap<K, V>
3982           */
3983          public ConcurrentHashMap<K,V> getMap() { return map; }
3984  
3985 <        public final int size()                 { return map.size(); }
3986 <        public final boolean isEmpty()          { return map.isEmpty(); }
3987 <        public final void clear()               { map.clear(); }
3985 >        /**
3986 >         * Removes all of the elements from this view, by removing all
3987 >         * the mappings from the map backing this view.
3988 >         */
3989 >        public final void clear()      { map.clear(); }
3990 >        public final int size()        { return map.size(); }
3991 >        public final boolean isEmpty() { return map.isEmpty(); }
3992  
3993          // implementations below rely on concrete classes supplying these
3994 <        abstract public Iterator<?> iterator();
3995 <        abstract public boolean contains(Object o);
3996 <        abstract public boolean remove(Object o);
3994 >        // abstract methods
3995 >        /**
3996 >         * Returns a "weakly consistent" iterator that will never
3997 >         * throw {@link ConcurrentModificationException}, and
3998 >         * guarantees to traverse elements as they existed upon
3999 >         * construction of the iterator, and may (but is not
4000 >         * guaranteed to) reflect any modifications subsequent to
4001 >         * construction.
4002 >         */
4003 >        public abstract Iterator<E> iterator();
4004 >        public abstract boolean contains(Object o);
4005 >        public abstract boolean remove(Object o);
4006  
4007          private static final String oomeMsg = "Required array size too large";
4008  
4009          public final Object[] toArray() {
4010              long sz = map.mappingCount();
4011 <            if (sz > (long)(MAX_ARRAY_SIZE))
4011 >            if (sz > MAX_ARRAY_SIZE)
4012                  throw new OutOfMemoryError(oomeMsg);
4013              int n = (int)sz;
4014              Object[] r = new Object[n];
4015              int i = 0;
4016 <            Iterator<?> it = iterator();
3992 <            while (it.hasNext()) {
4016 >            for (E e : this) {
4017                  if (i == n) {
4018                      if (n >= MAX_ARRAY_SIZE)
4019                          throw new OutOfMemoryError(oomeMsg);
# Line 3999 | Line 4023 | public class ConcurrentHashMap<K, V>
4023                          n += (n >>> 1) + 1;
4024                      r = Arrays.copyOf(r, n);
4025                  }
4026 <                r[i++] = it.next();
4026 >                r[i++] = e;
4027              }
4028              return (i == n) ? r : Arrays.copyOf(r, i);
4029          }
4030  
4031 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4031 >        public final <T> T[] toArray(T[] a) {
4032              long sz = map.mappingCount();
4033 <            if (sz > (long)(MAX_ARRAY_SIZE))
4033 >            if (sz > MAX_ARRAY_SIZE)
4034                  throw new OutOfMemoryError(oomeMsg);
4035              int m = (int)sz;
4036              T[] r = (a.length >= m) ? a :
# Line 4014 | Line 4038 | public class ConcurrentHashMap<K, V>
4038                  .newInstance(a.getClass().getComponentType(), m);
4039              int n = r.length;
4040              int i = 0;
4041 <            Iterator<?> it = iterator();
4018 <            while (it.hasNext()) {
4041 >            for (E e : this) {
4042                  if (i == n) {
4043                      if (n >= MAX_ARRAY_SIZE)
4044                          throw new OutOfMemoryError(oomeMsg);
# Line 4025 | Line 4048 | public class ConcurrentHashMap<K, V>
4048                          n += (n >>> 1) + 1;
4049                      r = Arrays.copyOf(r, n);
4050                  }
4051 <                r[i++] = (T)it.next();
4051 >                r[i++] = (T)e;
4052              }
4053              if (a == r && i < n) {
4054                  r[i] = null; // null-terminate
# Line 4034 | Line 4057 | public class ConcurrentHashMap<K, V>
4057              return (i == n) ? r : Arrays.copyOf(r, i);
4058          }
4059  
4060 <        public final int hashCode() {
4061 <            int h = 0;
4062 <            for (Iterator<?> it = iterator(); it.hasNext();)
4063 <                h += it.next().hashCode();
4064 <            return h;
4065 <        }
4066 <
4060 >        /**
4061 >         * Returns a string representation of this collection.
4062 >         * The string representation consists of the string representations
4063 >         * of the collection's elements in the order they are returned by
4064 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4065 >         * Adjacent elements are separated by the characters {@code ", "}
4066 >         * (comma and space).  Elements are converted to strings as by
4067 >         * {@link String#valueOf(Object)}.
4068 >         *
4069 >         * @return a string representation of this collection
4070 >         */
4071          public final String toString() {
4072              StringBuilder sb = new StringBuilder();
4073              sb.append('[');
4074 <            Iterator<?> it = iterator();
4074 >            Iterator<E> it = iterator();
4075              if (it.hasNext()) {
4076                  for (;;) {
4077                      Object e = it.next();
# Line 4059 | Line 4086 | public class ConcurrentHashMap<K, V>
4086  
4087          public final boolean containsAll(Collection<?> c) {
4088              if (c != this) {
4089 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4063 <                    Object e = it.next();
4089 >                for (Object e : c) {
4090                      if (e == null || !contains(e))
4091                          return false;
4092                  }
# Line 4070 | Line 4096 | public class ConcurrentHashMap<K, V>
4096  
4097          public final boolean removeAll(Collection<?> c) {
4098              boolean modified = false;
4099 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4099 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4100                  if (c.contains(it.next())) {
4101                      it.remove();
4102                      modified = true;
# Line 4081 | Line 4107 | public class ConcurrentHashMap<K, V>
4107  
4108          public final boolean retainAll(Collection<?> c) {
4109              boolean modified = false;
4110 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4110 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4111                  if (!c.contains(it.next())) {
4112                      it.remove();
4113                      modified = true;
# Line 4095 | Line 4121 | public class ConcurrentHashMap<K, V>
4121      /**
4122       * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4123       * which additions may optionally be enabled by mapping to a
4124 <     * common value.  This class cannot be directly instantiated. See
4125 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4126 <     * {@link #newKeySet(int)}.
4124 >     * common value.  This class cannot be directly instantiated.
4125 >     * See {@link #keySet() keySet()},
4126 >     * {@link #keySet(Object) keySet(V)},
4127 >     * {@link #newKeySet() newKeySet()},
4128 >     * {@link #newKeySet(int) newKeySet(int)}.
4129       */
4130 <    public static class KeySetView<K,V> extends CHMView<K,V> implements Set<K>, java.io.Serializable {
4130 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4131 >        implements Set<K>, java.io.Serializable {
4132          private static final long serialVersionUID = 7249069246763182397L;
4133          private final V value;
4134 <        KeySetView(ConcurrentHashMap<K, V> map, V value) {  // non-public
4134 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4135              super(map);
4136              this.value = value;
4137          }
# Line 4112 | Line 4141 | public class ConcurrentHashMap<K, V>
4141           * or {@code null} if additions are not supported.
4142           *
4143           * @return the default mapped value for additions, or {@code null}
4144 <         * if not supported.
4144 >         * if not supported
4145           */
4146          public V getMappedValue() { return value; }
4147  
4148 <        // implement Set API
4149 <
4148 >        /**
4149 >         * {@inheritDoc}
4150 >         * @throws NullPointerException if the specified key is null
4151 >         */
4152          public boolean contains(Object o) { return map.containsKey(o); }
4122        public boolean remove(Object o)   { return map.remove(o) != null; }
4153  
4154          /**
4155 <         * Returns a "weakly consistent" iterator that will never
4156 <         * throw {@link ConcurrentModificationException}, and
4157 <         * guarantees to traverse elements as they existed upon
4158 <         * construction of the iterator, and may (but is not
4159 <         * guaranteed to) reflect any modifications subsequent to
4160 <         * construction.
4155 >         * Removes the key from this map view, by removing the key (and its
4156 >         * corresponding value) from the backing map.  This method does
4157 >         * nothing if the key is not in the map.
4158 >         *
4159 >         * @param  o the key to be removed from the backing map
4160 >         * @return {@code true} if the backing map contained the specified key
4161 >         * @throws NullPointerException if the specified key is null
4162 >         */
4163 >        public boolean remove(Object o) { return map.remove(o) != null; }
4164 >
4165 >        /**
4166 >         * @return an iterator over the keys of the backing map
4167 >         */
4168 >        public Iterator<K> iterator() {
4169 >            Node<K,V>[] t;
4170 >            ConcurrentHashMap<K,V> m = map;
4171 >            int f = (t = m.table) == null ? 0 : t.length;
4172 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4173 >        }
4174 >
4175 >        /**
4176 >         * Adds the specified key to this set view by mapping the key to
4177 >         * the default mapped value in the backing map, if defined.
4178           *
4179 <         * @return an iterator over the keys of this map
4179 >         * @param e key to be added
4180 >         * @return {@code true} if this set changed as a result of the call
4181 >         * @throws NullPointerException if the specified key is null
4182 >         * @throws UnsupportedOperationException if no default mapped value
4183 >         * for additions was provided
4184           */
4134        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4185          public boolean add(K e) {
4186              V v;
4187              if ((v = value) == null)
4188                  throw new UnsupportedOperationException();
4189 <            if (e == null)
4140 <                throw new NullPointerException();
4141 <            return map.internalPutIfAbsent(e, v) == null;
4189 >            return map.internalPut(e, v, true) == null;
4190          }
4191 +
4192 +        /**
4193 +         * Adds all of the elements in the specified collection to this set,
4194 +         * as if by calling {@link #add} on each one.
4195 +         *
4196 +         * @param c the elements to be inserted into this set
4197 +         * @return {@code true} if this set changed as a result of the call
4198 +         * @throws NullPointerException if the collection or any of its
4199 +         * elements are {@code null}
4200 +         * @throws UnsupportedOperationException if no default mapped value
4201 +         * for additions was provided
4202 +         */
4203          public boolean addAll(Collection<? extends K> c) {
4204              boolean added = false;
4205              V v;
4206              if ((v = value) == null)
4207                  throw new UnsupportedOperationException();
4208              for (K e : c) {
4209 <                if (e == null)
4150 <                    throw new NullPointerException();
4151 <                if (map.internalPutIfAbsent(e, v) == null)
4209 >                if (map.internalPut(e, v, true) == null)
4210                      added = true;
4211              }
4212              return added;
4213          }
4214 +
4215 +        public int hashCode() {
4216 +            int h = 0;
4217 +            for (K e : this)
4218 +                h += e.hashCode();
4219 +            return h;
4220 +        }
4221 +
4222          public boolean equals(Object o) {
4223              Set<?> c;
4224              return ((o instanceof Set) &&
# Line 4160 | Line 4226 | public class ConcurrentHashMap<K, V>
4226                       (containsAll(c) && c.containsAll(this))));
4227          }
4228  
4229 <        /**
4230 <         * Performs the given action for each key.
4231 <         *
4232 <         * @param action the action
4233 <         */
4234 <        public void forEach(Action<K> action) {
4169 <            ForkJoinTasks.forEachKey
4170 <                (map, action).invoke();
4171 <        }
4172 <
4173 <        /**
4174 <         * Performs the given action for each non-null transformation
4175 <         * of each key.
4176 <         *
4177 <         * @param transformer a function returning the transformation
4178 <         * for an element, or null of there is no transformation (in
4179 <         * which case the action is not applied).
4180 <         * @param action the action
4181 <         */
4182 <        public <U> void forEach(Fun<? super K, ? extends U> transformer,
4183 <                                Action<U> action) {
4184 <            ForkJoinTasks.forEachKey
4185 <                (map, transformer, action).invoke();
4186 <        }
4187 <
4188 <        /**
4189 <         * Returns a non-null result from applying the given search
4190 <         * function on each key, or null if none. Upon success,
4191 <         * further element processing is suppressed and the results of
4192 <         * any other parallel invocations of the search function are
4193 <         * ignored.
4194 <         *
4195 <         * @param searchFunction a function returning a non-null
4196 <         * result on success, else null
4197 <         * @return a non-null result from applying the given search
4198 <         * function on each key, or null if none
4199 <         */
4200 <        public <U> U search(Fun<? super K, ? extends U> searchFunction) {
4201 <            return ForkJoinTasks.searchKeys
4202 <                (map, searchFunction).invoke();
4203 <        }
4204 <
4205 <        /**
4206 <         * Returns the result of accumulating all keys using the given
4207 <         * reducer to combine values, or null if none.
4208 <         *
4209 <         * @param reducer a commutative associative combining function
4210 <         * @return the result of accumulating all keys using the given
4211 <         * reducer to combine values, or null if none
4212 <         */
4213 <        public K reduce(BiFun<? super K, ? super K, ? extends K> reducer) {
4214 <            return ForkJoinTasks.reduceKeys
4215 <                (map, reducer).invoke();
4216 <        }
4217 <
4218 <        /**
4219 <         * Returns the result of accumulating the given transformation
4220 <         * of all keys using the given reducer to combine values, and
4221 <         * the given basis as an identity value.
4222 <         *
4223 <         * @param transformer a function returning the transformation
4224 <         * for an element
4225 <         * @param basis the identity (initial default value) for the reduction
4226 <         * @param reducer a commutative associative combining function
4227 <         * @return  the result of accumulating the given transformation
4228 <         * of all keys
4229 <         */
4230 <        public double reduceToDouble(ObjectToDouble<? super K> transformer,
4231 <                                     double basis,
4232 <                                     DoubleByDoubleToDouble reducer) {
4233 <            return ForkJoinTasks.reduceKeysToDouble
4234 <                (map, transformer, basis, reducer).invoke();
4235 <        }
4236 <
4237 <
4238 <        /**
4239 <         * Returns the result of accumulating the given transformation
4240 <         * of all keys using the given reducer to combine values, and
4241 <         * the given basis as an identity value.
4242 <         *
4243 <         * @param transformer a function returning the transformation
4244 <         * for an element
4245 <         * @param basis the identity (initial default value) for the reduction
4246 <         * @param reducer a commutative associative combining function
4247 <         * @return the result of accumulating the given transformation
4248 <         * of all keys
4249 <         */
4250 <        public long reduceToLong(ObjectToLong<? super K> transformer,
4251 <                                 long basis,
4252 <                                 LongByLongToLong reducer) {
4253 <            return ForkJoinTasks.reduceKeysToLong
4254 <                (map, transformer, basis, reducer).invoke();
4229 >        public Spliterator<K> spliterator() {
4230 >            Node<K,V>[] t;
4231 >            ConcurrentHashMap<K,V> m = map;
4232 >            long n = m.sumCount();
4233 >            int f = (t = m.table) == null ? 0 : t.length;
4234 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4235          }
4236  
4237 <        /**
4238 <         * Returns the result of accumulating the given transformation
4239 <         * of all keys using the given reducer to combine values, and
4240 <         * the given basis as an identity value.
4241 <         *
4242 <         * @param transformer a function returning the transformation
4243 <         * for an element
4244 <         * @param basis the identity (initial default value) for the reduction
4265 <         * @param reducer a commutative associative combining function
4266 <         * @return the result of accumulating the given transformation
4267 <         * of all keys
4268 <         */
4269 <        public int reduceToInt(ObjectToInt<? super K> transformer,
4270 <                               int basis,
4271 <                               IntByIntToInt reducer) {
4272 <            return ForkJoinTasks.reduceKeysToInt
4273 <                (map, transformer, basis, reducer).invoke();
4237 >        public void forEach(Consumer<? super K> action) {
4238 >            if (action == null) throw new NullPointerException();
4239 >            Node<K,V>[] t;
4240 >            if ((t = map.table) != null) {
4241 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4242 >                for (Node<K,V> p; (p = it.advance()) != null; )
4243 >                    action.accept((K)p.key);
4244 >            }
4245          }
4275
4246      }
4247  
4248      /**
4249       * A view of a ConcurrentHashMap as a {@link Collection} of
4250       * values, in which additions are disabled. This class cannot be
4251 <     * directly instantiated. See {@link #values},
4282 <     *
4283 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4284 <     * that will never throw {@link ConcurrentModificationException},
4285 <     * and guarantees to traverse elements as they existed upon
4286 <     * construction of the iterator, and may (but is not guaranteed to)
4287 <     * reflect any modifications subsequent to construction.
4251 >     * directly instantiated. See {@link #values()}.
4252       */
4253 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4254 <        implements Collection<V> {
4255 <        ValuesView(ConcurrentHashMap<K, V> map)   { super(map); }
4256 <        public final boolean contains(Object o) { return map.containsValue(o); }
4253 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4254 >        implements Collection<V>, java.io.Serializable {
4255 >        private static final long serialVersionUID = 2249069246763182397L;
4256 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4257 >        public final boolean contains(Object o) {
4258 >            return map.containsValue(o);
4259 >        }
4260 >
4261          public final boolean remove(Object o) {
4262              if (o != null) {
4263 <                Iterator<V> it = new ValueIterator<K,V>(map);
4296 <                while (it.hasNext()) {
4263 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4264                      if (o.equals(it.next())) {
4265                          it.remove();
4266                          return true;
# Line 4303 | Line 4270 | public class ConcurrentHashMap<K, V>
4270              return false;
4271          }
4272  
4306        /**
4307         * Returns a "weakly consistent" iterator that will never
4308         * throw {@link ConcurrentModificationException}, and
4309         * guarantees to traverse elements as they existed upon
4310         * construction of the iterator, and may (but is not
4311         * guaranteed to) reflect any modifications subsequent to
4312         * construction.
4313         *
4314         * @return an iterator over the values of this map
4315         */
4273          public final Iterator<V> iterator() {
4274 <            return new ValueIterator<K,V>(map);
4274 >            ConcurrentHashMap<K,V> m = map;
4275 >            Node<K,V>[] t;
4276 >            int f = (t = m.table) == null ? 0 : t.length;
4277 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4278          }
4279 +
4280          public final boolean add(V e) {
4281              throw new UnsupportedOperationException();
4282          }
# Line 4323 | Line 4284 | public class ConcurrentHashMap<K, V>
4284              throw new UnsupportedOperationException();
4285          }
4286  
4287 <        /**
4288 <         * Performs the given action for each value.
4289 <         *
4290 <         * @param action the action
4291 <         */
4292 <        public void forEach(Action<V> action) {
4332 <            ForkJoinTasks.forEachValue
4333 <                (map, action).invoke();
4334 <        }
4335 <
4336 <        /**
4337 <         * Performs the given action for each non-null transformation
4338 <         * of each value.
4339 <         *
4340 <         * @param transformer a function returning the transformation
4341 <         * for an element, or null of there is no transformation (in
4342 <         * which case the action is not applied).
4343 <         */
4344 <        public <U> void forEach(Fun<? super V, ? extends U> transformer,
4345 <                                     Action<U> action) {
4346 <            ForkJoinTasks.forEachValue
4347 <                (map, transformer, action).invoke();
4348 <        }
4349 <
4350 <        /**
4351 <         * Returns a non-null result from applying the given search
4352 <         * function on each value, or null if none.  Upon success,
4353 <         * further element processing is suppressed and the results of
4354 <         * any other parallel invocations of the search function are
4355 <         * ignored.
4356 <         *
4357 <         * @param searchFunction a function returning a non-null
4358 <         * result on success, else null
4359 <         * @return a non-null result from applying the given search
4360 <         * function on each value, or null if none
4361 <         *
4362 <         */
4363 <        public <U> U search(Fun<? super V, ? extends U> searchFunction) {
4364 <            return ForkJoinTasks.searchValues
4365 <                (map, searchFunction).invoke();
4366 <        }
4367 <
4368 <        /**
4369 <         * Returns the result of accumulating all values using the
4370 <         * given reducer to combine values, or null if none.
4371 <         *
4372 <         * @param reducer a commutative associative combining function
4373 <         * @return  the result of accumulating all values
4374 <         */
4375 <        public V reduce(BiFun<? super V, ? super V, ? extends V> reducer) {
4376 <            return ForkJoinTasks.reduceValues
4377 <                (map, reducer).invoke();
4378 <        }
4379 <
4380 <        /**
4381 <         * Returns the result of accumulating the given transformation
4382 <         * of all values using the given reducer to combine values, or
4383 <         * null if none.
4384 <         *
4385 <         * @param transformer a function returning the transformation
4386 <         * for an element, or null of there is no transformation (in
4387 <         * which case it is not combined).
4388 <         * @param reducer a commutative associative combining function
4389 <         * @return the result of accumulating the given transformation
4390 <         * of all values
4391 <         */
4392 <        public <U> U reduce(Fun<? super V, ? extends U> transformer,
4393 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
4394 <            return ForkJoinTasks.reduceValues
4395 <                (map, transformer, reducer).invoke();
4287 >        public Spliterator<V> spliterator() {
4288 >            Node<K,V>[] t;
4289 >            ConcurrentHashMap<K,V> m = map;
4290 >            long n = m.sumCount();
4291 >            int f = (t = m.table) == null ? 0 : t.length;
4292 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4293          }
4294  
4295 <        /**
4296 <         * Returns the result of accumulating the given transformation
4297 <         * of all values using the given reducer to combine values,
4298 <         * and the given basis as an identity value.
4299 <         *
4300 <         * @param transformer a function returning the transformation
4301 <         * for an element
4302 <         * @param basis the identity (initial default value) for the reduction
4406 <         * @param reducer a commutative associative combining function
4407 <         * @return the result of accumulating the given transformation
4408 <         * of all values
4409 <         */
4410 <        public double reduceToDouble(ObjectToDouble<? super V> transformer,
4411 <                                     double basis,
4412 <                                     DoubleByDoubleToDouble reducer) {
4413 <            return ForkJoinTasks.reduceValuesToDouble
4414 <                (map, transformer, basis, reducer).invoke();
4415 <        }
4416 <
4417 <        /**
4418 <         * Returns the result of accumulating the given transformation
4419 <         * of all values using the given reducer to combine values,
4420 <         * and the given basis as an identity value.
4421 <         *
4422 <         * @param transformer a function returning the transformation
4423 <         * for an element
4424 <         * @param basis the identity (initial default value) for the reduction
4425 <         * @param reducer a commutative associative combining function
4426 <         * @return the result of accumulating the given transformation
4427 <         * of all values
4428 <         */
4429 <        public long reduceToLong(ObjectToLong<? super V> transformer,
4430 <                                 long basis,
4431 <                                 LongByLongToLong reducer) {
4432 <            return ForkJoinTasks.reduceValuesToLong
4433 <                (map, transformer, basis, reducer).invoke();
4434 <        }
4435 <
4436 <        /**
4437 <         * Returns the result of accumulating the given transformation
4438 <         * of all values using the given reducer to combine values,
4439 <         * and the given basis as an identity value.
4440 <         *
4441 <         * @param transformer a function returning the transformation
4442 <         * for an element
4443 <         * @param basis the identity (initial default value) for the reduction
4444 <         * @param reducer a commutative associative combining function
4445 <         * @return the result of accumulating the given transformation
4446 <         * of all values
4447 <         */
4448 <        public int reduceToInt(ObjectToInt<? super V> transformer,
4449 <                               int basis,
4450 <                               IntByIntToInt reducer) {
4451 <            return ForkJoinTasks.reduceValuesToInt
4452 <                (map, transformer, basis, reducer).invoke();
4295 >        public void forEach(Consumer<? super V> action) {
4296 >            if (action == null) throw new NullPointerException();
4297 >            Node<K,V>[] t;
4298 >            if ((t = map.table) != null) {
4299 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4300 >                for (Node<K,V> p; (p = it.advance()) != null; )
4301 >                    action.accept(p.val);
4302 >            }
4303          }
4454
4304      }
4305  
4306      /**
4307       * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4308       * entries.  This class cannot be directly instantiated. See
4309 <     * {@link #entrySet}.
4309 >     * {@link #entrySet()}.
4310       */
4311 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4312 <        implements Set<Map.Entry<K,V>> {
4313 <        EntrySetView(ConcurrentHashMap<K, V> map) { super(map); }
4314 <        public final boolean contains(Object o) {
4311 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4312 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4313 >        private static final long serialVersionUID = 2249069246763182397L;
4314 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4315 >
4316 >        public boolean contains(Object o) {
4317              Object k, v, r; Map.Entry<?,?> e;
4318              return ((o instanceof Map.Entry) &&
4319                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4470 | Line 4321 | public class ConcurrentHashMap<K, V>
4321                      (v = e.getValue()) != null &&
4322                      (v == r || v.equals(r)));
4323          }
4324 <        public final boolean remove(Object o) {
4324 >
4325 >        public boolean remove(Object o) {
4326              Object k, v; Map.Entry<?,?> e;
4327              return ((o instanceof Map.Entry) &&
4328                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4479 | Line 4331 | public class ConcurrentHashMap<K, V>
4331          }
4332  
4333          /**
4334 <         * Returns a "weakly consistent" iterator that will never
4483 <         * throw {@link ConcurrentModificationException}, and
4484 <         * guarantees to traverse elements as they existed upon
4485 <         * construction of the iterator, and may (but is not
4486 <         * guaranteed to) reflect any modifications subsequent to
4487 <         * construction.
4488 <         *
4489 <         * @return an iterator over the entries of this map
4334 >         * @return an iterator over the entries of the backing map
4335           */
4336 <        public final Iterator<Map.Entry<K,V>> iterator() {
4337 <            return new EntryIterator<K,V>(map);
4336 >        public Iterator<Map.Entry<K,V>> iterator() {
4337 >            ConcurrentHashMap<K,V> m = map;
4338 >            Node<K,V>[] t;
4339 >            int f = (t = m.table) == null ? 0 : t.length;
4340 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4341          }
4342  
4343 <        public final boolean add(Entry<K,V> e) {
4344 <            K key = e.getKey();
4497 <            V value = e.getValue();
4498 <            if (key == null || value == null)
4499 <                throw new NullPointerException();
4500 <            return map.internalPut(key, value) == null;
4343 >        public boolean add(Entry<K,V> e) {
4344 >            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4345          }
4346 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4346 >
4347 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4348              boolean added = false;
4349              for (Entry<K,V> e : c) {
4350                  if (add(e))
# Line 4507 | Line 4352 | public class ConcurrentHashMap<K, V>
4352              }
4353              return added;
4354          }
4355 <        public boolean equals(Object o) {
4355 >
4356 >        public final int hashCode() {
4357 >            int h = 0;
4358 >            Node<K,V>[] t;
4359 >            if ((t = map.table) != null) {
4360 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4361 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4362 >                    h += p.hashCode();
4363 >                }
4364 >            }
4365 >            return h;
4366 >        }
4367 >
4368 >        public final boolean equals(Object o) {
4369              Set<?> c;
4370              return ((o instanceof Set) &&
4371                      ((c = (Set<?>)o) == this ||
4372                       (containsAll(c) && c.containsAll(this))));
4373          }
4374  
4375 <        /**
4376 <         * Performs the given action for each entry.
4377 <         *
4378 <         * @param action the action
4379 <         */
4380 <        public void forEach(Action<Map.Entry<K,V>> action) {
4523 <            ForkJoinTasks.forEachEntry
4524 <                (map, action).invoke();
4525 <        }
4526 <
4527 <        /**
4528 <         * Performs the given action for each non-null transformation
4529 <         * of each entry.
4530 <         *
4531 <         * @param transformer a function returning the transformation
4532 <         * for an element, or null of there is no transformation (in
4533 <         * which case the action is not applied).
4534 <         * @param action the action
4535 <         */
4536 <        public <U> void forEach(Fun<Map.Entry<K,V>, ? extends U> transformer,
4537 <                                Action<U> action) {
4538 <            ForkJoinTasks.forEachEntry
4539 <                (map, transformer, action).invoke();
4540 <        }
4541 <
4542 <        /**
4543 <         * Returns a non-null result from applying the given search
4544 <         * function on each entry, or null if none.  Upon success,
4545 <         * further element processing is suppressed and the results of
4546 <         * any other parallel invocations of the search function are
4547 <         * ignored.
4548 <         *
4549 <         * @param searchFunction a function returning a non-null
4550 <         * result on success, else null
4551 <         * @return a non-null result from applying the given search
4552 <         * function on each entry, or null if none
4553 <         */
4554 <        public <U> U search(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4555 <            return ForkJoinTasks.searchEntries
4556 <                (map, searchFunction).invoke();
4557 <        }
4558 <
4559 <        /**
4560 <         * Returns the result of accumulating all entries using the
4561 <         * given reducer to combine values, or null if none.
4562 <         *
4563 <         * @param reducer a commutative associative combining function
4564 <         * @return the result of accumulating all entries
4565 <         */
4566 <        public Map.Entry<K,V> reduce(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4567 <            return ForkJoinTasks.reduceEntries
4568 <                (map, reducer).invoke();
4569 <        }
4570 <
4571 <        /**
4572 <         * Returns the result of accumulating the given transformation
4573 <         * of all entries using the given reducer to combine values,
4574 <         * or null if none.
4575 <         *
4576 <         * @param transformer a function returning the transformation
4577 <         * for an element, or null of there is no transformation (in
4578 <         * which case it is not combined).
4579 <         * @param reducer a commutative associative combining function
4580 <         * @return the result of accumulating the given transformation
4581 <         * of all entries
4582 <         */
4583 <        public <U> U reduce(Fun<Map.Entry<K,V>, ? extends U> transformer,
4584 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
4585 <            return ForkJoinTasks.reduceEntries
4586 <                (map, transformer, reducer).invoke();
4587 <        }
4588 <
4589 <        /**
4590 <         * Returns the result of accumulating the given transformation
4591 <         * of all entries using the given reducer to combine values,
4592 <         * and the given basis as an identity value.
4593 <         *
4594 <         * @param transformer a function returning the transformation
4595 <         * for an element
4596 <         * @param basis the identity (initial default value) for the reduction
4597 <         * @param reducer a commutative associative combining function
4598 <         * @return the result of accumulating the given transformation
4599 <         * of all entries
4600 <         */
4601 <        public double reduceToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4602 <                                     double basis,
4603 <                                     DoubleByDoubleToDouble reducer) {
4604 <            return ForkJoinTasks.reduceEntriesToDouble
4605 <                (map, transformer, basis, reducer).invoke();
4606 <        }
4607 <
4608 <        /**
4609 <         * Returns the result of accumulating the given transformation
4610 <         * of all entries using the given reducer to combine values,
4611 <         * and the given basis as an identity value.
4612 <         *
4613 <         * @param transformer a function returning the transformation
4614 <         * for an element
4615 <         * @param basis the identity (initial default value) for the reduction
4616 <         * @param reducer a commutative associative combining function
4617 <         * @return  the result of accumulating the given transformation
4618 <         * of all entries
4619 <         */
4620 <        public long reduceToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4621 <                                 long basis,
4622 <                                 LongByLongToLong reducer) {
4623 <            return ForkJoinTasks.reduceEntriesToLong
4624 <                (map, transformer, basis, reducer).invoke();
4625 <        }
4626 <
4627 <        /**
4628 <         * Returns the result of accumulating the given transformation
4629 <         * of all entries using the given reducer to combine values,
4630 <         * and the given basis as an identity value.
4631 <         *
4632 <         * @param transformer a function returning the transformation
4633 <         * for an element
4634 <         * @param basis the identity (initial default value) for the reduction
4635 <         * @param reducer a commutative associative combining function
4636 <         * @return the result of accumulating the given transformation
4637 <         * of all entries
4638 <         */
4639 <        public int reduceToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4640 <                               int basis,
4641 <                               IntByIntToInt reducer) {
4642 <            return ForkJoinTasks.reduceEntriesToInt
4643 <                (map, transformer, basis, reducer).invoke();
4644 <        }
4645 <
4646 <    }
4647 <
4648 <    // ---------------------------------------------------------------------
4649 <
4650 <    /**
4651 <     * Predefined tasks for performing bulk parallel operations on
4652 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
4653 <     * for bulk operations. Each method has the same name, but returns
4654 <     * a task rather than invoking it. These methods may be useful in
4655 <     * custom applications such as submitting a task without waiting
4656 <     * for completion, using a custom pool, or combining with other
4657 <     * tasks.
4658 <     */
4659 <    public static class ForkJoinTasks {
4660 <        private ForkJoinTasks() {}
4661 <
4662 <        /**
4663 <         * Returns a task that when invoked, performs the given
4664 <         * action for each (key, value)
4665 <         *
4666 <         * @param map the map
4667 <         * @param action the action
4668 <         * @return the task
4669 <         */
4670 <        public static <K,V> ForkJoinTask<Void> forEach
4671 <            (ConcurrentHashMap<K,V> map,
4672 <             BiAction<K,V> action) {
4673 <            if (action == null) throw new NullPointerException();
4674 <            return new ForEachMappingTask<K,V>(map, null, -1, null, action);
4675 <        }
4676 <
4677 <        /**
4678 <         * Returns a task that when invoked, performs the given
4679 <         * action for each non-null transformation of each (key, value)
4680 <         *
4681 <         * @param map the map
4682 <         * @param transformer a function returning the transformation
4683 <         * for an element, or null if there is no transformation (in
4684 <         * which case the action is not applied)
4685 <         * @param action the action
4686 <         * @return the task
4687 <         */
4688 <        public static <K,V,U> ForkJoinTask<Void> forEach
4689 <            (ConcurrentHashMap<K,V> map,
4690 <             BiFun<? super K, ? super V, ? extends U> transformer,
4691 <             Action<U> action) {
4692 <            if (transformer == null || action == null)
4693 <                throw new NullPointerException();
4694 <            return new ForEachTransformedMappingTask<K,V,U>
4695 <                (map, null, -1, null, transformer, action);
4696 <        }
4697 <
4698 <        /**
4699 <         * Returns a task that when invoked, returns a non-null result
4700 <         * from applying the given search function on each (key,
4701 <         * value), or null if none. Upon success, further element
4702 <         * processing is suppressed and the results of any other
4703 <         * parallel invocations of the search function are ignored.
4704 <         *
4705 <         * @param map the map
4706 <         * @param searchFunction a function returning a non-null
4707 <         * result on success, else null
4708 <         * @return the task
4709 <         */
4710 <        public static <K,V,U> ForkJoinTask<U> search
4711 <            (ConcurrentHashMap<K,V> map,
4712 <             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4713 <            if (searchFunction == null) throw new NullPointerException();
4714 <            return new SearchMappingsTask<K,V,U>
4715 <                (map, null, -1, null, searchFunction,
4716 <                 new AtomicReference<U>());
4717 <        }
4718 <
4719 <        /**
4720 <         * Returns a task that when invoked, returns the result of
4721 <         * accumulating the given transformation of all (key, value) pairs
4722 <         * using the given reducer to combine values, or null if none.
4723 <         *
4724 <         * @param map the map
4725 <         * @param transformer a function returning the transformation
4726 <         * for an element, or null if there is no transformation (in
4727 <         * which case it is not combined).
4728 <         * @param reducer a commutative associative combining function
4729 <         * @return the task
4730 <         */
4731 <        public static <K,V,U> ForkJoinTask<U> reduce
4732 <            (ConcurrentHashMap<K,V> map,
4733 <             BiFun<? super K, ? super V, ? extends U> transformer,
4734 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4735 <            if (transformer == null || reducer == null)
4736 <                throw new NullPointerException();
4737 <            return new MapReduceMappingsTask<K,V,U>
4738 <                (map, null, -1, null, transformer, reducer);
4739 <        }
4740 <
4741 <        /**
4742 <         * Returns a task that when invoked, returns the result of
4743 <         * accumulating the given transformation of all (key, value) pairs
4744 <         * using the given reducer to combine values, and the given
4745 <         * basis as an identity value.
4746 <         *
4747 <         * @param map the map
4748 <         * @param transformer a function returning the transformation
4749 <         * for an element
4750 <         * @param basis the identity (initial default value) for the reduction
4751 <         * @param reducer a commutative associative combining function
4752 <         * @return the task
4753 <         */
4754 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4755 <            (ConcurrentHashMap<K,V> map,
4756 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
4757 <             double basis,
4758 <             DoubleByDoubleToDouble reducer) {
4759 <            if (transformer == null || reducer == null)
4760 <                throw new NullPointerException();
4761 <            return new MapReduceMappingsToDoubleTask<K,V>
4762 <                (map, null, -1, null, transformer, basis, reducer);
4763 <        }
4764 <
4765 <        /**
4766 <         * Returns a task that when invoked, returns the result of
4767 <         * accumulating the given transformation of all (key, value) pairs
4768 <         * using the given reducer to combine values, and the given
4769 <         * basis as an identity value.
4770 <         *
4771 <         * @param map the map
4772 <         * @param transformer a function returning the transformation
4773 <         * for an element
4774 <         * @param basis the identity (initial default value) for the reduction
4775 <         * @param reducer a commutative associative combining function
4776 <         * @return the task
4777 <         */
4778 <        public static <K,V> ForkJoinTask<Long> reduceToLong
4779 <            (ConcurrentHashMap<K,V> map,
4780 <             ObjectByObjectToLong<? super K, ? super V> transformer,
4781 <             long basis,
4782 <             LongByLongToLong reducer) {
4783 <            if (transformer == null || reducer == null)
4784 <                throw new NullPointerException();
4785 <            return new MapReduceMappingsToLongTask<K,V>
4786 <                (map, null, -1, null, transformer, basis, reducer);
4787 <        }
4788 <
4789 <        /**
4790 <         * Returns a task that when invoked, returns the result of
4791 <         * accumulating the given transformation of all (key, value) pairs
4792 <         * using the given reducer to combine values, and the given
4793 <         * basis as an identity value.
4794 <         *
4795 <         * @param transformer a function returning the transformation
4796 <         * for an element
4797 <         * @param basis the identity (initial default value) for the reduction
4798 <         * @param reducer a commutative associative combining function
4799 <         * @return the task
4800 <         */
4801 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
4802 <            (ConcurrentHashMap<K,V> map,
4803 <             ObjectByObjectToInt<? super K, ? super V> transformer,
4804 <             int basis,
4805 <             IntByIntToInt reducer) {
4806 <            if (transformer == null || reducer == null)
4807 <                throw new NullPointerException();
4808 <            return new MapReduceMappingsToIntTask<K,V>
4809 <                (map, null, -1, null, transformer, basis, reducer);
4810 <        }
4811 <
4812 <        /**
4813 <         * Returns a task that when invoked, performs the given action
4814 <         * for each key.
4815 <         *
4816 <         * @param map the map
4817 <         * @param action the action
4818 <         * @return the task
4819 <         */
4820 <        public static <K,V> ForkJoinTask<Void> forEachKey
4821 <            (ConcurrentHashMap<K,V> map,
4822 <             Action<K> action) {
4823 <            if (action == null) throw new NullPointerException();
4824 <            return new ForEachKeyTask<K,V>(map, null, -1, null, action);
4825 <        }
4826 <
4827 <        /**
4828 <         * Returns a task that when invoked, performs the given action
4829 <         * for each non-null transformation of each key.
4830 <         *
4831 <         * @param map the map
4832 <         * @param transformer a function returning the transformation
4833 <         * for an element, or null if there is no transformation (in
4834 <         * which case the action is not applied)
4835 <         * @param action the action
4836 <         * @return the task
4837 <         */
4838 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
4839 <            (ConcurrentHashMap<K,V> map,
4840 <             Fun<? super K, ? extends U> transformer,
4841 <             Action<U> action) {
4842 <            if (transformer == null || action == null)
4843 <                throw new NullPointerException();
4844 <            return new ForEachTransformedKeyTask<K,V,U>
4845 <                (map, null, -1, null, transformer, action);
4846 <        }
4847 <
4848 <        /**
4849 <         * Returns a task that when invoked, returns a non-null result
4850 <         * from applying the given search function on each key, or
4851 <         * null if none.  Upon success, further element processing is
4852 <         * suppressed and the results of any other parallel
4853 <         * invocations of the search function are ignored.
4854 <         *
4855 <         * @param map the map
4856 <         * @param searchFunction a function returning a non-null
4857 <         * result on success, else null
4858 <         * @return the task
4859 <         */
4860 <        public static <K,V,U> ForkJoinTask<U> searchKeys
4861 <            (ConcurrentHashMap<K,V> map,
4862 <             Fun<? super K, ? extends U> searchFunction) {
4863 <            if (searchFunction == null) throw new NullPointerException();
4864 <            return new SearchKeysTask<K,V,U>
4865 <                (map, null, -1, null, searchFunction,
4866 <                 new AtomicReference<U>());
4867 <        }
4868 <
4869 <        /**
4870 <         * Returns a task that when invoked, returns the result of
4871 <         * accumulating all keys using the given reducer to combine
4872 <         * values, or null if none.
4873 <         *
4874 <         * @param map the map
4875 <         * @param reducer a commutative associative combining function
4876 <         * @return the task
4877 <         */
4878 <        public static <K,V> ForkJoinTask<K> reduceKeys
4879 <            (ConcurrentHashMap<K,V> map,
4880 <             BiFun<? super K, ? super K, ? extends K> reducer) {
4881 <            if (reducer == null) throw new NullPointerException();
4882 <            return new ReduceKeysTask<K,V>
4883 <                (map, null, -1, null, reducer);
4884 <        }
4885 <
4886 <        /**
4887 <         * Returns a task that when invoked, returns the result of
4888 <         * accumulating the given transformation of all keys using the given
4889 <         * reducer to combine values, or null if none.
4890 <         *
4891 <         * @param map the map
4892 <         * @param transformer a function returning the transformation
4893 <         * for an element, or null if there is no transformation (in
4894 <         * which case it is not combined).
4895 <         * @param reducer a commutative associative combining function
4896 <         * @return the task
4897 <         */
4898 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
4899 <            (ConcurrentHashMap<K,V> map,
4900 <             Fun<? super K, ? extends U> transformer,
4901 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4902 <            if (transformer == null || reducer == null)
4903 <                throw new NullPointerException();
4904 <            return new MapReduceKeysTask<K,V,U>
4905 <                (map, null, -1, null, transformer, reducer);
4906 <        }
4907 <
4908 <        /**
4909 <         * Returns a task that when invoked, returns the result of
4910 <         * accumulating the given transformation of all keys using the given
4911 <         * reducer to combine values, and the given basis as an
4912 <         * identity value.
4913 <         *
4914 <         * @param map the map
4915 <         * @param transformer a function returning the transformation
4916 <         * for an element
4917 <         * @param basis the identity (initial default value) for the reduction
4918 <         * @param reducer a commutative associative combining function
4919 <         * @return the task
4920 <         */
4921 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
4922 <            (ConcurrentHashMap<K,V> map,
4923 <             ObjectToDouble<? super K> transformer,
4924 <             double basis,
4925 <             DoubleByDoubleToDouble reducer) {
4926 <            if (transformer == null || reducer == null)
4927 <                throw new NullPointerException();
4928 <            return new MapReduceKeysToDoubleTask<K,V>
4929 <                (map, null, -1, null, transformer, basis, reducer);
4930 <        }
4931 <
4932 <        /**
4933 <         * Returns a task that when invoked, returns the result of
4934 <         * accumulating the given transformation of all keys using the given
4935 <         * reducer to combine values, and the given basis as an
4936 <         * identity value.
4937 <         *
4938 <         * @param map the map
4939 <         * @param transformer a function returning the transformation
4940 <         * for an element
4941 <         * @param basis the identity (initial default value) for the reduction
4942 <         * @param reducer a commutative associative combining function
4943 <         * @return the task
4944 <         */
4945 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
4946 <            (ConcurrentHashMap<K,V> map,
4947 <             ObjectToLong<? super K> transformer,
4948 <             long basis,
4949 <             LongByLongToLong reducer) {
4950 <            if (transformer == null || reducer == null)
4951 <                throw new NullPointerException();
4952 <            return new MapReduceKeysToLongTask<K,V>
4953 <                (map, null, -1, null, transformer, basis, reducer);
4954 <        }
4955 <
4956 <        /**
4957 <         * Returns a task that when invoked, returns the result of
4958 <         * accumulating the given transformation of all keys using the given
4959 <         * reducer to combine values, and the given basis as an
4960 <         * identity value.
4961 <         *
4962 <         * @param map the map
4963 <         * @param transformer a function returning the transformation
4964 <         * for an element
4965 <         * @param basis the identity (initial default value) for the reduction
4966 <         * @param reducer a commutative associative combining function
4967 <         * @return the task
4968 <         */
4969 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
4970 <            (ConcurrentHashMap<K,V> map,
4971 <             ObjectToInt<? super K> transformer,
4972 <             int basis,
4973 <             IntByIntToInt reducer) {
4974 <            if (transformer == null || reducer == null)
4975 <                throw new NullPointerException();
4976 <            return new MapReduceKeysToIntTask<K,V>
4977 <                (map, null, -1, null, transformer, basis, reducer);
4978 <        }
4979 <
4980 <        /**
4981 <         * Returns a task that when invoked, performs the given action
4982 <         * for each value.
4983 <         *
4984 <         * @param map the map
4985 <         * @param action the action
4986 <         */
4987 <        public static <K,V> ForkJoinTask<Void> forEachValue
4988 <            (ConcurrentHashMap<K,V> map,
4989 <             Action<V> action) {
4990 <            if (action == null) throw new NullPointerException();
4991 <            return new ForEachValueTask<K,V>(map, null, -1, null, action);
4992 <        }
4993 <
4994 <        /**
4995 <         * Returns a task that when invoked, performs the given action
4996 <         * for each non-null transformation of each value.
4997 <         *
4998 <         * @param map the map
4999 <         * @param transformer a function returning the transformation
5000 <         * for an element, or null if there is no transformation (in
5001 <         * which case the action is not applied)
5002 <         * @param action the action
5003 <         */
5004 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
5005 <            (ConcurrentHashMap<K,V> map,
5006 <             Fun<? super V, ? extends U> transformer,
5007 <             Action<U> action) {
5008 <            if (transformer == null || action == null)
5009 <                throw new NullPointerException();
5010 <            return new ForEachTransformedValueTask<K,V,U>
5011 <                (map, null, -1, null, transformer, action);
5012 <        }
5013 <
5014 <        /**
5015 <         * Returns a task that when invoked, returns a non-null result
5016 <         * from applying the given search function on each value, or
5017 <         * null if none.  Upon success, further element processing is
5018 <         * suppressed and the results of any other parallel
5019 <         * invocations of the search function are ignored.
5020 <         *
5021 <         * @param map the map
5022 <         * @param searchFunction a function returning a non-null
5023 <         * result on success, else null
5024 <         * @return the task
5025 <         */
5026 <        public static <K,V,U> ForkJoinTask<U> searchValues
5027 <            (ConcurrentHashMap<K,V> map,
5028 <             Fun<? super V, ? extends U> searchFunction) {
5029 <            if (searchFunction == null) throw new NullPointerException();
5030 <            return new SearchValuesTask<K,V,U>
5031 <                (map, null, -1, null, searchFunction,
5032 <                 new AtomicReference<U>());
5033 <        }
5034 <
5035 <        /**
5036 <         * Returns a task that when invoked, returns the result of
5037 <         * accumulating all values using the given reducer to combine
5038 <         * values, or null if none.
5039 <         *
5040 <         * @param map the map
5041 <         * @param reducer a commutative associative combining function
5042 <         * @return the task
5043 <         */
5044 <        public static <K,V> ForkJoinTask<V> reduceValues
5045 <            (ConcurrentHashMap<K,V> map,
5046 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5047 <            if (reducer == null) throw new NullPointerException();
5048 <            return new ReduceValuesTask<K,V>
5049 <                (map, null, -1, null, reducer);
5050 <        }
5051 <
5052 <        /**
5053 <         * Returns a task that when invoked, returns the result of
5054 <         * accumulating the given transformation of all values using the
5055 <         * given reducer to combine values, or null if none.
5056 <         *
5057 <         * @param map the map
5058 <         * @param transformer a function returning the transformation
5059 <         * for an element, or null if there is no transformation (in
5060 <         * which case it is not combined).
5061 <         * @param reducer a commutative associative combining function
5062 <         * @return the task
5063 <         */
5064 <        public static <K,V,U> ForkJoinTask<U> reduceValues
5065 <            (ConcurrentHashMap<K,V> map,
5066 <             Fun<? super V, ? extends U> transformer,
5067 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5068 <            if (transformer == null || reducer == null)
5069 <                throw new NullPointerException();
5070 <            return new MapReduceValuesTask<K,V,U>
5071 <                (map, null, -1, null, transformer, reducer);
5072 <        }
5073 <
5074 <        /**
5075 <         * Returns a task that when invoked, returns the result of
5076 <         * accumulating the given transformation of all values using the
5077 <         * given reducer to combine values, and the given basis as an
5078 <         * identity value.
5079 <         *
5080 <         * @param map the map
5081 <         * @param transformer a function returning the transformation
5082 <         * for an element
5083 <         * @param basis the identity (initial default value) for the reduction
5084 <         * @param reducer a commutative associative combining function
5085 <         * @return the task
5086 <         */
5087 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5088 <            (ConcurrentHashMap<K,V> map,
5089 <             ObjectToDouble<? super V> transformer,
5090 <             double basis,
5091 <             DoubleByDoubleToDouble reducer) {
5092 <            if (transformer == null || reducer == null)
5093 <                throw new NullPointerException();
5094 <            return new MapReduceValuesToDoubleTask<K,V>
5095 <                (map, null, -1, null, transformer, basis, reducer);
5096 <        }
5097 <
5098 <        /**
5099 <         * Returns a task that when invoked, returns the result of
5100 <         * accumulating the given transformation of all values using the
5101 <         * given reducer to combine values, and the given basis as an
5102 <         * identity value.
5103 <         *
5104 <         * @param map the map
5105 <         * @param transformer a function returning the transformation
5106 <         * for an element
5107 <         * @param basis the identity (initial default value) for the reduction
5108 <         * @param reducer a commutative associative combining function
5109 <         * @return the task
5110 <         */
5111 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5112 <            (ConcurrentHashMap<K,V> map,
5113 <             ObjectToLong<? super V> transformer,
5114 <             long basis,
5115 <             LongByLongToLong reducer) {
5116 <            if (transformer == null || reducer == null)
5117 <                throw new NullPointerException();
5118 <            return new MapReduceValuesToLongTask<K,V>
5119 <                (map, null, -1, null, transformer, basis, reducer);
5120 <        }
5121 <
5122 <        /**
5123 <         * Returns a task that when invoked, returns the result of
5124 <         * accumulating the given transformation of all values using the
5125 <         * given reducer to combine values, and the given basis as an
5126 <         * identity value.
5127 <         *
5128 <         * @param map the map
5129 <         * @param transformer a function returning the transformation
5130 <         * for an element
5131 <         * @param basis the identity (initial default value) for the reduction
5132 <         * @param reducer a commutative associative combining function
5133 <         * @return the task
5134 <         */
5135 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5136 <            (ConcurrentHashMap<K,V> map,
5137 <             ObjectToInt<? super V> transformer,
5138 <             int basis,
5139 <             IntByIntToInt reducer) {
5140 <            if (transformer == null || reducer == null)
5141 <                throw new NullPointerException();
5142 <            return new MapReduceValuesToIntTask<K,V>
5143 <                (map, null, -1, null, transformer, basis, reducer);
4375 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4376 >            Node<K,V>[] t;
4377 >            ConcurrentHashMap<K,V> m = map;
4378 >            long n = m.sumCount();
4379 >            int f = (t = m.table) == null ? 0 : t.length;
4380 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4381          }
4382  
4383 <        /**
5147 <         * Returns a task that when invoked, perform the given action
5148 <         * for each entry.
5149 <         *
5150 <         * @param map the map
5151 <         * @param action the action
5152 <         */
5153 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5154 <            (ConcurrentHashMap<K,V> map,
5155 <             Action<Map.Entry<K,V>> action) {
4383 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4384              if (action == null) throw new NullPointerException();
4385 <            return new ForEachEntryTask<K,V>(map, null, -1, null, action);
4386 <        }
4387 <
4388 <        /**
4389 <         * Returns a task that when invoked, perform the given action
4390 <         * for each non-null transformation of each entry.
5163 <         *
5164 <         * @param map the map
5165 <         * @param transformer a function returning the transformation
5166 <         * for an element, or null if there is no transformation (in
5167 <         * which case the action is not applied)
5168 <         * @param action the action
5169 <         */
5170 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5171 <            (ConcurrentHashMap<K,V> map,
5172 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5173 <             Action<U> action) {
5174 <            if (transformer == null || action == null)
5175 <                throw new NullPointerException();
5176 <            return new ForEachTransformedEntryTask<K,V,U>
5177 <                (map, null, -1, null, transformer, action);
5178 <        }
5179 <
5180 <        /**
5181 <         * Returns a task that when invoked, returns a non-null result
5182 <         * from applying the given search function on each entry, or
5183 <         * null if none.  Upon success, further element processing is
5184 <         * suppressed and the results of any other parallel
5185 <         * invocations of the search function are ignored.
5186 <         *
5187 <         * @param map the map
5188 <         * @param searchFunction a function returning a non-null
5189 <         * result on success, else null
5190 <         * @return the task
5191 <         */
5192 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5193 <            (ConcurrentHashMap<K,V> map,
5194 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5195 <            if (searchFunction == null) throw new NullPointerException();
5196 <            return new SearchEntriesTask<K,V,U>
5197 <                (map, null, -1, null, searchFunction,
5198 <                 new AtomicReference<U>());
5199 <        }
5200 <
5201 <        /**
5202 <         * Returns a task that when invoked, returns the result of
5203 <         * accumulating all entries using the given reducer to combine
5204 <         * values, or null if none.
5205 <         *
5206 <         * @param map the map
5207 <         * @param reducer a commutative associative combining function
5208 <         * @return the task
5209 <         */
5210 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5211 <            (ConcurrentHashMap<K,V> map,
5212 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5213 <            if (reducer == null) throw new NullPointerException();
5214 <            return new ReduceEntriesTask<K,V>
5215 <                (map, null, -1, null, reducer);
5216 <        }
5217 <
5218 <        /**
5219 <         * Returns a task that when invoked, returns the result of
5220 <         * accumulating the given transformation of all entries using the
5221 <         * given reducer to combine values, or null if none.
5222 <         *
5223 <         * @param map the map
5224 <         * @param transformer a function returning the transformation
5225 <         * for an element, or null if there is no transformation (in
5226 <         * which case it is not combined).
5227 <         * @param reducer a commutative associative combining function
5228 <         * @return the task
5229 <         */
5230 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5231 <            (ConcurrentHashMap<K,V> map,
5232 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5233 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5234 <            if (transformer == null || reducer == null)
5235 <                throw new NullPointerException();
5236 <            return new MapReduceEntriesTask<K,V,U>
5237 <                (map, null, -1, null, transformer, reducer);
5238 <        }
5239 <
5240 <        /**
5241 <         * Returns a task that when invoked, returns the result of
5242 <         * accumulating the given transformation of all entries using the
5243 <         * given reducer to combine values, and the given basis as an
5244 <         * identity value.
5245 <         *
5246 <         * @param map the map
5247 <         * @param transformer a function returning the transformation
5248 <         * for an element
5249 <         * @param basis the identity (initial default value) for the reduction
5250 <         * @param reducer a commutative associative combining function
5251 <         * @return the task
5252 <         */
5253 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5254 <            (ConcurrentHashMap<K,V> map,
5255 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5256 <             double basis,
5257 <             DoubleByDoubleToDouble reducer) {
5258 <            if (transformer == null || reducer == null)
5259 <                throw new NullPointerException();
5260 <            return new MapReduceEntriesToDoubleTask<K,V>
5261 <                (map, null, -1, null, transformer, basis, reducer);
5262 <        }
5263 <
5264 <        /**
5265 <         * Returns a task that when invoked, returns the result of
5266 <         * accumulating the given transformation of all entries using the
5267 <         * given reducer to combine values, and the given basis as an
5268 <         * identity value.
5269 <         *
5270 <         * @param map the map
5271 <         * @param transformer a function returning the transformation
5272 <         * for an element
5273 <         * @param basis the identity (initial default value) for the reduction
5274 <         * @param reducer a commutative associative combining function
5275 <         * @return the task
5276 <         */
5277 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
5278 <            (ConcurrentHashMap<K,V> map,
5279 <             ObjectToLong<Map.Entry<K,V>> transformer,
5280 <             long basis,
5281 <             LongByLongToLong reducer) {
5282 <            if (transformer == null || reducer == null)
5283 <                throw new NullPointerException();
5284 <            return new MapReduceEntriesToLongTask<K,V>
5285 <                (map, null, -1, null, transformer, basis, reducer);
4385 >            Node<K,V>[] t;
4386 >            if ((t = map.table) != null) {
4387 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4388 >                for (Node<K,V> p; (p = it.advance()) != null; )
4389 >                    action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
4390 >            }
4391          }
4392  
5288        /**
5289         * Returns a task that when invoked, returns the result of
5290         * accumulating the given transformation of all entries using the
5291         * given reducer to combine values, and the given basis as an
5292         * identity value.
5293         *
5294         * @param map the map
5295         * @param transformer a function returning the transformation
5296         * for an element
5297         * @param basis the identity (initial default value) for the reduction
5298         * @param reducer a commutative associative combining function
5299         * @return the task
5300         */
5301        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
5302            (ConcurrentHashMap<K,V> map,
5303             ObjectToInt<Map.Entry<K,V>> transformer,
5304             int basis,
5305             IntByIntToInt reducer) {
5306            if (transformer == null || reducer == null)
5307                throw new NullPointerException();
5308            return new MapReduceEntriesToIntTask<K,V>
5309                (map, null, -1, null, transformer, basis, reducer);
5310        }
4393      }
4394  
4395      // -------------------------------------------------------
4396  
4397      /**
4398 <     * Base for FJ tasks for bulk operations. This adds a variant of
4399 <     * CountedCompleters and some split and merge bookkeeping to
5318 <     * iterator functionality. The forEach and reduce methods are
5319 <     * similar to those illustrated in CountedCompleter documentation,
5320 <     * except that bottom-up reduction completions perform them within
5321 <     * their compute methods. The search methods are like forEach
5322 <     * except they continually poll for success and exit early.  Also,
5323 <     * exceptions are handled in a simpler manner, by just trying to
5324 <     * complete root task exceptionally.
5325 <     */
5326 <    @SuppressWarnings("serial") static abstract class BulkTask<K,V,R> extends Traverser<K,V,R> {
5327 <        final BulkTask<K,V,?> parent;  // completion target
5328 <        int batch;                     // split control; -1 for unknown
5329 <        int pending;                   // completion control
5330 <
5331 <        BulkTask(ConcurrentHashMap<K,V> map, BulkTask<K,V,?> parent,
5332 <                 int batch) {
5333 <            super(map);
5334 <            this.parent = parent;
5335 <            this.batch = batch;
5336 <            if (parent != null && map != null) { // split parent
5337 <                Node[] t;
5338 <                if ((t = parent.tab) == null &&
5339 <                    (t = parent.tab = map.table) != null)
5340 <                    parent.baseLimit = parent.baseSize = t.length;
5341 <                this.tab = t;
5342 <                this.baseSize = parent.baseSize;
5343 <                int hi = this.baseLimit = parent.baseLimit;
5344 <                parent.baseLimit = this.index = this.baseIndex =
5345 <                    (hi + parent.baseIndex + 1) >>> 1;
5346 <            }
5347 <        }
5348 <
5349 <        /**
5350 <         * Forces root task to complete.
5351 <         * @param ex if null, complete normally, else exceptionally
5352 <         * @return false to simplify use
5353 <         */
5354 <        final boolean tryCompleteComputation(Throwable ex) {
5355 <            for (BulkTask<K,V,?> a = this;;) {
5356 <                BulkTask<K,V,?> p = a.parent;
5357 <                if (p == null) {
5358 <                    if (ex != null)
5359 <                        a.completeExceptionally(ex);
5360 <                    else
5361 <                        a.quietlyComplete();
5362 <                    return false;
5363 <                }
5364 <                a = p;
5365 <            }
5366 <        }
5367 <
5368 <        /**
5369 <         * Version of tryCompleteComputation for function screening checks
5370 <         */
5371 <        final boolean abortOnNullFunction() {
5372 <            return tryCompleteComputation(new Error("Unexpected null function"));
5373 <        }
5374 <
5375 <        // utilities
5376 <
5377 <        /** CompareAndSet pending count */
5378 <        final boolean casPending(int cmp, int val) {
5379 <            return U.compareAndSwapInt(this, PENDING, cmp, val);
5380 <        }
5381 <
5382 <        /**
5383 <         * Returns approx exp2 of the number of times (minus one) to
5384 <         * split task by two before executing leaf action. This value
5385 <         * is faster to compute and more convenient to use as a guide
5386 <         * to splitting than is the depth, since it is used while
5387 <         * dividing by two anyway.
5388 <         */
5389 <        final int batch() {
5390 <            ConcurrentHashMap<K, V> m; int b; Node[] t;  ForkJoinPool pool;
5391 <            if ((b = batch) < 0 && (m = map) != null) { // force initialization
5392 <                if ((t = tab) == null && (t = tab = m.table) != null)
5393 <                    baseLimit = baseSize = t.length;
5394 <                if (t != null) {
5395 <                    long n = m.counter.sum();
5396 <                    int par = ((pool = getPool()) == null) ?
5397 <                        ForkJoinPool.getCommonPoolParallelism() :
5398 <                        pool.getParallelism();
5399 <                    int sp = par << 3; // slack of 8
5400 <                    b = batch = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
5401 <                }
5402 <            }
5403 <            return b;
5404 <        }
5405 <
5406 <        /**
5407 <         * Returns exportable snapshot entry.
5408 <         */
5409 <        static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
5410 <            return new AbstractMap.SimpleEntry<K,V>(k, v);
5411 <        }
5412 <
5413 <        // Unsafe mechanics
5414 <        private static final sun.misc.Unsafe U;
5415 <        private static final long PENDING;
5416 <        static {
5417 <            try {
5418 <                U = sun.misc.Unsafe.getUnsafe();
5419 <                PENDING = U.objectFieldOffset
5420 <                    (BulkTask.class.getDeclaredField("pending"));
5421 <            } catch (Exception e) {
5422 <                throw new Error(e);
5423 <            }
5424 <        }
5425 <    }
5426 <
5427 <    /**
5428 <     * Base class for non-reductive actions
4398 >     * Base class for bulk tasks. Repeats some fields and code from
4399 >     * class Traverser, because we need to subclass CountedCompleter.
4400       */
4401 <    @SuppressWarnings("serial") static abstract class BulkAction<K,V,R> extends BulkTask<K,V,R> {
4402 <        BulkAction<K,V,?> nextTask;
4403 <        BulkAction(ConcurrentHashMap<K,V> map, BulkTask<K,V,?> parent,
4404 <                   int batch, BulkAction<K,V,?> nextTask) {
4405 <            super(map, parent, batch);
4406 <            this.nextTask = nextTask;
4401 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4402 >        Node<K,V>[] tab;        // same as Traverser
4403 >        Node<K,V> next;
4404 >        int index;
4405 >        int baseIndex;
4406 >        int baseLimit;
4407 >        final int baseSize;
4408 >        int batch;              // split control
4409 >
4410 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4411 >            super(par);
4412 >            this.batch = b;
4413 >            this.index = this.baseIndex = i;
4414 >            if ((this.tab = t) == null)
4415 >                this.baseSize = this.baseLimit = 0;
4416 >            else if (par == null)
4417 >                this.baseSize = this.baseLimit = t.length;
4418 >            else {
4419 >                this.baseLimit = f;
4420 >                this.baseSize = par.baseSize;
4421 >            }
4422          }
4423  
4424          /**
4425 <         * Try to complete task and upward parents. Upon hitting
5440 <         * non-completed parent, if a non-FJ task, try to help out the
5441 <         * computation.
4425 >         * Same as Traverser version
4426           */
4427 <        final void tryComplete(BulkAction<K,V,?> subtasks) {
4428 <            BulkTask<K,V,?> a = this, s = a;
4429 <            for (int c;;) {
4430 <                if ((c = a.pending) == 0) {
4431 <                    if ((a = (s = a).parent) == null) {
4432 <                        s.quietlyComplete();
4433 <                        break;
4434 <                    }
4435 <                }
4436 <                else if (a.casPending(c, c - 1)) {
4437 <                    if (subtasks != null && !inForkJoinPool()) {
4438 <                        while ((s = a.parent) != null)
4439 <                            a = s;
4440 <                        while (!a.isDone()) {
4441 <                            BulkAction<K,V,?> next = subtasks.nextTask;
4442 <                            if (subtasks.tryUnfork())
4443 <                                subtasks.exec();
4444 <                            if ((subtasks = next) == null)
5461 <                                break;
5462 <                        }
4427 >        final Node<K,V> advance() {
4428 >            Node<K,V> e;
4429 >            if ((e = next) != null)
4430 >                e = e.next;
4431 >            for (;;) {
4432 >                Node<K,V>[] t; int i, n; Object ek;
4433 >                if (e != null)
4434 >                    return next = e;
4435 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4436 >                    (n = t.length) <= (i = index) || i < 0)
4437 >                    return next = null;
4438 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4439 >                    if ((ek = e.key) instanceof TreeBin)
4440 >                        e = ((TreeBin<K,V>)ek).first;
4441 >                    else {
4442 >                        tab = (Node<K,V>[])ek;
4443 >                        e = null;
4444 >                        continue;
4445                      }
5464                    break;
4446                  }
4447 +                if ((index += baseSize) >= n)
4448 +                    index = ++baseIndex;
4449              }
4450          }
5468
4451      }
4452  
4453      /*
4454       * Task classes. Coded in a regular but ugly format/style to
4455       * simplify checks that each variant differs in the right way from
4456 <     * others.
4456 >     * others. The null screenings exist because compilers cannot tell
4457 >     * that we've already null-checked task arguments, so we force
4458 >     * simplest hoisted bypass to help avoid convoluted traps.
4459       */
4460  
4461 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4462 <        extends BulkAction<K,V,Void> {
4463 <        final Action<K> action;
4461 >    static final class ForEachKeyTask<K,V>
4462 >        extends BulkTask<K,V,Void> {
4463 >        final Consumer<? super K> action;
4464          ForEachKeyTask
4465 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4466 <             ForEachKeyTask<K,V> nextTask,
4467 <             Action<K> action) {
5484 <            super(m, p, b, nextTask);
4465 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4466 >             Consumer<? super K> action) {
4467 >            super(p, b, i, f, t);
4468              this.action = action;
4469          }
4470 <        @SuppressWarnings("unchecked") public final boolean exec() {
4471 <            final Action<K> action = this.action;
4472 <            if (action == null)
4473 <                return abortOnNullFunction();
4474 <            ForEachKeyTask<K,V> subtasks = null;
4475 <            try {
4476 <                int b = batch(), c;
4477 <                while (b > 1 && baseIndex != baseLimit) {
4478 <                    do {} while (!casPending(c = pending, c+1));
4479 <                    (subtasks = new ForEachKeyTask<K,V>
4480 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4481 <                }
4482 <                while (advance() != null)
5500 <                    action.apply((K)nextKey);
5501 <            } catch (Throwable ex) {
5502 <                return tryCompleteComputation(ex);
4470 >        public final void compute() {
4471 >            final Consumer<? super K> action;
4472 >            if ((action = this.action) != null) {
4473 >                for (int i = baseIndex, f, h; batch > 0 &&
4474 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4475 >                    addToPendingCount(1);
4476 >                    new ForEachKeyTask<K,V>
4477 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4478 >                         action).fork();
4479 >                }
4480 >                for (Node<K,V> p; (p = advance()) != null;)
4481 >                    action.accept((K)p.key);
4482 >                propagateCompletion();
4483              }
5504            tryComplete(subtasks);
5505            return false;
4484          }
4485      }
4486  
4487 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4488 <        extends BulkAction<K,V,Void> {
4489 <        final Action<V> action;
4487 >    static final class ForEachValueTask<K,V>
4488 >        extends BulkTask<K,V,Void> {
4489 >        final Consumer<? super V> action;
4490          ForEachValueTask
4491 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4492 <             ForEachValueTask<K,V> nextTask,
4493 <             Action<V> action) {
5516 <            super(m, p, b, nextTask);
4491 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4492 >             Consumer<? super V> action) {
4493 >            super(p, b, i, f, t);
4494              this.action = action;
4495          }
4496 <        @SuppressWarnings("unchecked") public final boolean exec() {
4497 <            final Action<V> action = this.action;
4498 <            if (action == null)
4499 <                return abortOnNullFunction();
4500 <            ForEachValueTask<K,V> subtasks = null;
4501 <            try {
4502 <                int b = batch(), c;
4503 <                while (b > 1 && baseIndex != baseLimit) {
4504 <                    do {} while (!casPending(c = pending, c+1));
4505 <                    (subtasks = new ForEachValueTask<K,V>
4506 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4507 <                }
4508 <                Object v;
5532 <                while ((v = advance()) != null)
5533 <                    action.apply((V)v);
5534 <            } catch (Throwable ex) {
5535 <                return tryCompleteComputation(ex);
4496 >        public final void compute() {
4497 >            final Consumer<? super V> action;
4498 >            if ((action = this.action) != null) {
4499 >                for (int i = baseIndex, f, h; batch > 0 &&
4500 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4501 >                    addToPendingCount(1);
4502 >                    new ForEachValueTask<K,V>
4503 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4504 >                         action).fork();
4505 >                }
4506 >                for (Node<K,V> p; (p = advance()) != null;)
4507 >                    action.accept(p.val);
4508 >                propagateCompletion();
4509              }
5537            tryComplete(subtasks);
5538            return false;
4510          }
4511      }
4512  
4513 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4514 <        extends BulkAction<K,V,Void> {
4515 <        final Action<Entry<K,V>> action;
4513 >    static final class ForEachEntryTask<K,V>
4514 >        extends BulkTask<K,V,Void> {
4515 >        final Consumer<? super Entry<K,V>> action;
4516          ForEachEntryTask
4517 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4518 <             ForEachEntryTask<K,V> nextTask,
4519 <             Action<Entry<K,V>> action) {
5549 <            super(m, p, b, nextTask);
4517 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4518 >             Consumer<? super Entry<K,V>> action) {
4519 >            super(p, b, i, f, t);
4520              this.action = action;
4521          }
4522 <        @SuppressWarnings("unchecked") public final boolean exec() {
4523 <            final Action<Entry<K,V>> action = this.action;
4524 <            if (action == null)
4525 <                return abortOnNullFunction();
4526 <            ForEachEntryTask<K,V> subtasks = null;
4527 <            try {
4528 <                int b = batch(), c;
4529 <                while (b > 1 && baseIndex != baseLimit) {
4530 <                    do {} while (!casPending(c = pending, c+1));
4531 <                    (subtasks = new ForEachEntryTask<K,V>
4532 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4533 <                }
4534 <                Object v;
5565 <                while ((v = advance()) != null)
5566 <                    action.apply(entryFor((K)nextKey, (V)v));
5567 <            } catch (Throwable ex) {
5568 <                return tryCompleteComputation(ex);
4522 >        public final void compute() {
4523 >            final Consumer<? super Entry<K,V>> action;
4524 >            if ((action = this.action) != null) {
4525 >                for (int i = baseIndex, f, h; batch > 0 &&
4526 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4527 >                    addToPendingCount(1);
4528 >                    new ForEachEntryTask<K,V>
4529 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4530 >                         action).fork();
4531 >                }
4532 >                for (Node<K,V> p; (p = advance()) != null; )
4533 >                    action.accept(p);
4534 >                propagateCompletion();
4535              }
5570            tryComplete(subtasks);
5571            return false;
4536          }
4537      }
4538  
4539 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4540 <        extends BulkAction<K,V,Void> {
4541 <        final BiAction<K,V> action;
4539 >    static final class ForEachMappingTask<K,V>
4540 >        extends BulkTask<K,V,Void> {
4541 >        final BiConsumer<? super K, ? super V> action;
4542          ForEachMappingTask
4543 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4544 <             ForEachMappingTask<K,V> nextTask,
4545 <             BiAction<K,V> action) {
5582 <            super(m, p, b, nextTask);
4543 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4544 >             BiConsumer<? super K,? super V> action) {
4545 >            super(p, b, i, f, t);
4546              this.action = action;
4547          }
4548 <        @SuppressWarnings("unchecked") public final boolean exec() {
4549 <            final BiAction<K,V> action = this.action;
4550 <            if (action == null)
4551 <                return abortOnNullFunction();
4552 <            ForEachMappingTask<K,V> subtasks = null;
4553 <            try {
4554 <                int b = batch(), c;
4555 <                while (b > 1 && baseIndex != baseLimit) {
4556 <                    do {} while (!casPending(c = pending, c+1));
4557 <                    (subtasks = new ForEachMappingTask<K,V>
4558 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4559 <                }
4560 <                Object v;
5598 <                while ((v = advance()) != null)
5599 <                    action.apply((K)nextKey, (V)v);
5600 <            } catch (Throwable ex) {
5601 <                return tryCompleteComputation(ex);
4548 >        public final void compute() {
4549 >            final BiConsumer<? super K, ? super V> action;
4550 >            if ((action = this.action) != null) {
4551 >                for (int i = baseIndex, f, h; batch > 0 &&
4552 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4553 >                    addToPendingCount(1);
4554 >                    new ForEachMappingTask<K,V>
4555 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4556 >                         action).fork();
4557 >                }
4558 >                for (Node<K,V> p; (p = advance()) != null; )
4559 >                    action.accept((K)p.key, p.val);
4560 >                propagateCompletion();
4561              }
5603            tryComplete(subtasks);
5604            return false;
4562          }
4563      }
4564  
4565 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4566 <        extends BulkAction<K,V,Void> {
4567 <        final Fun<? super K, ? extends U> transformer;
4568 <        final Action<U> action;
4565 >    static final class ForEachTransformedKeyTask<K,V,U>
4566 >        extends BulkTask<K,V,Void> {
4567 >        final Function<? super K, ? extends U> transformer;
4568 >        final Consumer<? super U> action;
4569          ForEachTransformedKeyTask
4570 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4571 <             ForEachTransformedKeyTask<K,V,U> nextTask,
4572 <             Fun<? super K, ? extends U> transformer,
4573 <             Action<U> action) {
4574 <            super(m, p, b, nextTask);
4575 <            this.transformer = transformer;
4576 <            this.action = action;
4577 <
4578 <        }
4579 <        @SuppressWarnings("unchecked") public final boolean exec() {
4580 <            final Fun<? super K, ? extends U> transformer =
4581 <                this.transformer;
4582 <            final Action<U> action = this.action;
4583 <            if (transformer == null || action == null)
4584 <                return abortOnNullFunction();
4585 <            ForEachTransformedKeyTask<K,V,U> subtasks = null;
4586 <            try {
4587 <                int b = batch(), c;
4588 <                while (b > 1 && baseIndex != baseLimit) {
4589 <                    do {} while (!casPending(c = pending, c+1));
4590 <                    (subtasks = new ForEachTransformedKeyTask<K,V,U>
4591 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
4592 <                }
5636 <                U u;
5637 <                while (advance() != null) {
5638 <                    if ((u = transformer.apply((K)nextKey)) != null)
5639 <                        action.apply(u);
5640 <                }
5641 <            } catch (Throwable ex) {
5642 <                return tryCompleteComputation(ex);
4570 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4571 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
4572 >            super(p, b, i, f, t);
4573 >            this.transformer = transformer; this.action = action;
4574 >        }
4575 >        public final void compute() {
4576 >            final Function<? super K, ? extends U> transformer;
4577 >            final Consumer<? super U> action;
4578 >            if ((transformer = this.transformer) != null &&
4579 >                (action = this.action) != null) {
4580 >                for (int i = baseIndex, f, h; batch > 0 &&
4581 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4582 >                    addToPendingCount(1);
4583 >                    new ForEachTransformedKeyTask<K,V,U>
4584 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4585 >                         transformer, action).fork();
4586 >                }
4587 >                for (Node<K,V> p; (p = advance()) != null; ) {
4588 >                    U u;
4589 >                    if ((u = transformer.apply((K)p.key)) != null)
4590 >                        action.accept(u);
4591 >                }
4592 >                propagateCompletion();
4593              }
5644            tryComplete(subtasks);
5645            return false;
4594          }
4595      }
4596  
4597 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
4598 <        extends BulkAction<K,V,Void> {
4599 <        final Fun<? super V, ? extends U> transformer;
4600 <        final Action<U> action;
4597 >    static final class ForEachTransformedValueTask<K,V,U>
4598 >        extends BulkTask<K,V,Void> {
4599 >        final Function<? super V, ? extends U> transformer;
4600 >        final Consumer<? super U> action;
4601          ForEachTransformedValueTask
4602 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4603 <             ForEachTransformedValueTask<K,V,U> nextTask,
4604 <             Fun<? super V, ? extends U> transformer,
4605 <             Action<U> action) {
4606 <            super(m, p, b, nextTask);
4607 <            this.transformer = transformer;
4608 <            this.action = action;
4609 <
4610 <        }
4611 <        @SuppressWarnings("unchecked") public final boolean exec() {
4612 <            final Fun<? super V, ? extends U> transformer =
4613 <                this.transformer;
4614 <            final Action<U> action = this.action;
4615 <            if (transformer == null || action == null)
4616 <                return abortOnNullFunction();
4617 <            ForEachTransformedValueTask<K,V,U> subtasks = null;
4618 <            try {
4619 <                int b = batch(), c;
4620 <                while (b > 1 && baseIndex != baseLimit) {
4621 <                    do {} while (!casPending(c = pending, c+1));
4622 <                    (subtasks = new ForEachTransformedValueTask<K,V,U>
4623 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
4624 <                }
5677 <                Object v; U u;
5678 <                while ((v = advance()) != null) {
5679 <                    if ((u = transformer.apply((V)v)) != null)
5680 <                        action.apply(u);
5681 <                }
5682 <            } catch (Throwable ex) {
5683 <                return tryCompleteComputation(ex);
4602 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4603 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
4604 >            super(p, b, i, f, t);
4605 >            this.transformer = transformer; this.action = action;
4606 >        }
4607 >        public final void compute() {
4608 >            final Function<? super V, ? extends U> transformer;
4609 >            final Consumer<? super U> action;
4610 >            if ((transformer = this.transformer) != null &&
4611 >                (action = this.action) != null) {
4612 >                for (int i = baseIndex, f, h; batch > 0 &&
4613 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4614 >                    addToPendingCount(1);
4615 >                    new ForEachTransformedValueTask<K,V,U>
4616 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4617 >                         transformer, action).fork();
4618 >                }
4619 >                for (Node<K,V> p; (p = advance()) != null; ) {
4620 >                    U u;
4621 >                    if ((u = transformer.apply(p.val)) != null)
4622 >                        action.accept(u);
4623 >                }
4624 >                propagateCompletion();
4625              }
5685            tryComplete(subtasks);
5686            return false;
4626          }
4627      }
4628  
4629 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
4630 <        extends BulkAction<K,V,Void> {
4631 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
4632 <        final Action<U> action;
4629 >    static final class ForEachTransformedEntryTask<K,V,U>
4630 >        extends BulkTask<K,V,Void> {
4631 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
4632 >        final Consumer<? super U> action;
4633          ForEachTransformedEntryTask
4634 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4635 <             ForEachTransformedEntryTask<K,V,U> nextTask,
4636 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4637 <             Action<U> action) {
4638 <            super(m, p, b, nextTask);
4639 <            this.transformer = transformer;
4640 <            this.action = action;
4641 <
4642 <        }
4643 <        @SuppressWarnings("unchecked") public final boolean exec() {
4644 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
4645 <                this.transformer;
4646 <            final Action<U> action = this.action;
4647 <            if (transformer == null || action == null)
4648 <                return abortOnNullFunction();
4649 <            ForEachTransformedEntryTask<K,V,U> subtasks = null;
4650 <            try {
4651 <                int b = batch(), c;
4652 <                while (b > 1 && baseIndex != baseLimit) {
4653 <                    do {} while (!casPending(c = pending, c+1));
4654 <                    (subtasks = new ForEachTransformedEntryTask<K,V,U>
4655 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
4656 <                }
5718 <                Object v; U u;
5719 <                while ((v = advance()) != null) {
5720 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5721 <                        action.apply(u);
5722 <                }
5723 <            } catch (Throwable ex) {
5724 <                return tryCompleteComputation(ex);
4634 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4635 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
4636 >            super(p, b, i, f, t);
4637 >            this.transformer = transformer; this.action = action;
4638 >        }
4639 >        public final void compute() {
4640 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
4641 >            final Consumer<? super U> action;
4642 >            if ((transformer = this.transformer) != null &&
4643 >                (action = this.action) != null) {
4644 >                for (int i = baseIndex, f, h; batch > 0 &&
4645 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4646 >                    addToPendingCount(1);
4647 >                    new ForEachTransformedEntryTask<K,V,U>
4648 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4649 >                         transformer, action).fork();
4650 >                }
4651 >                for (Node<K,V> p; (p = advance()) != null; ) {
4652 >                    U u;
4653 >                    if ((u = transformer.apply(p)) != null)
4654 >                        action.accept(u);
4655 >                }
4656 >                propagateCompletion();
4657              }
5726            tryComplete(subtasks);
5727            return false;
4658          }
4659      }
4660  
4661 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
4662 <        extends BulkAction<K,V,Void> {
4663 <        final BiFun<? super K, ? super V, ? extends U> transformer;
4664 <        final Action<U> action;
4661 >    static final class ForEachTransformedMappingTask<K,V,U>
4662 >        extends BulkTask<K,V,Void> {
4663 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
4664 >        final Consumer<? super U> action;
4665          ForEachTransformedMappingTask
4666 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4667 <             ForEachTransformedMappingTask<K,V,U> nextTask,
4668 <             BiFun<? super K, ? super V, ? extends U> transformer,
4669 <             Action<U> action) {
4670 <            super(m, p, b, nextTask);
4671 <            this.transformer = transformer;
4672 <            this.action = action;
4673 <
4674 <        }
4675 <        @SuppressWarnings("unchecked") public final boolean exec() {
4676 <            final BiFun<? super K, ? super V, ? extends U> transformer =
4677 <                this.transformer;
4678 <            final Action<U> action = this.action;
4679 <            if (transformer == null || action == null)
4680 <                return abortOnNullFunction();
4681 <            ForEachTransformedMappingTask<K,V,U> subtasks = null;
4682 <            try {
4683 <                int b = batch(), c;
4684 <                while (b > 1 && baseIndex != baseLimit) {
4685 <                    do {} while (!casPending(c = pending, c+1));
4686 <                    (subtasks = new ForEachTransformedMappingTask<K,V,U>
4687 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5758 <                }
5759 <                Object v; U u;
5760 <                while ((v = advance()) != null) {
5761 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5762 <                        action.apply(u);
4666 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4667 >             BiFunction<? super K, ? super V, ? extends U> transformer,
4668 >             Consumer<? super U> action) {
4669 >            super(p, b, i, f, t);
4670 >            this.transformer = transformer; this.action = action;
4671 >        }
4672 >        public final void compute() {
4673 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
4674 >            final Consumer<? super U> action;
4675 >            if ((transformer = this.transformer) != null &&
4676 >                (action = this.action) != null) {
4677 >                for (int i = baseIndex, f, h; batch > 0 &&
4678 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4679 >                    addToPendingCount(1);
4680 >                    new ForEachTransformedMappingTask<K,V,U>
4681 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4682 >                         transformer, action).fork();
4683 >                }
4684 >                for (Node<K,V> p; (p = advance()) != null; ) {
4685 >                    U u;
4686 >                    if ((u = transformer.apply((K)p.key, p.val)) != null)
4687 >                        action.accept(u);
4688                  }
4689 <            } catch (Throwable ex) {
5765 <                return tryCompleteComputation(ex);
4689 >                propagateCompletion();
4690              }
5767            tryComplete(subtasks);
5768            return false;
4691          }
4692      }
4693  
4694 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
4695 <        extends BulkAction<K,V,U> {
4696 <        final Fun<? super K, ? extends U> searchFunction;
4694 >    static final class SearchKeysTask<K,V,U>
4695 >        extends BulkTask<K,V,U> {
4696 >        final Function<? super K, ? extends U> searchFunction;
4697          final AtomicReference<U> result;
4698          SearchKeysTask
4699 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4700 <             SearchKeysTask<K,V,U> nextTask,
5779 <             Fun<? super K, ? extends U> searchFunction,
4699 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4700 >             Function<? super K, ? extends U> searchFunction,
4701               AtomicReference<U> result) {
4702 <            super(m, p, b, nextTask);
4702 >            super(p, b, i, f, t);
4703              this.searchFunction = searchFunction; this.result = result;
4704          }
4705 <        @SuppressWarnings("unchecked") public final boolean exec() {
4706 <            AtomicReference<U> result = this.result;
4707 <            final Fun<? super K, ? extends U> searchFunction =
4708 <                this.searchFunction;
4709 <            if (searchFunction == null || result == null)
4710 <                return abortOnNullFunction();
4711 <            SearchKeysTask<K,V,U> subtasks = null;
4712 <            try {
4713 <                int b = batch(), c;
4714 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4715 <                    do {} while (!casPending(c = pending, c+1));
4716 <                    (subtasks = new SearchKeysTask<K,V,U>
4717 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
4718 <                }
4719 <                U u;
4720 <                while (result.get() == null && advance() != null) {
4721 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
4705 >        public final U getRawResult() { return result.get(); }
4706 >        public final void compute() {
4707 >            final Function<? super K, ? extends U> searchFunction;
4708 >            final AtomicReference<U> result;
4709 >            if ((searchFunction = this.searchFunction) != null &&
4710 >                (result = this.result) != null) {
4711 >                for (int i = baseIndex, f, h; batch > 0 &&
4712 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4713 >                    if (result.get() != null)
4714 >                        return;
4715 >                    addToPendingCount(1);
4716 >                    new SearchKeysTask<K,V,U>
4717 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4718 >                         searchFunction, result).fork();
4719 >                }
4720 >                while (result.get() == null) {
4721 >                    U u;
4722 >                    Node<K,V> p;
4723 >                    if ((p = advance()) == null) {
4724 >                        propagateCompletion();
4725 >                        break;
4726 >                    }
4727 >                    if ((u = searchFunction.apply((K)p.key)) != null) {
4728                          if (result.compareAndSet(null, u))
4729 <                            tryCompleteComputation(null);
4729 >                            quietlyCompleteRoot();
4730                          break;
4731                      }
4732                  }
5806            } catch (Throwable ex) {
5807                return tryCompleteComputation(ex);
4733              }
5809            tryComplete(subtasks);
5810            return false;
4734          }
5812        public final U getRawResult() { return result.get(); }
4735      }
4736  
4737 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
4738 <        extends BulkAction<K,V,U> {
4739 <        final Fun<? super V, ? extends U> searchFunction;
4737 >    static final class SearchValuesTask<K,V,U>
4738 >        extends BulkTask<K,V,U> {
4739 >        final Function<? super V, ? extends U> searchFunction;
4740          final AtomicReference<U> result;
4741          SearchValuesTask
4742 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4743 <             SearchValuesTask<K,V,U> nextTask,
5822 <             Fun<? super V, ? extends U> searchFunction,
4742 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4743 >             Function<? super V, ? extends U> searchFunction,
4744               AtomicReference<U> result) {
4745 <            super(m, p, b, nextTask);
4745 >            super(p, b, i, f, t);
4746              this.searchFunction = searchFunction; this.result = result;
4747          }
4748 <        @SuppressWarnings("unchecked") public final boolean exec() {
4749 <            AtomicReference<U> result = this.result;
4750 <            final Fun<? super V, ? extends U> searchFunction =
4751 <                this.searchFunction;
4752 <            if (searchFunction == null || result == null)
4753 <                return abortOnNullFunction();
4754 <            SearchValuesTask<K,V,U> subtasks = null;
4755 <            try {
4756 <                int b = batch(), c;
4757 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4758 <                    do {} while (!casPending(c = pending, c+1));
4759 <                    (subtasks = new SearchValuesTask<K,V,U>
4760 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
4761 <                }
4762 <                Object v; U u;
4763 <                while (result.get() == null && (v = advance()) != null) {
4764 <                    if ((u = searchFunction.apply((V)v)) != null) {
4748 >        public final U getRawResult() { return result.get(); }
4749 >        public final void compute() {
4750 >            final Function<? super V, ? extends U> searchFunction;
4751 >            final AtomicReference<U> result;
4752 >            if ((searchFunction = this.searchFunction) != null &&
4753 >                (result = this.result) != null) {
4754 >                for (int i = baseIndex, f, h; batch > 0 &&
4755 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4756 >                    if (result.get() != null)
4757 >                        return;
4758 >                    addToPendingCount(1);
4759 >                    new SearchValuesTask<K,V,U>
4760 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4761 >                         searchFunction, result).fork();
4762 >                }
4763 >                while (result.get() == null) {
4764 >                    U u;
4765 >                    Node<K,V> p;
4766 >                    if ((p = advance()) == null) {
4767 >                        propagateCompletion();
4768 >                        break;
4769 >                    }
4770 >                    if ((u = searchFunction.apply(p.val)) != null) {
4771                          if (result.compareAndSet(null, u))
4772 <                            tryCompleteComputation(null);
4772 >                            quietlyCompleteRoot();
4773                          break;
4774                      }
4775                  }
5849            } catch (Throwable ex) {
5850                return tryCompleteComputation(ex);
4776              }
5852            tryComplete(subtasks);
5853            return false;
4777          }
5855        public final U getRawResult() { return result.get(); }
4778      }
4779  
4780 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
4781 <        extends BulkAction<K,V,U> {
4782 <        final Fun<Entry<K,V>, ? extends U> searchFunction;
4780 >    static final class SearchEntriesTask<K,V,U>
4781 >        extends BulkTask<K,V,U> {
4782 >        final Function<Entry<K,V>, ? extends U> searchFunction;
4783          final AtomicReference<U> result;
4784          SearchEntriesTask
4785 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4786 <             SearchEntriesTask<K,V,U> nextTask,
5865 <             Fun<Entry<K,V>, ? extends U> searchFunction,
4785 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4786 >             Function<Entry<K,V>, ? extends U> searchFunction,
4787               AtomicReference<U> result) {
4788 <            super(m, p, b, nextTask);
4788 >            super(p, b, i, f, t);
4789              this.searchFunction = searchFunction; this.result = result;
4790          }
4791 <        @SuppressWarnings("unchecked") public final boolean exec() {
4792 <            AtomicReference<U> result = this.result;
4793 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
4794 <                this.searchFunction;
4795 <            if (searchFunction == null || result == null)
4796 <                return abortOnNullFunction();
4797 <            SearchEntriesTask<K,V,U> subtasks = null;
4798 <            try {
4799 <                int b = batch(), c;
4800 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4801 <                    do {} while (!casPending(c = pending, c+1));
4802 <                    (subtasks = new SearchEntriesTask<K,V,U>
4803 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
4804 <                }
4805 <                Object v; U u;
4806 <                while (result.get() == null && (v = advance()) != null) {
4807 <                    if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
4808 <                        if (result.compareAndSet(null, u))
4809 <                            tryCompleteComputation(null);
4791 >        public final U getRawResult() { return result.get(); }
4792 >        public final void compute() {
4793 >            final Function<Entry<K,V>, ? extends U> searchFunction;
4794 >            final AtomicReference<U> result;
4795 >            if ((searchFunction = this.searchFunction) != null &&
4796 >                (result = this.result) != null) {
4797 >                for (int i = baseIndex, f, h; batch > 0 &&
4798 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4799 >                    if (result.get() != null)
4800 >                        return;
4801 >                    addToPendingCount(1);
4802 >                    new SearchEntriesTask<K,V,U>
4803 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4804 >                         searchFunction, result).fork();
4805 >                }
4806 >                while (result.get() == null) {
4807 >                    U u;
4808 >                    Node<K,V> p;
4809 >                    if ((p = advance()) == null) {
4810 >                        propagateCompletion();
4811                          break;
4812                      }
4813 +                    if ((u = searchFunction.apply(p)) != null) {
4814 +                        if (result.compareAndSet(null, u))
4815 +                            quietlyCompleteRoot();
4816 +                        return;
4817 +                    }
4818                  }
5892            } catch (Throwable ex) {
5893                return tryCompleteComputation(ex);
4819              }
5895            tryComplete(subtasks);
5896            return false;
4820          }
5898        public final U getRawResult() { return result.get(); }
4821      }
4822  
4823 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
4824 <        extends BulkAction<K,V,U> {
4825 <        final BiFun<? super K, ? super V, ? extends U> searchFunction;
4823 >    static final class SearchMappingsTask<K,V,U>
4824 >        extends BulkTask<K,V,U> {
4825 >        final BiFunction<? super K, ? super V, ? extends U> searchFunction;
4826          final AtomicReference<U> result;
4827          SearchMappingsTask
4828 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4829 <             SearchMappingsTask<K,V,U> nextTask,
5908 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
4828 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4829 >             BiFunction<? super K, ? super V, ? extends U> searchFunction,
4830               AtomicReference<U> result) {
4831 <            super(m, p, b, nextTask);
4831 >            super(p, b, i, f, t);
4832              this.searchFunction = searchFunction; this.result = result;
4833          }
4834 <        @SuppressWarnings("unchecked") public final boolean exec() {
4835 <            AtomicReference<U> result = this.result;
4836 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
4837 <                this.searchFunction;
4838 <            if (searchFunction == null || result == null)
4839 <                return abortOnNullFunction();
4840 <            SearchMappingsTask<K,V,U> subtasks = null;
4841 <            try {
4842 <                int b = batch(), c;
4843 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4844 <                    do {} while (!casPending(c = pending, c+1));
4845 <                    (subtasks = new SearchMappingsTask<K,V,U>
4846 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
4847 <                }
4848 <                Object v; U u;
4849 <                while (result.get() == null && (v = advance()) != null) {
4850 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
4834 >        public final U getRawResult() { return result.get(); }
4835 >        public final void compute() {
4836 >            final BiFunction<? super K, ? super V, ? extends U> searchFunction;
4837 >            final AtomicReference<U> result;
4838 >            if ((searchFunction = this.searchFunction) != null &&
4839 >                (result = this.result) != null) {
4840 >                for (int i = baseIndex, f, h; batch > 0 &&
4841 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4842 >                    if (result.get() != null)
4843 >                        return;
4844 >                    addToPendingCount(1);
4845 >                    new SearchMappingsTask<K,V,U>
4846 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4847 >                         searchFunction, result).fork();
4848 >                }
4849 >                while (result.get() == null) {
4850 >                    U u;
4851 >                    Node<K,V> p;
4852 >                    if ((p = advance()) == null) {
4853 >                        propagateCompletion();
4854 >                        break;
4855 >                    }
4856 >                    if ((u = searchFunction.apply((K)p.key, p.val)) != null) {
4857                          if (result.compareAndSet(null, u))
4858 <                            tryCompleteComputation(null);
4858 >                            quietlyCompleteRoot();
4859                          break;
4860                      }
4861                  }
5935            } catch (Throwable ex) {
5936                return tryCompleteComputation(ex);
4862              }
5938            tryComplete(subtasks);
5939            return false;
4863          }
5941        public final U getRawResult() { return result.get(); }
4864      }
4865  
4866 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
4866 >    static final class ReduceKeysTask<K,V>
4867          extends BulkTask<K,V,K> {
4868 <        final BiFun<? super K, ? super K, ? extends K> reducer;
4868 >        final BiFunction<? super K, ? super K, ? extends K> reducer;
4869          K result;
4870          ReduceKeysTask<K,V> rights, nextRight;
4871          ReduceKeysTask
4872 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4872 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4873               ReduceKeysTask<K,V> nextRight,
4874 <             BiFun<? super K, ? super K, ? extends K> reducer) {
4875 <            super(m, p, b); this.nextRight = nextRight;
4874 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
4875 >            super(p, b, i, f, t); this.nextRight = nextRight;
4876              this.reducer = reducer;
4877          }
4878 <        @SuppressWarnings("unchecked") public final boolean exec() {
4879 <            final BiFun<? super K, ? super K, ? extends K> reducer =
4880 <                this.reducer;
4881 <            if (reducer == null)
4882 <                return abortOnNullFunction();
4883 <            try {
4884 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5963 <                    do {} while (!casPending(c = pending, c+1));
4878 >        public final K getRawResult() { return result; }
4879 >        public final void compute() {
4880 >            final BiFunction<? super K, ? super K, ? extends K> reducer;
4881 >            if ((reducer = this.reducer) != null) {
4882 >                for (int i = baseIndex, f, h; batch > 0 &&
4883 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4884 >                    addToPendingCount(1);
4885                      (rights = new ReduceKeysTask<K,V>
4886 <                     (map, this, b >>>= 1, rights, reducer)).fork();
4886 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
4887 >                      rights, reducer)).fork();
4888                  }
4889                  K r = null;
4890 <                while (advance() != null) {
4891 <                    K u = (K)nextKey;
4892 <                    r = (r == null) ? u : reducer.apply(r, u);
4890 >                for (Node<K,V> p; (p = advance()) != null; ) {
4891 >                    K u = (K)p.key;
4892 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
4893                  }
4894                  result = r;
4895 <                for (ReduceKeysTask<K,V> t = this, s;;) {
4896 <                    int c; BulkTask<K,V,?> par; K tr, sr;
4897 <                    if ((c = t.pending) == 0) {
4898 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
4899 <                            if ((sr = s.result) != null)
4900 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
4901 <                        }
4902 <                        if ((par = t.parent) == null ||
4903 <                            !(par instanceof ReduceKeysTask)) {
4904 <                            t.quietlyComplete();
4905 <                            break;
5984 <                        }
5985 <                        t = (ReduceKeysTask<K,V>)par;
4895 >                CountedCompleter<?> c;
4896 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
4897 >                    ReduceKeysTask<K,V>
4898 >                        t = (ReduceKeysTask<K,V>)c,
4899 >                        s = t.rights;
4900 >                    while (s != null) {
4901 >                        K tr, sr;
4902 >                        if ((sr = s.result) != null)
4903 >                            t.result = (((tr = t.result) == null) ? sr :
4904 >                                        reducer.apply(tr, sr));
4905 >                        s = t.rights = s.nextRight;
4906                      }
5987                    else if (t.casPending(c, c - 1))
5988                        break;
4907                  }
5990            } catch (Throwable ex) {
5991                return tryCompleteComputation(ex);
4908              }
5993            ReduceKeysTask<K,V> s = rights;
5994            if (s != null && !inForkJoinPool()) {
5995                do  {
5996                    if (s.tryUnfork())
5997                        s.exec();
5998                } while ((s = s.nextRight) != null);
5999            }
6000            return false;
4909          }
6002        public final K getRawResult() { return result; }
4910      }
4911  
4912 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
4912 >    static final class ReduceValuesTask<K,V>
4913          extends BulkTask<K,V,V> {
4914 <        final BiFun<? super V, ? super V, ? extends V> reducer;
4914 >        final BiFunction<? super V, ? super V, ? extends V> reducer;
4915          V result;
4916          ReduceValuesTask<K,V> rights, nextRight;
4917          ReduceValuesTask
4918 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4918 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4919               ReduceValuesTask<K,V> nextRight,
4920 <             BiFun<? super V, ? super V, ? extends V> reducer) {
4921 <            super(m, p, b); this.nextRight = nextRight;
4920 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
4921 >            super(p, b, i, f, t); this.nextRight = nextRight;
4922              this.reducer = reducer;
4923          }
4924 <        @SuppressWarnings("unchecked") public final boolean exec() {
4925 <            final BiFun<? super V, ? super V, ? extends V> reducer =
4926 <                this.reducer;
4927 <            if (reducer == null)
4928 <                return abortOnNullFunction();
4929 <            try {
4930 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6024 <                    do {} while (!casPending(c = pending, c+1));
4924 >        public final V getRawResult() { return result; }
4925 >        public final void compute() {
4926 >            final BiFunction<? super V, ? super V, ? extends V> reducer;
4927 >            if ((reducer = this.reducer) != null) {
4928 >                for (int i = baseIndex, f, h; batch > 0 &&
4929 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4930 >                    addToPendingCount(1);
4931                      (rights = new ReduceValuesTask<K,V>
4932 <                     (map, this, b >>>= 1, rights, reducer)).fork();
4932 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
4933 >                      rights, reducer)).fork();
4934                  }
4935                  V r = null;
4936 <                Object v;
4937 <                while ((v = advance()) != null) {
4938 <                    V u = (V)v;
6032 <                    r = (r == null) ? u : reducer.apply(r, u);
4936 >                for (Node<K,V> p; (p = advance()) != null; ) {
4937 >                    V v = p.val;
4938 >                    r = (r == null) ? v : reducer.apply(r, v);
4939                  }
4940                  result = r;
4941 <                for (ReduceValuesTask<K,V> t = this, s;;) {
4942 <                    int c; BulkTask<K,V,?> par; V tr, sr;
4943 <                    if ((c = t.pending) == 0) {
4944 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
4945 <                            if ((sr = s.result) != null)
4946 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
4947 <                        }
4948 <                        if ((par = t.parent) == null ||
4949 <                            !(par instanceof ReduceValuesTask)) {
4950 <                            t.quietlyComplete();
4951 <                            break;
6046 <                        }
6047 <                        t = (ReduceValuesTask<K,V>)par;
4941 >                CountedCompleter<?> c;
4942 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
4943 >                    ReduceValuesTask<K,V>
4944 >                        t = (ReduceValuesTask<K,V>)c,
4945 >                        s = t.rights;
4946 >                    while (s != null) {
4947 >                        V tr, sr;
4948 >                        if ((sr = s.result) != null)
4949 >                            t.result = (((tr = t.result) == null) ? sr :
4950 >                                        reducer.apply(tr, sr));
4951 >                        s = t.rights = s.nextRight;
4952                      }
6049                    else if (t.casPending(c, c - 1))
6050                        break;
4953                  }
6052            } catch (Throwable ex) {
6053                return tryCompleteComputation(ex);
6054            }
6055            ReduceValuesTask<K,V> s = rights;
6056            if (s != null && !inForkJoinPool()) {
6057                do  {
6058                    if (s.tryUnfork())
6059                        s.exec();
6060                } while ((s = s.nextRight) != null);
4954              }
6062            return false;
4955          }
6064        public final V getRawResult() { return result; }
4956      }
4957  
4958 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
4958 >    static final class ReduceEntriesTask<K,V>
4959          extends BulkTask<K,V,Map.Entry<K,V>> {
4960 <        final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
4960 >        final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
4961          Map.Entry<K,V> result;
4962          ReduceEntriesTask<K,V> rights, nextRight;
4963          ReduceEntriesTask
4964 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4964 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4965               ReduceEntriesTask<K,V> nextRight,
4966 <             BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4967 <            super(m, p, b); this.nextRight = nextRight;
4966 >             BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4967 >            super(p, b, i, f, t); this.nextRight = nextRight;
4968              this.reducer = reducer;
4969          }
4970 <        @SuppressWarnings("unchecked") public final boolean exec() {
4971 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
4972 <                this.reducer;
4973 <            if (reducer == null)
4974 <                return abortOnNullFunction();
4975 <            try {
4976 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6086 <                    do {} while (!casPending(c = pending, c+1));
4970 >        public final Map.Entry<K,V> getRawResult() { return result; }
4971 >        public final void compute() {
4972 >            final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
4973 >            if ((reducer = this.reducer) != null) {
4974 >                for (int i = baseIndex, f, h; batch > 0 &&
4975 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4976 >                    addToPendingCount(1);
4977                      (rights = new ReduceEntriesTask<K,V>
4978 <                     (map, this, b >>>= 1, rights, reducer)).fork();
4978 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
4979 >                      rights, reducer)).fork();
4980                  }
4981                  Map.Entry<K,V> r = null;
4982 <                Object v;
4983 <                while ((v = advance()) != null) {
6093 <                    Map.Entry<K,V> u = entryFor((K)nextKey, (V)v);
6094 <                    r = (r == null) ? u : reducer.apply(r, u);
6095 <                }
4982 >                for (Node<K,V> p; (p = advance()) != null; )
4983 >                    r = (r == null) ? p : reducer.apply(r, p);
4984                  result = r;
4985 <                for (ReduceEntriesTask<K,V> t = this, s;;) {
4986 <                    int c; BulkTask<K,V,?> par; Map.Entry<K,V> tr, sr;
4987 <                    if ((c = t.pending) == 0) {
4988 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
4989 <                            if ((sr = s.result) != null)
4990 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
4991 <                        }
4992 <                        if ((par = t.parent) == null ||
4993 <                            !(par instanceof ReduceEntriesTask)) {
4994 <                            t.quietlyComplete();
4995 <                            break;
6108 <                        }
6109 <                        t = (ReduceEntriesTask<K,V>)par;
4985 >                CountedCompleter<?> c;
4986 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
4987 >                    ReduceEntriesTask<K,V>
4988 >                        t = (ReduceEntriesTask<K,V>)c,
4989 >                        s = t.rights;
4990 >                    while (s != null) {
4991 >                        Map.Entry<K,V> tr, sr;
4992 >                        if ((sr = s.result) != null)
4993 >                            t.result = (((tr = t.result) == null) ? sr :
4994 >                                        reducer.apply(tr, sr));
4995 >                        s = t.rights = s.nextRight;
4996                      }
6111                    else if (t.casPending(c, c - 1))
6112                        break;
4997                  }
6114            } catch (Throwable ex) {
6115                return tryCompleteComputation(ex);
4998              }
6117            ReduceEntriesTask<K,V> s = rights;
6118            if (s != null && !inForkJoinPool()) {
6119                do  {
6120                    if (s.tryUnfork())
6121                        s.exec();
6122                } while ((s = s.nextRight) != null);
6123            }
6124            return false;
4999          }
6126        public final Map.Entry<K,V> getRawResult() { return result; }
5000      }
5001  
5002 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5002 >    static final class MapReduceKeysTask<K,V,U>
5003          extends BulkTask<K,V,U> {
5004 <        final Fun<? super K, ? extends U> transformer;
5005 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5004 >        final Function<? super K, ? extends U> transformer;
5005 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5006          U result;
5007          MapReduceKeysTask<K,V,U> rights, nextRight;
5008          MapReduceKeysTask
5009 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5009 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5010               MapReduceKeysTask<K,V,U> nextRight,
5011 <             Fun<? super K, ? extends U> transformer,
5012 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5013 <            super(m, p, b); this.nextRight = nextRight;
5011 >             Function<? super K, ? extends U> transformer,
5012 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5013 >            super(p, b, i, f, t); this.nextRight = nextRight;
5014              this.transformer = transformer;
5015              this.reducer = reducer;
5016          }
5017 <        @SuppressWarnings("unchecked") public final boolean exec() {
5018 <            final Fun<? super K, ? extends U> transformer =
5019 <                this.transformer;
5020 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5021 <                this.reducer;
5022 <            if (transformer == null || reducer == null)
5023 <                return abortOnNullFunction();
5024 <            try {
5025 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6153 <                    do {} while (!casPending(c = pending, c+1));
5017 >        public final U getRawResult() { return result; }
5018 >        public final void compute() {
5019 >            final Function<? super K, ? extends U> transformer;
5020 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5021 >            if ((transformer = this.transformer) != null &&
5022 >                (reducer = this.reducer) != null) {
5023 >                for (int i = baseIndex, f, h; batch > 0 &&
5024 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5025 >                    addToPendingCount(1);
5026                      (rights = new MapReduceKeysTask<K,V,U>
5027 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5027 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5028 >                      rights, transformer, reducer)).fork();
5029                  }
5030 <                U r = null, u;
5031 <                while (advance() != null) {
5032 <                    if ((u = transformer.apply((K)nextKey)) != null)
5030 >                U r = null;
5031 >                for (Node<K,V> p; (p = advance()) != null; ) {
5032 >                    U u;
5033 >                    if ((u = transformer.apply((K)p.key)) != null)
5034                          r = (r == null) ? u : reducer.apply(r, u);
5035                  }
5036                  result = r;
5037 <                for (MapReduceKeysTask<K,V,U> t = this, s;;) {
5038 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5039 <                    if ((c = t.pending) == 0) {
5040 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5041 <                            if ((sr = s.result) != null)
5042 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5043 <                        }
5044 <                        if ((par = t.parent) == null ||
5045 <                            !(par instanceof MapReduceKeysTask)) {
5046 <                            t.quietlyComplete();
5047 <                            break;
6174 <                        }
6175 <                        t = (MapReduceKeysTask<K,V,U>)par;
5037 >                CountedCompleter<?> c;
5038 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5039 >                    MapReduceKeysTask<K,V,U>
5040 >                        t = (MapReduceKeysTask<K,V,U>)c,
5041 >                        s = t.rights;
5042 >                    while (s != null) {
5043 >                        U tr, sr;
5044 >                        if ((sr = s.result) != null)
5045 >                            t.result = (((tr = t.result) == null) ? sr :
5046 >                                        reducer.apply(tr, sr));
5047 >                        s = t.rights = s.nextRight;
5048                      }
6177                    else if (t.casPending(c, c - 1))
6178                        break;
5049                  }
6180            } catch (Throwable ex) {
6181                return tryCompleteComputation(ex);
6182            }
6183            MapReduceKeysTask<K,V,U> s = rights;
6184            if (s != null && !inForkJoinPool()) {
6185                do  {
6186                    if (s.tryUnfork())
6187                        s.exec();
6188                } while ((s = s.nextRight) != null);
5050              }
6190            return false;
5051          }
6192        public final U getRawResult() { return result; }
5052      }
5053  
5054 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5054 >    static final class MapReduceValuesTask<K,V,U>
5055          extends BulkTask<K,V,U> {
5056 <        final Fun<? super V, ? extends U> transformer;
5057 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5056 >        final Function<? super V, ? extends U> transformer;
5057 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5058          U result;
5059          MapReduceValuesTask<K,V,U> rights, nextRight;
5060          MapReduceValuesTask
5061 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5061 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5062               MapReduceValuesTask<K,V,U> nextRight,
5063 <             Fun<? super V, ? extends U> transformer,
5064 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5065 <            super(m, p, b); this.nextRight = nextRight;
5063 >             Function<? super V, ? extends U> transformer,
5064 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5065 >            super(p, b, i, f, t); this.nextRight = nextRight;
5066              this.transformer = transformer;
5067              this.reducer = reducer;
5068          }
5069 <        @SuppressWarnings("unchecked") public final boolean exec() {
5070 <            final Fun<? super V, ? extends U> transformer =
5071 <                this.transformer;
5072 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5073 <                this.reducer;
5074 <            if (transformer == null || reducer == null)
5075 <                return abortOnNullFunction();
5076 <            try {
5077 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6219 <                    do {} while (!casPending(c = pending, c+1));
5069 >        public final U getRawResult() { return result; }
5070 >        public final void compute() {
5071 >            final Function<? super V, ? extends U> transformer;
5072 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5073 >            if ((transformer = this.transformer) != null &&
5074 >                (reducer = this.reducer) != null) {
5075 >                for (int i = baseIndex, f, h; batch > 0 &&
5076 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5077 >                    addToPendingCount(1);
5078                      (rights = new MapReduceValuesTask<K,V,U>
5079 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5079 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5080 >                      rights, transformer, reducer)).fork();
5081                  }
5082 <                U r = null, u;
5083 <                Object v;
5084 <                while ((v = advance()) != null) {
5085 <                    if ((u = transformer.apply((V)v)) != null)
5082 >                U r = null;
5083 >                for (Node<K,V> p; (p = advance()) != null; ) {
5084 >                    U u;
5085 >                    if ((u = transformer.apply(p.val)) != null)
5086                          r = (r == null) ? u : reducer.apply(r, u);
5087                  }
5088                  result = r;
5089 <                for (MapReduceValuesTask<K,V,U> t = this, s;;) {
5090 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5091 <                    if ((c = t.pending) == 0) {
5092 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5093 <                            if ((sr = s.result) != null)
5094 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5095 <                        }
5096 <                        if ((par = t.parent) == null ||
5097 <                            !(par instanceof MapReduceValuesTask)) {
5098 <                            t.quietlyComplete();
5099 <                            break;
6241 <                        }
6242 <                        t = (MapReduceValuesTask<K,V,U>)par;
5089 >                CountedCompleter<?> c;
5090 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5091 >                    MapReduceValuesTask<K,V,U>
5092 >                        t = (MapReduceValuesTask<K,V,U>)c,
5093 >                        s = t.rights;
5094 >                    while (s != null) {
5095 >                        U tr, sr;
5096 >                        if ((sr = s.result) != null)
5097 >                            t.result = (((tr = t.result) == null) ? sr :
5098 >                                        reducer.apply(tr, sr));
5099 >                        s = t.rights = s.nextRight;
5100                      }
6244                    else if (t.casPending(c, c - 1))
6245                        break;
5101                  }
6247            } catch (Throwable ex) {
6248                return tryCompleteComputation(ex);
5102              }
6250            MapReduceValuesTask<K,V,U> s = rights;
6251            if (s != null && !inForkJoinPool()) {
6252                do  {
6253                    if (s.tryUnfork())
6254                        s.exec();
6255                } while ((s = s.nextRight) != null);
6256            }
6257            return false;
5103          }
6259        public final U getRawResult() { return result; }
5104      }
5105  
5106 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5106 >    static final class MapReduceEntriesTask<K,V,U>
5107          extends BulkTask<K,V,U> {
5108 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5109 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5108 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5109 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5110          U result;
5111          MapReduceEntriesTask<K,V,U> rights, nextRight;
5112          MapReduceEntriesTask
5113 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5113 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5114               MapReduceEntriesTask<K,V,U> nextRight,
5115 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5116 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5117 <            super(m, p, b); this.nextRight = nextRight;
5115 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5116 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5117 >            super(p, b, i, f, t); this.nextRight = nextRight;
5118              this.transformer = transformer;
5119              this.reducer = reducer;
5120          }
5121 <        @SuppressWarnings("unchecked") public final boolean exec() {
5122 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5123 <                this.transformer;
5124 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5125 <                this.reducer;
5126 <            if (transformer == null || reducer == null)
5127 <                return abortOnNullFunction();
5128 <            try {
5129 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6286 <                    do {} while (!casPending(c = pending, c+1));
5121 >        public final U getRawResult() { return result; }
5122 >        public final void compute() {
5123 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5124 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5125 >            if ((transformer = this.transformer) != null &&
5126 >                (reducer = this.reducer) != null) {
5127 >                for (int i = baseIndex, f, h; batch > 0 &&
5128 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5129 >                    addToPendingCount(1);
5130                      (rights = new MapReduceEntriesTask<K,V,U>
5131 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5131 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5132 >                      rights, transformer, reducer)).fork();
5133                  }
5134 <                U r = null, u;
5135 <                Object v;
5136 <                while ((v = advance()) != null) {
5137 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5134 >                U r = null;
5135 >                for (Node<K,V> p; (p = advance()) != null; ) {
5136 >                    U u;
5137 >                    if ((u = transformer.apply(p)) != null)
5138                          r = (r == null) ? u : reducer.apply(r, u);
5139                  }
5140                  result = r;
5141 <                for (MapReduceEntriesTask<K,V,U> t = this, s;;) {
5142 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5143 <                    if ((c = t.pending) == 0) {
5144 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5145 <                            if ((sr = s.result) != null)
5146 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5147 <                        }
5148 <                        if ((par = t.parent) == null ||
5149 <                            !(par instanceof MapReduceEntriesTask)) {
5150 <                            t.quietlyComplete();
5151 <                            break;
6308 <                        }
6309 <                        t = (MapReduceEntriesTask<K,V,U>)par;
5141 >                CountedCompleter<?> c;
5142 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5143 >                    MapReduceEntriesTask<K,V,U>
5144 >                        t = (MapReduceEntriesTask<K,V,U>)c,
5145 >                        s = t.rights;
5146 >                    while (s != null) {
5147 >                        U tr, sr;
5148 >                        if ((sr = s.result) != null)
5149 >                            t.result = (((tr = t.result) == null) ? sr :
5150 >                                        reducer.apply(tr, sr));
5151 >                        s = t.rights = s.nextRight;
5152                      }
6311                    else if (t.casPending(c, c - 1))
6312                        break;
5153                  }
6314            } catch (Throwable ex) {
6315                return tryCompleteComputation(ex);
5154              }
6317            MapReduceEntriesTask<K,V,U> s = rights;
6318            if (s != null && !inForkJoinPool()) {
6319                do  {
6320                    if (s.tryUnfork())
6321                        s.exec();
6322                } while ((s = s.nextRight) != null);
6323            }
6324            return false;
5155          }
6326        public final U getRawResult() { return result; }
5156      }
5157  
5158 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5158 >    static final class MapReduceMappingsTask<K,V,U>
5159          extends BulkTask<K,V,U> {
5160 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5161 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5160 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5161 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5162          U result;
5163          MapReduceMappingsTask<K,V,U> rights, nextRight;
5164          MapReduceMappingsTask
5165 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5165 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5166               MapReduceMappingsTask<K,V,U> nextRight,
5167 <             BiFun<? super K, ? super V, ? extends U> transformer,
5168 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5169 <            super(m, p, b); this.nextRight = nextRight;
5167 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5168 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5169 >            super(p, b, i, f, t); this.nextRight = nextRight;
5170              this.transformer = transformer;
5171              this.reducer = reducer;
5172          }
5173 <        @SuppressWarnings("unchecked") public final boolean exec() {
5174 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5175 <                this.transformer;
5176 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5177 <                this.reducer;
5178 <            if (transformer == null || reducer == null)
5179 <                return abortOnNullFunction();
5180 <            try {
5181 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6353 <                    do {} while (!casPending(c = pending, c+1));
5173 >        public final U getRawResult() { return result; }
5174 >        public final void compute() {
5175 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5176 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5177 >            if ((transformer = this.transformer) != null &&
5178 >                (reducer = this.reducer) != null) {
5179 >                for (int i = baseIndex, f, h; batch > 0 &&
5180 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5181 >                    addToPendingCount(1);
5182                      (rights = new MapReduceMappingsTask<K,V,U>
5183 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5183 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5184 >                      rights, transformer, reducer)).fork();
5185                  }
5186 <                U r = null, u;
5187 <                Object v;
5188 <                while ((v = advance()) != null) {
5189 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5186 >                U r = null;
5187 >                for (Node<K,V> p; (p = advance()) != null; ) {
5188 >                    U u;
5189 >                    if ((u = transformer.apply((K)p.key, p.val)) != null)
5190                          r = (r == null) ? u : reducer.apply(r, u);
5191                  }
5192                  result = r;
5193 <                for (MapReduceMappingsTask<K,V,U> t = this, s;;) {
5194 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5195 <                    if ((c = t.pending) == 0) {
5196 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5197 <                            if ((sr = s.result) != null)
5198 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5199 <                        }
5200 <                        if ((par = t.parent) == null ||
5201 <                            !(par instanceof MapReduceMappingsTask)) {
5202 <                            t.quietlyComplete();
5203 <                            break;
6375 <                        }
6376 <                        t = (MapReduceMappingsTask<K,V,U>)par;
5193 >                CountedCompleter<?> c;
5194 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5195 >                    MapReduceMappingsTask<K,V,U>
5196 >                        t = (MapReduceMappingsTask<K,V,U>)c,
5197 >                        s = t.rights;
5198 >                    while (s != null) {
5199 >                        U tr, sr;
5200 >                        if ((sr = s.result) != null)
5201 >                            t.result = (((tr = t.result) == null) ? sr :
5202 >                                        reducer.apply(tr, sr));
5203 >                        s = t.rights = s.nextRight;
5204                      }
6378                    else if (t.casPending(c, c - 1))
6379                        break;
5205                  }
6381            } catch (Throwable ex) {
6382                return tryCompleteComputation(ex);
6383            }
6384            MapReduceMappingsTask<K,V,U> s = rights;
6385            if (s != null && !inForkJoinPool()) {
6386                do  {
6387                    if (s.tryUnfork())
6388                        s.exec();
6389                } while ((s = s.nextRight) != null);
5206              }
6391            return false;
5207          }
6393        public final U getRawResult() { return result; }
5208      }
5209  
5210 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5210 >    static final class MapReduceKeysToDoubleTask<K,V>
5211          extends BulkTask<K,V,Double> {
5212 <        final ObjectToDouble<? super K> transformer;
5213 <        final DoubleByDoubleToDouble reducer;
5212 >        final ToDoubleFunction<? super K> transformer;
5213 >        final DoubleBinaryOperator reducer;
5214          final double basis;
5215          double result;
5216          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5217          MapReduceKeysToDoubleTask
5218 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5218 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5219               MapReduceKeysToDoubleTask<K,V> nextRight,
5220 <             ObjectToDouble<? super K> transformer,
5220 >             ToDoubleFunction<? super K> transformer,
5221               double basis,
5222 <             DoubleByDoubleToDouble reducer) {
5223 <            super(m, p, b); this.nextRight = nextRight;
5222 >             DoubleBinaryOperator reducer) {
5223 >            super(p, b, i, f, t); this.nextRight = nextRight;
5224              this.transformer = transformer;
5225              this.basis = basis; this.reducer = reducer;
5226          }
5227 <        @SuppressWarnings("unchecked") public final boolean exec() {
5228 <            final ObjectToDouble<? super K> transformer =
5229 <                this.transformer;
5230 <            final DoubleByDoubleToDouble reducer = this.reducer;
5231 <            if (transformer == null || reducer == null)
5232 <                return abortOnNullFunction();
5233 <            try {
5234 <                final double id = this.basis;
5235 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5236 <                    do {} while (!casPending(c = pending, c+1));
5227 >        public final Double getRawResult() { return result; }
5228 >        public final void compute() {
5229 >            final ToDoubleFunction<? super K> transformer;
5230 >            final DoubleBinaryOperator reducer;
5231 >            if ((transformer = this.transformer) != null &&
5232 >                (reducer = this.reducer) != null) {
5233 >                double r = this.basis;
5234 >                for (int i = baseIndex, f, h; batch > 0 &&
5235 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5236 >                    addToPendingCount(1);
5237                      (rights = new MapReduceKeysToDoubleTask<K,V>
5238 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5238 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5239 >                      rights, transformer, r, reducer)).fork();
5240                  }
5241 <                double r = id;
5242 <                while (advance() != null)
6428 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5241 >                for (Node<K,V> p; (p = advance()) != null; )
5242 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)p.key));
5243                  result = r;
5244 <                for (MapReduceKeysToDoubleTask<K,V> t = this, s;;) {
5245 <                    int c; BulkTask<K,V,?> par;
5246 <                    if ((c = t.pending) == 0) {
5247 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5248 <                            t.result = reducer.apply(t.result, s.result);
5249 <                        }
5250 <                        if ((par = t.parent) == null ||
5251 <                            !(par instanceof MapReduceKeysToDoubleTask)) {
6438 <                            t.quietlyComplete();
6439 <                            break;
6440 <                        }
6441 <                        t = (MapReduceKeysToDoubleTask<K,V>)par;
5244 >                CountedCompleter<?> c;
5245 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5246 >                    MapReduceKeysToDoubleTask<K,V>
5247 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
5248 >                        s = t.rights;
5249 >                    while (s != null) {
5250 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5251 >                        s = t.rights = s.nextRight;
5252                      }
6443                    else if (t.casPending(c, c - 1))
6444                        break;
5253                  }
6446            } catch (Throwable ex) {
6447                return tryCompleteComputation(ex);
6448            }
6449            MapReduceKeysToDoubleTask<K,V> s = rights;
6450            if (s != null && !inForkJoinPool()) {
6451                do  {
6452                    if (s.tryUnfork())
6453                        s.exec();
6454                } while ((s = s.nextRight) != null);
5254              }
6456            return false;
5255          }
6458        public final Double getRawResult() { return result; }
5256      }
5257  
5258 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5258 >    static final class MapReduceValuesToDoubleTask<K,V>
5259          extends BulkTask<K,V,Double> {
5260 <        final ObjectToDouble<? super V> transformer;
5261 <        final DoubleByDoubleToDouble reducer;
5260 >        final ToDoubleFunction<? super V> transformer;
5261 >        final DoubleBinaryOperator reducer;
5262          final double basis;
5263          double result;
5264          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5265          MapReduceValuesToDoubleTask
5266 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5266 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5267               MapReduceValuesToDoubleTask<K,V> nextRight,
5268 <             ObjectToDouble<? super V> transformer,
5268 >             ToDoubleFunction<? super V> transformer,
5269               double basis,
5270 <             DoubleByDoubleToDouble reducer) {
5271 <            super(m, p, b); this.nextRight = nextRight;
5270 >             DoubleBinaryOperator reducer) {
5271 >            super(p, b, i, f, t); this.nextRight = nextRight;
5272              this.transformer = transformer;
5273              this.basis = basis; this.reducer = reducer;
5274          }
5275 <        @SuppressWarnings("unchecked") public final boolean exec() {
5276 <            final ObjectToDouble<? super V> transformer =
5277 <                this.transformer;
5278 <            final DoubleByDoubleToDouble reducer = this.reducer;
5279 <            if (transformer == null || reducer == null)
5280 <                return abortOnNullFunction();
5281 <            try {
5282 <                final double id = this.basis;
5283 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5284 <                    do {} while (!casPending(c = pending, c+1));
5275 >        public final Double getRawResult() { return result; }
5276 >        public final void compute() {
5277 >            final ToDoubleFunction<? super V> transformer;
5278 >            final DoubleBinaryOperator reducer;
5279 >            if ((transformer = this.transformer) != null &&
5280 >                (reducer = this.reducer) != null) {
5281 >                double r = this.basis;
5282 >                for (int i = baseIndex, f, h; batch > 0 &&
5283 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5284 >                    addToPendingCount(1);
5285                      (rights = new MapReduceValuesToDoubleTask<K,V>
5286 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5286 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5287 >                      rights, transformer, r, reducer)).fork();
5288                  }
5289 <                double r = id;
5290 <                Object v;
6493 <                while ((v = advance()) != null)
6494 <                    r = reducer.apply(r, transformer.apply((V)v));
5289 >                for (Node<K,V> p; (p = advance()) != null; )
5290 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5291                  result = r;
5292 <                for (MapReduceValuesToDoubleTask<K,V> t = this, s;;) {
5293 <                    int c; BulkTask<K,V,?> par;
5294 <                    if ((c = t.pending) == 0) {
5295 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5296 <                            t.result = reducer.apply(t.result, s.result);
5297 <                        }
5298 <                        if ((par = t.parent) == null ||
5299 <                            !(par instanceof MapReduceValuesToDoubleTask)) {
6504 <                            t.quietlyComplete();
6505 <                            break;
6506 <                        }
6507 <                        t = (MapReduceValuesToDoubleTask<K,V>)par;
5292 >                CountedCompleter<?> c;
5293 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5294 >                    MapReduceValuesToDoubleTask<K,V>
5295 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
5296 >                        s = t.rights;
5297 >                    while (s != null) {
5298 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5299 >                        s = t.rights = s.nextRight;
5300                      }
6509                    else if (t.casPending(c, c - 1))
6510                        break;
5301                  }
6512            } catch (Throwable ex) {
6513                return tryCompleteComputation(ex);
5302              }
6515            MapReduceValuesToDoubleTask<K,V> s = rights;
6516            if (s != null && !inForkJoinPool()) {
6517                do  {
6518                    if (s.tryUnfork())
6519                        s.exec();
6520                } while ((s = s.nextRight) != null);
6521            }
6522            return false;
5303          }
6524        public final Double getRawResult() { return result; }
5304      }
5305  
5306 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5306 >    static final class MapReduceEntriesToDoubleTask<K,V>
5307          extends BulkTask<K,V,Double> {
5308 <        final ObjectToDouble<Map.Entry<K,V>> transformer;
5309 <        final DoubleByDoubleToDouble reducer;
5308 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
5309 >        final DoubleBinaryOperator reducer;
5310          final double basis;
5311          double result;
5312          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5313          MapReduceEntriesToDoubleTask
5314 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5314 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5315               MapReduceEntriesToDoubleTask<K,V> nextRight,
5316 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5316 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5317               double basis,
5318 <             DoubleByDoubleToDouble reducer) {
5319 <            super(m, p, b); this.nextRight = nextRight;
5318 >             DoubleBinaryOperator reducer) {
5319 >            super(p, b, i, f, t); this.nextRight = nextRight;
5320              this.transformer = transformer;
5321              this.basis = basis; this.reducer = reducer;
5322          }
5323 <        @SuppressWarnings("unchecked") public final boolean exec() {
5324 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
5325 <                this.transformer;
5326 <            final DoubleByDoubleToDouble reducer = this.reducer;
5327 <            if (transformer == null || reducer == null)
5328 <                return abortOnNullFunction();
5329 <            try {
5330 <                final double id = this.basis;
5331 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5332 <                    do {} while (!casPending(c = pending, c+1));
5323 >        public final Double getRawResult() { return result; }
5324 >        public final void compute() {
5325 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
5326 >            final DoubleBinaryOperator reducer;
5327 >            if ((transformer = this.transformer) != null &&
5328 >                (reducer = this.reducer) != null) {
5329 >                double r = this.basis;
5330 >                for (int i = baseIndex, f, h; batch > 0 &&
5331 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5332 >                    addToPendingCount(1);
5333                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5334 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5334 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5335 >                      rights, transformer, r, reducer)).fork();
5336                  }
5337 <                double r = id;
5338 <                Object v;
6559 <                while ((v = advance()) != null)
6560 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5337 >                for (Node<K,V> p; (p = advance()) != null; )
5338 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5339                  result = r;
5340 <                for (MapReduceEntriesToDoubleTask<K,V> t = this, s;;) {
5341 <                    int c; BulkTask<K,V,?> par;
5342 <                    if ((c = t.pending) == 0) {
5343 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5344 <                            t.result = reducer.apply(t.result, s.result);
5345 <                        }
5346 <                        if ((par = t.parent) == null ||
5347 <                            !(par instanceof MapReduceEntriesToDoubleTask)) {
6570 <                            t.quietlyComplete();
6571 <                            break;
6572 <                        }
6573 <                        t = (MapReduceEntriesToDoubleTask<K,V>)par;
5340 >                CountedCompleter<?> c;
5341 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5342 >                    MapReduceEntriesToDoubleTask<K,V>
5343 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
5344 >                        s = t.rights;
5345 >                    while (s != null) {
5346 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5347 >                        s = t.rights = s.nextRight;
5348                      }
6575                    else if (t.casPending(c, c - 1))
6576                        break;
5349                  }
6578            } catch (Throwable ex) {
6579                return tryCompleteComputation(ex);
6580            }
6581            MapReduceEntriesToDoubleTask<K,V> s = rights;
6582            if (s != null && !inForkJoinPool()) {
6583                do  {
6584                    if (s.tryUnfork())
6585                        s.exec();
6586                } while ((s = s.nextRight) != null);
5350              }
6588            return false;
5351          }
6590        public final Double getRawResult() { return result; }
5352      }
5353  
5354 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5354 >    static final class MapReduceMappingsToDoubleTask<K,V>
5355          extends BulkTask<K,V,Double> {
5356 <        final ObjectByObjectToDouble<? super K, ? super V> transformer;
5357 <        final DoubleByDoubleToDouble reducer;
5356 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
5357 >        final DoubleBinaryOperator reducer;
5358          final double basis;
5359          double result;
5360          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5361          MapReduceMappingsToDoubleTask
5362 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5362 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5363               MapReduceMappingsToDoubleTask<K,V> nextRight,
5364 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
5364 >             ToDoubleBiFunction<? super K, ? super V> transformer,
5365               double basis,
5366 <             DoubleByDoubleToDouble reducer) {
5367 <            super(m, p, b); this.nextRight = nextRight;
5366 >             DoubleBinaryOperator reducer) {
5367 >            super(p, b, i, f, t); this.nextRight = nextRight;
5368              this.transformer = transformer;
5369              this.basis = basis; this.reducer = reducer;
5370          }
5371 <        @SuppressWarnings("unchecked") public final boolean exec() {
5372 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
5373 <                this.transformer;
5374 <            final DoubleByDoubleToDouble reducer = this.reducer;
5375 <            if (transformer == null || reducer == null)
5376 <                return abortOnNullFunction();
5377 <            try {
5378 <                final double id = this.basis;
5379 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5380 <                    do {} while (!casPending(c = pending, c+1));
5371 >        public final Double getRawResult() { return result; }
5372 >        public final void compute() {
5373 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
5374 >            final DoubleBinaryOperator reducer;
5375 >            if ((transformer = this.transformer) != null &&
5376 >                (reducer = this.reducer) != null) {
5377 >                double r = this.basis;
5378 >                for (int i = baseIndex, f, h; batch > 0 &&
5379 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5380 >                    addToPendingCount(1);
5381                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5382 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5382 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5383 >                      rights, transformer, r, reducer)).fork();
5384                  }
5385 <                double r = id;
5386 <                Object v;
6625 <                while ((v = advance()) != null)
6626 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5385 >                for (Node<K,V> p; (p = advance()) != null; )
5386 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)p.key, p.val));
5387                  result = r;
5388 <                for (MapReduceMappingsToDoubleTask<K,V> t = this, s;;) {
5389 <                    int c; BulkTask<K,V,?> par;
5390 <                    if ((c = t.pending) == 0) {
5391 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5392 <                            t.result = reducer.apply(t.result, s.result);
5393 <                        }
5394 <                        if ((par = t.parent) == null ||
5395 <                            !(par instanceof MapReduceMappingsToDoubleTask)) {
6636 <                            t.quietlyComplete();
6637 <                            break;
6638 <                        }
6639 <                        t = (MapReduceMappingsToDoubleTask<K,V>)par;
5388 >                CountedCompleter<?> c;
5389 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5390 >                    MapReduceMappingsToDoubleTask<K,V>
5391 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
5392 >                        s = t.rights;
5393 >                    while (s != null) {
5394 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5395 >                        s = t.rights = s.nextRight;
5396                      }
6641                    else if (t.casPending(c, c - 1))
6642                        break;
5397                  }
6644            } catch (Throwable ex) {
6645                return tryCompleteComputation(ex);
5398              }
6647            MapReduceMappingsToDoubleTask<K,V> s = rights;
6648            if (s != null && !inForkJoinPool()) {
6649                do  {
6650                    if (s.tryUnfork())
6651                        s.exec();
6652                } while ((s = s.nextRight) != null);
6653            }
6654            return false;
5399          }
6656        public final Double getRawResult() { return result; }
5400      }
5401  
5402 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5402 >    static final class MapReduceKeysToLongTask<K,V>
5403          extends BulkTask<K,V,Long> {
5404 <        final ObjectToLong<? super K> transformer;
5405 <        final LongByLongToLong reducer;
5404 >        final ToLongFunction<? super K> transformer;
5405 >        final LongBinaryOperator reducer;
5406          final long basis;
5407          long result;
5408          MapReduceKeysToLongTask<K,V> rights, nextRight;
5409          MapReduceKeysToLongTask
5410 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5410 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5411               MapReduceKeysToLongTask<K,V> nextRight,
5412 <             ObjectToLong<? super K> transformer,
5412 >             ToLongFunction<? super K> transformer,
5413               long basis,
5414 <             LongByLongToLong reducer) {
5415 <            super(m, p, b); this.nextRight = nextRight;
5414 >             LongBinaryOperator reducer) {
5415 >            super(p, b, i, f, t); this.nextRight = nextRight;
5416              this.transformer = transformer;
5417              this.basis = basis; this.reducer = reducer;
5418          }
5419 <        @SuppressWarnings("unchecked") public final boolean exec() {
5420 <            final ObjectToLong<? super K> transformer =
5421 <                this.transformer;
5422 <            final LongByLongToLong reducer = this.reducer;
5423 <            if (transformer == null || reducer == null)
5424 <                return abortOnNullFunction();
5425 <            try {
5426 <                final long id = this.basis;
5427 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5428 <                    do {} while (!casPending(c = pending, c+1));
5419 >        public final Long getRawResult() { return result; }
5420 >        public final void compute() {
5421 >            final ToLongFunction<? super K> transformer;
5422 >            final LongBinaryOperator reducer;
5423 >            if ((transformer = this.transformer) != null &&
5424 >                (reducer = this.reducer) != null) {
5425 >                long r = this.basis;
5426 >                for (int i = baseIndex, f, h; batch > 0 &&
5427 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5428 >                    addToPendingCount(1);
5429                      (rights = new MapReduceKeysToLongTask<K,V>
5430 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5430 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5431 >                      rights, transformer, r, reducer)).fork();
5432                  }
5433 <                long r = id;
5434 <                while (advance() != null)
6691 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5433 >                for (Node<K,V> p; (p = advance()) != null; )
5434 >                    r = reducer.applyAsLong(r, transformer.applyAsLong((K)p.key));
5435                  result = r;
5436 <                for (MapReduceKeysToLongTask<K,V> t = this, s;;) {
5437 <                    int c; BulkTask<K,V,?> par;
5438 <                    if ((c = t.pending) == 0) {
5439 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5440 <                            t.result = reducer.apply(t.result, s.result);
5441 <                        }
5442 <                        if ((par = t.parent) == null ||
5443 <                            !(par instanceof MapReduceKeysToLongTask)) {
6701 <                            t.quietlyComplete();
6702 <                            break;
6703 <                        }
6704 <                        t = (MapReduceKeysToLongTask<K,V>)par;
5436 >                CountedCompleter<?> c;
5437 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5438 >                    MapReduceKeysToLongTask<K,V>
5439 >                        t = (MapReduceKeysToLongTask<K,V>)c,
5440 >                        s = t.rights;
5441 >                    while (s != null) {
5442 >                        t.result = reducer.applyAsLong(t.result, s.result);
5443 >                        s = t.rights = s.nextRight;
5444                      }
6706                    else if (t.casPending(c, c - 1))
6707                        break;
5445                  }
6709            } catch (Throwable ex) {
6710                return tryCompleteComputation(ex);
5446              }
6712            MapReduceKeysToLongTask<K,V> s = rights;
6713            if (s != null && !inForkJoinPool()) {
6714                do  {
6715                    if (s.tryUnfork())
6716                        s.exec();
6717                } while ((s = s.nextRight) != null);
6718            }
6719            return false;
5447          }
6721        public final Long getRawResult() { return result; }
5448      }
5449  
5450 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5450 >    static final class MapReduceValuesToLongTask<K,V>
5451          extends BulkTask<K,V,Long> {
5452 <        final ObjectToLong<? super V> transformer;
5453 <        final LongByLongToLong reducer;
5452 >        final ToLongFunction<? super V> transformer;
5453 >        final LongBinaryOperator reducer;
5454          final long basis;
5455          long result;
5456          MapReduceValuesToLongTask<K,V> rights, nextRight;
5457          MapReduceValuesToLongTask
5458 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5458 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5459               MapReduceValuesToLongTask<K,V> nextRight,
5460 <             ObjectToLong<? super V> transformer,
5460 >             ToLongFunction<? super V> transformer,
5461               long basis,
5462 <             LongByLongToLong reducer) {
5463 <            super(m, p, b); this.nextRight = nextRight;
5462 >             LongBinaryOperator reducer) {
5463 >            super(p, b, i, f, t); this.nextRight = nextRight;
5464              this.transformer = transformer;
5465              this.basis = basis; this.reducer = reducer;
5466          }
5467 <        @SuppressWarnings("unchecked") public final boolean exec() {
5468 <            final ObjectToLong<? super V> transformer =
5469 <                this.transformer;
5470 <            final LongByLongToLong reducer = this.reducer;
5471 <            if (transformer == null || reducer == null)
5472 <                return abortOnNullFunction();
5473 <            try {
5474 <                final long id = this.basis;
5475 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5476 <                    do {} while (!casPending(c = pending, c+1));
5467 >        public final Long getRawResult() { return result; }
5468 >        public final void compute() {
5469 >            final ToLongFunction<? super V> transformer;
5470 >            final LongBinaryOperator reducer;
5471 >            if ((transformer = this.transformer) != null &&
5472 >                (reducer = this.reducer) != null) {
5473 >                long r = this.basis;
5474 >                for (int i = baseIndex, f, h; batch > 0 &&
5475 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5476 >                    addToPendingCount(1);
5477                      (rights = new MapReduceValuesToLongTask<K,V>
5478 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5478 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5479 >                      rights, transformer, r, reducer)).fork();
5480                  }
5481 <                long r = id;
5482 <                Object v;
6756 <                while ((v = advance()) != null)
6757 <                    r = reducer.apply(r, transformer.apply((V)v));
5481 >                for (Node<K,V> p; (p = advance()) != null; )
5482 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5483                  result = r;
5484 <                for (MapReduceValuesToLongTask<K,V> t = this, s;;) {
5485 <                    int c; BulkTask<K,V,?> par;
5486 <                    if ((c = t.pending) == 0) {
5487 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5488 <                            t.result = reducer.apply(t.result, s.result);
5489 <                        }
5490 <                        if ((par = t.parent) == null ||
5491 <                            !(par instanceof MapReduceValuesToLongTask)) {
6767 <                            t.quietlyComplete();
6768 <                            break;
6769 <                        }
6770 <                        t = (MapReduceValuesToLongTask<K,V>)par;
5484 >                CountedCompleter<?> c;
5485 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5486 >                    MapReduceValuesToLongTask<K,V>
5487 >                        t = (MapReduceValuesToLongTask<K,V>)c,
5488 >                        s = t.rights;
5489 >                    while (s != null) {
5490 >                        t.result = reducer.applyAsLong(t.result, s.result);
5491 >                        s = t.rights = s.nextRight;
5492                      }
6772                    else if (t.casPending(c, c - 1))
6773                        break;
5493                  }
6775            } catch (Throwable ex) {
6776                return tryCompleteComputation(ex);
6777            }
6778            MapReduceValuesToLongTask<K,V> s = rights;
6779            if (s != null && !inForkJoinPool()) {
6780                do  {
6781                    if (s.tryUnfork())
6782                        s.exec();
6783                } while ((s = s.nextRight) != null);
5494              }
6785            return false;
5495          }
6787        public final Long getRawResult() { return result; }
5496      }
5497  
5498 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5498 >    static final class MapReduceEntriesToLongTask<K,V>
5499          extends BulkTask<K,V,Long> {
5500 <        final ObjectToLong<Map.Entry<K,V>> transformer;
5501 <        final LongByLongToLong reducer;
5500 >        final ToLongFunction<Map.Entry<K,V>> transformer;
5501 >        final LongBinaryOperator reducer;
5502          final long basis;
5503          long result;
5504          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5505          MapReduceEntriesToLongTask
5506 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5506 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5507               MapReduceEntriesToLongTask<K,V> nextRight,
5508 <             ObjectToLong<Map.Entry<K,V>> transformer,
5508 >             ToLongFunction<Map.Entry<K,V>> transformer,
5509               long basis,
5510 <             LongByLongToLong reducer) {
5511 <            super(m, p, b); this.nextRight = nextRight;
5510 >             LongBinaryOperator reducer) {
5511 >            super(p, b, i, f, t); this.nextRight = nextRight;
5512              this.transformer = transformer;
5513              this.basis = basis; this.reducer = reducer;
5514          }
5515 <        @SuppressWarnings("unchecked") public final boolean exec() {
5516 <            final ObjectToLong<Map.Entry<K,V>> transformer =
5517 <                this.transformer;
5518 <            final LongByLongToLong reducer = this.reducer;
5519 <            if (transformer == null || reducer == null)
5520 <                return abortOnNullFunction();
5521 <            try {
5522 <                final long id = this.basis;
5523 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5524 <                    do {} while (!casPending(c = pending, c+1));
5515 >        public final Long getRawResult() { return result; }
5516 >        public final void compute() {
5517 >            final ToLongFunction<Map.Entry<K,V>> transformer;
5518 >            final LongBinaryOperator reducer;
5519 >            if ((transformer = this.transformer) != null &&
5520 >                (reducer = this.reducer) != null) {
5521 >                long r = this.basis;
5522 >                for (int i = baseIndex, f, h; batch > 0 &&
5523 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5524 >                    addToPendingCount(1);
5525                      (rights = new MapReduceEntriesToLongTask<K,V>
5526 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5526 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5527 >                      rights, transformer, r, reducer)).fork();
5528                  }
5529 <                long r = id;
5530 <                Object v;
6822 <                while ((v = advance()) != null)
6823 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5529 >                for (Node<K,V> p; (p = advance()) != null; )
5530 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
5531                  result = r;
5532 <                for (MapReduceEntriesToLongTask<K,V> t = this, s;;) {
5533 <                    int c; BulkTask<K,V,?> par;
5534 <                    if ((c = t.pending) == 0) {
5535 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5536 <                            t.result = reducer.apply(t.result, s.result);
5537 <                        }
5538 <                        if ((par = t.parent) == null ||
5539 <                            !(par instanceof MapReduceEntriesToLongTask)) {
6833 <                            t.quietlyComplete();
6834 <                            break;
6835 <                        }
6836 <                        t = (MapReduceEntriesToLongTask<K,V>)par;
5532 >                CountedCompleter<?> c;
5533 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5534 >                    MapReduceEntriesToLongTask<K,V>
5535 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
5536 >                        s = t.rights;
5537 >                    while (s != null) {
5538 >                        t.result = reducer.applyAsLong(t.result, s.result);
5539 >                        s = t.rights = s.nextRight;
5540                      }
6838                    else if (t.casPending(c, c - 1))
6839                        break;
5541                  }
6841            } catch (Throwable ex) {
6842                return tryCompleteComputation(ex);
5542              }
6844            MapReduceEntriesToLongTask<K,V> s = rights;
6845            if (s != null && !inForkJoinPool()) {
6846                do  {
6847                    if (s.tryUnfork())
6848                        s.exec();
6849                } while ((s = s.nextRight) != null);
6850            }
6851            return false;
5543          }
6853        public final Long getRawResult() { return result; }
5544      }
5545  
5546 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
5546 >    static final class MapReduceMappingsToLongTask<K,V>
5547          extends BulkTask<K,V,Long> {
5548 <        final ObjectByObjectToLong<? super K, ? super V> transformer;
5549 <        final LongByLongToLong reducer;
5548 >        final ToLongBiFunction<? super K, ? super V> transformer;
5549 >        final LongBinaryOperator reducer;
5550          final long basis;
5551          long result;
5552          MapReduceMappingsToLongTask<K,V> rights, nextRight;
5553          MapReduceMappingsToLongTask
5554 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5554 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5555               MapReduceMappingsToLongTask<K,V> nextRight,
5556 <             ObjectByObjectToLong<? super K, ? super V> transformer,
5556 >             ToLongBiFunction<? super K, ? super V> transformer,
5557               long basis,
5558 <             LongByLongToLong reducer) {
5559 <            super(m, p, b); this.nextRight = nextRight;
5558 >             LongBinaryOperator reducer) {
5559 >            super(p, b, i, f, t); this.nextRight = nextRight;
5560              this.transformer = transformer;
5561              this.basis = basis; this.reducer = reducer;
5562          }
5563 <        @SuppressWarnings("unchecked") public final boolean exec() {
5564 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
5565 <                this.transformer;
5566 <            final LongByLongToLong reducer = this.reducer;
5567 <            if (transformer == null || reducer == null)
5568 <                return abortOnNullFunction();
5569 <            try {
5570 <                final long id = this.basis;
5571 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5572 <                    do {} while (!casPending(c = pending, c+1));
5563 >        public final Long getRawResult() { return result; }
5564 >        public final void compute() {
5565 >            final ToLongBiFunction<? super K, ? super V> transformer;
5566 >            final LongBinaryOperator reducer;
5567 >            if ((transformer = this.transformer) != null &&
5568 >                (reducer = this.reducer) != null) {
5569 >                long r = this.basis;
5570 >                for (int i = baseIndex, f, h; batch > 0 &&
5571 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5572 >                    addToPendingCount(1);
5573                      (rights = new MapReduceMappingsToLongTask<K,V>
5574 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5574 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5575 >                      rights, transformer, r, reducer)).fork();
5576                  }
5577 <                long r = id;
5578 <                Object v;
6888 <                while ((v = advance()) != null)
6889 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5577 >                for (Node<K,V> p; (p = advance()) != null; )
5578 >                    r = reducer.applyAsLong(r, transformer.applyAsLong((K)p.key, p.val));
5579                  result = r;
5580 <                for (MapReduceMappingsToLongTask<K,V> t = this, s;;) {
5581 <                    int c; BulkTask<K,V,?> par;
5582 <                    if ((c = t.pending) == 0) {
5583 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5584 <                            t.result = reducer.apply(t.result, s.result);
5585 <                        }
5586 <                        if ((par = t.parent) == null ||
5587 <                            !(par instanceof MapReduceMappingsToLongTask)) {
6899 <                            t.quietlyComplete();
6900 <                            break;
6901 <                        }
6902 <                        t = (MapReduceMappingsToLongTask<K,V>)par;
5580 >                CountedCompleter<?> c;
5581 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5582 >                    MapReduceMappingsToLongTask<K,V>
5583 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
5584 >                        s = t.rights;
5585 >                    while (s != null) {
5586 >                        t.result = reducer.applyAsLong(t.result, s.result);
5587 >                        s = t.rights = s.nextRight;
5588                      }
6904                    else if (t.casPending(c, c - 1))
6905                        break;
5589                  }
6907            } catch (Throwable ex) {
6908                return tryCompleteComputation(ex);
6909            }
6910            MapReduceMappingsToLongTask<K,V> s = rights;
6911            if (s != null && !inForkJoinPool()) {
6912                do  {
6913                    if (s.tryUnfork())
6914                        s.exec();
6915                } while ((s = s.nextRight) != null);
5590              }
6917            return false;
5591          }
6919        public final Long getRawResult() { return result; }
5592      }
5593  
5594 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
5594 >    static final class MapReduceKeysToIntTask<K,V>
5595          extends BulkTask<K,V,Integer> {
5596 <        final ObjectToInt<? super K> transformer;
5597 <        final IntByIntToInt reducer;
5596 >        final ToIntFunction<? super K> transformer;
5597 >        final IntBinaryOperator reducer;
5598          final int basis;
5599          int result;
5600          MapReduceKeysToIntTask<K,V> rights, nextRight;
5601          MapReduceKeysToIntTask
5602 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5602 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5603               MapReduceKeysToIntTask<K,V> nextRight,
5604 <             ObjectToInt<? super K> transformer,
5604 >             ToIntFunction<? super K> transformer,
5605               int basis,
5606 <             IntByIntToInt reducer) {
5607 <            super(m, p, b); this.nextRight = nextRight;
5606 >             IntBinaryOperator reducer) {
5607 >            super(p, b, i, f, t); this.nextRight = nextRight;
5608              this.transformer = transformer;
5609              this.basis = basis; this.reducer = reducer;
5610          }
5611 <        @SuppressWarnings("unchecked") public final boolean exec() {
5612 <            final ObjectToInt<? super K> transformer =
5613 <                this.transformer;
5614 <            final IntByIntToInt reducer = this.reducer;
5615 <            if (transformer == null || reducer == null)
5616 <                return abortOnNullFunction();
5617 <            try {
5618 <                final int id = this.basis;
5619 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5620 <                    do {} while (!casPending(c = pending, c+1));
5611 >        public final Integer getRawResult() { return result; }
5612 >        public final void compute() {
5613 >            final ToIntFunction<? super K> transformer;
5614 >            final IntBinaryOperator reducer;
5615 >            if ((transformer = this.transformer) != null &&
5616 >                (reducer = this.reducer) != null) {
5617 >                int r = this.basis;
5618 >                for (int i = baseIndex, f, h; batch > 0 &&
5619 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5620 >                    addToPendingCount(1);
5621                      (rights = new MapReduceKeysToIntTask<K,V>
5622 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5622 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5623 >                      rights, transformer, r, reducer)).fork();
5624                  }
5625 <                int r = id;
5626 <                while (advance() != null)
6954 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5625 >                for (Node<K,V> p; (p = advance()) != null; )
5626 >                    r = reducer.applyAsInt(r, transformer.applyAsInt((K)p.key));
5627                  result = r;
5628 <                for (MapReduceKeysToIntTask<K,V> t = this, s;;) {
5629 <                    int c; BulkTask<K,V,?> par;
5630 <                    if ((c = t.pending) == 0) {
5631 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5632 <                            t.result = reducer.apply(t.result, s.result);
5633 <                        }
5634 <                        if ((par = t.parent) == null ||
5635 <                            !(par instanceof MapReduceKeysToIntTask)) {
6964 <                            t.quietlyComplete();
6965 <                            break;
6966 <                        }
6967 <                        t = (MapReduceKeysToIntTask<K,V>)par;
5628 >                CountedCompleter<?> c;
5629 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5630 >                    MapReduceKeysToIntTask<K,V>
5631 >                        t = (MapReduceKeysToIntTask<K,V>)c,
5632 >                        s = t.rights;
5633 >                    while (s != null) {
5634 >                        t.result = reducer.applyAsInt(t.result, s.result);
5635 >                        s = t.rights = s.nextRight;
5636                      }
6969                    else if (t.casPending(c, c - 1))
6970                        break;
5637                  }
6972            } catch (Throwable ex) {
6973                return tryCompleteComputation(ex);
6974            }
6975            MapReduceKeysToIntTask<K,V> s = rights;
6976            if (s != null && !inForkJoinPool()) {
6977                do  {
6978                    if (s.tryUnfork())
6979                        s.exec();
6980                } while ((s = s.nextRight) != null);
5638              }
6982            return false;
5639          }
6984        public final Integer getRawResult() { return result; }
5640      }
5641  
5642 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
5642 >    static final class MapReduceValuesToIntTask<K,V>
5643          extends BulkTask<K,V,Integer> {
5644 <        final ObjectToInt<? super V> transformer;
5645 <        final IntByIntToInt reducer;
5644 >        final ToIntFunction<? super V> transformer;
5645 >        final IntBinaryOperator reducer;
5646          final int basis;
5647          int result;
5648          MapReduceValuesToIntTask<K,V> rights, nextRight;
5649          MapReduceValuesToIntTask
5650 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5650 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5651               MapReduceValuesToIntTask<K,V> nextRight,
5652 <             ObjectToInt<? super V> transformer,
5652 >             ToIntFunction<? super V> transformer,
5653               int basis,
5654 <             IntByIntToInt reducer) {
5655 <            super(m, p, b); this.nextRight = nextRight;
5654 >             IntBinaryOperator reducer) {
5655 >            super(p, b, i, f, t); this.nextRight = nextRight;
5656              this.transformer = transformer;
5657              this.basis = basis; this.reducer = reducer;
5658          }
5659 <        @SuppressWarnings("unchecked") public final boolean exec() {
5660 <            final ObjectToInt<? super V> transformer =
5661 <                this.transformer;
5662 <            final IntByIntToInt reducer = this.reducer;
5663 <            if (transformer == null || reducer == null)
5664 <                return abortOnNullFunction();
5665 <            try {
5666 <                final int id = this.basis;
5667 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5668 <                    do {} while (!casPending(c = pending, c+1));
5659 >        public final Integer getRawResult() { return result; }
5660 >        public final void compute() {
5661 >            final ToIntFunction<? super V> transformer;
5662 >            final IntBinaryOperator reducer;
5663 >            if ((transformer = this.transformer) != null &&
5664 >                (reducer = this.reducer) != null) {
5665 >                int r = this.basis;
5666 >                for (int i = baseIndex, f, h; batch > 0 &&
5667 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5668 >                    addToPendingCount(1);
5669                      (rights = new MapReduceValuesToIntTask<K,V>
5670 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5670 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5671 >                      rights, transformer, r, reducer)).fork();
5672                  }
5673 <                int r = id;
5674 <                Object v;
7019 <                while ((v = advance()) != null)
7020 <                    r = reducer.apply(r, transformer.apply((V)v));
5673 >                for (Node<K,V> p; (p = advance()) != null; )
5674 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
5675                  result = r;
5676 <                for (MapReduceValuesToIntTask<K,V> t = this, s;;) {
5677 <                    int c; BulkTask<K,V,?> par;
5678 <                    if ((c = t.pending) == 0) {
5679 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5680 <                            t.result = reducer.apply(t.result, s.result);
5681 <                        }
5682 <                        if ((par = t.parent) == null ||
5683 <                            !(par instanceof MapReduceValuesToIntTask)) {
7030 <                            t.quietlyComplete();
7031 <                            break;
7032 <                        }
7033 <                        t = (MapReduceValuesToIntTask<K,V>)par;
5676 >                CountedCompleter<?> c;
5677 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5678 >                    MapReduceValuesToIntTask<K,V>
5679 >                        t = (MapReduceValuesToIntTask<K,V>)c,
5680 >                        s = t.rights;
5681 >                    while (s != null) {
5682 >                        t.result = reducer.applyAsInt(t.result, s.result);
5683 >                        s = t.rights = s.nextRight;
5684                      }
7035                    else if (t.casPending(c, c - 1))
7036                        break;
5685                  }
7038            } catch (Throwable ex) {
7039                return tryCompleteComputation(ex);
5686              }
7041            MapReduceValuesToIntTask<K,V> s = rights;
7042            if (s != null && !inForkJoinPool()) {
7043                do  {
7044                    if (s.tryUnfork())
7045                        s.exec();
7046                } while ((s = s.nextRight) != null);
7047            }
7048            return false;
5687          }
7050        public final Integer getRawResult() { return result; }
5688      }
5689  
5690 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
5690 >    static final class MapReduceEntriesToIntTask<K,V>
5691          extends BulkTask<K,V,Integer> {
5692 <        final ObjectToInt<Map.Entry<K,V>> transformer;
5693 <        final IntByIntToInt reducer;
5692 >        final ToIntFunction<Map.Entry<K,V>> transformer;
5693 >        final IntBinaryOperator reducer;
5694          final int basis;
5695          int result;
5696          MapReduceEntriesToIntTask<K,V> rights, nextRight;
5697          MapReduceEntriesToIntTask
5698 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5698 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5699               MapReduceEntriesToIntTask<K,V> nextRight,
5700 <             ObjectToInt<Map.Entry<K,V>> transformer,
5700 >             ToIntFunction<Map.Entry<K,V>> transformer,
5701               int basis,
5702 <             IntByIntToInt reducer) {
5703 <            super(m, p, b); this.nextRight = nextRight;
5702 >             IntBinaryOperator reducer) {
5703 >            super(p, b, i, f, t); this.nextRight = nextRight;
5704              this.transformer = transformer;
5705              this.basis = basis; this.reducer = reducer;
5706          }
5707 <        @SuppressWarnings("unchecked") public final boolean exec() {
5708 <            final ObjectToInt<Map.Entry<K,V>> transformer =
5709 <                this.transformer;
5710 <            final IntByIntToInt reducer = this.reducer;
5711 <            if (transformer == null || reducer == null)
5712 <                return abortOnNullFunction();
5713 <            try {
5714 <                final int id = this.basis;
5715 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5716 <                    do {} while (!casPending(c = pending, c+1));
5707 >        public final Integer getRawResult() { return result; }
5708 >        public final void compute() {
5709 >            final ToIntFunction<Map.Entry<K,V>> transformer;
5710 >            final IntBinaryOperator reducer;
5711 >            if ((transformer = this.transformer) != null &&
5712 >                (reducer = this.reducer) != null) {
5713 >                int r = this.basis;
5714 >                for (int i = baseIndex, f, h; batch > 0 &&
5715 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5716 >                    addToPendingCount(1);
5717                      (rights = new MapReduceEntriesToIntTask<K,V>
5718 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5718 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5719 >                      rights, transformer, r, reducer)).fork();
5720                  }
5721 <                int r = id;
5722 <                Object v;
7085 <                while ((v = advance()) != null)
7086 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5721 >                for (Node<K,V> p; (p = advance()) != null; )
5722 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
5723                  result = r;
5724 <                for (MapReduceEntriesToIntTask<K,V> t = this, s;;) {
5725 <                    int c; BulkTask<K,V,?> par;
5726 <                    if ((c = t.pending) == 0) {
5727 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5728 <                            t.result = reducer.apply(t.result, s.result);
5729 <                        }
5730 <                        if ((par = t.parent) == null ||
5731 <                            !(par instanceof MapReduceEntriesToIntTask)) {
7096 <                            t.quietlyComplete();
7097 <                            break;
7098 <                        }
7099 <                        t = (MapReduceEntriesToIntTask<K,V>)par;
5724 >                CountedCompleter<?> c;
5725 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5726 >                    MapReduceEntriesToIntTask<K,V>
5727 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
5728 >                        s = t.rights;
5729 >                    while (s != null) {
5730 >                        t.result = reducer.applyAsInt(t.result, s.result);
5731 >                        s = t.rights = s.nextRight;
5732                      }
7101                    else if (t.casPending(c, c - 1))
7102                        break;
5733                  }
7104            } catch (Throwable ex) {
7105                return tryCompleteComputation(ex);
5734              }
7107            MapReduceEntriesToIntTask<K,V> s = rights;
7108            if (s != null && !inForkJoinPool()) {
7109                do  {
7110                    if (s.tryUnfork())
7111                        s.exec();
7112                } while ((s = s.nextRight) != null);
7113            }
7114            return false;
5735          }
7116        public final Integer getRawResult() { return result; }
5736      }
5737  
5738 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
5738 >    static final class MapReduceMappingsToIntTask<K,V>
5739          extends BulkTask<K,V,Integer> {
5740 <        final ObjectByObjectToInt<? super K, ? super V> transformer;
5741 <        final IntByIntToInt reducer;
5740 >        final ToIntBiFunction<? super K, ? super V> transformer;
5741 >        final IntBinaryOperator reducer;
5742          final int basis;
5743          int result;
5744          MapReduceMappingsToIntTask<K,V> rights, nextRight;
5745          MapReduceMappingsToIntTask
5746 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5747 <             MapReduceMappingsToIntTask<K,V> rights,
5748 <             ObjectByObjectToInt<? super K, ? super V> transformer,
5746 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5747 >             MapReduceMappingsToIntTask<K,V> nextRight,
5748 >             ToIntBiFunction<? super K, ? super V> transformer,
5749               int basis,
5750 <             IntByIntToInt reducer) {
5751 <            super(m, p, b); this.nextRight = nextRight;
5750 >             IntBinaryOperator reducer) {
5751 >            super(p, b, i, f, t); this.nextRight = nextRight;
5752              this.transformer = transformer;
5753              this.basis = basis; this.reducer = reducer;
5754          }
5755 <        @SuppressWarnings("unchecked") public final boolean exec() {
5756 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
5757 <                this.transformer;
5758 <            final IntByIntToInt reducer = this.reducer;
5759 <            if (transformer == null || reducer == null)
5760 <                return abortOnNullFunction();
5761 <            try {
5762 <                final int id = this.basis;
5763 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5764 <                    do {} while (!casPending(c = pending, c+1));
5755 >        public final Integer getRawResult() { return result; }
5756 >        public final void compute() {
5757 >            final ToIntBiFunction<? super K, ? super V> transformer;
5758 >            final IntBinaryOperator reducer;
5759 >            if ((transformer = this.transformer) != null &&
5760 >                (reducer = this.reducer) != null) {
5761 >                int r = this.basis;
5762 >                for (int i = baseIndex, f, h; batch > 0 &&
5763 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5764 >                    addToPendingCount(1);
5765                      (rights = new MapReduceMappingsToIntTask<K,V>
5766 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5766 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5767 >                      rights, transformer, r, reducer)).fork();
5768                  }
5769 <                int r = id;
5770 <                Object v;
7151 <                while ((v = advance()) != null)
7152 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5769 >                for (Node<K,V> p; (p = advance()) != null; )
5770 >                    r = reducer.applyAsInt(r, transformer.applyAsInt((K)p.key, p.val));
5771                  result = r;
5772 <                for (MapReduceMappingsToIntTask<K,V> t = this, s;;) {
5773 <                    int c; BulkTask<K,V,?> par;
5774 <                    if ((c = t.pending) == 0) {
5775 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5776 <                            t.result = reducer.apply(t.result, s.result);
5777 <                        }
5778 <                        if ((par = t.parent) == null ||
5779 <                            !(par instanceof MapReduceMappingsToIntTask)) {
7162 <                            t.quietlyComplete();
7163 <                            break;
7164 <                        }
7165 <                        t = (MapReduceMappingsToIntTask<K,V>)par;
5772 >                CountedCompleter<?> c;
5773 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5774 >                    MapReduceMappingsToIntTask<K,V>
5775 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
5776 >                        s = t.rights;
5777 >                    while (s != null) {
5778 >                        t.result = reducer.applyAsInt(t.result, s.result);
5779 >                        s = t.rights = s.nextRight;
5780                      }
7167                    else if (t.casPending(c, c - 1))
7168                        break;
5781                  }
7170            } catch (Throwable ex) {
7171                return tryCompleteComputation(ex);
7172            }
7173            MapReduceMappingsToIntTask<K,V> s = rights;
7174            if (s != null && !inForkJoinPool()) {
7175                do  {
7176                    if (s.tryUnfork())
7177                        s.exec();
7178                } while ((s = s.nextRight) != null);
5782              }
7180            return false;
5783          }
7182        public final Integer getRawResult() { return result; }
5784      }
5785  
5786      // Unsafe mechanics
5787 <    private static final sun.misc.Unsafe UNSAFE;
5788 <    private static final long counterOffset;
5789 <    private static final long sizeCtlOffset;
5787 >    private static final sun.misc.Unsafe U;
5788 >    private static final long SIZECTL;
5789 >    private static final long TRANSFERINDEX;
5790 >    private static final long TRANSFERORIGIN;
5791 >    private static final long BASECOUNT;
5792 >    private static final long CELLSBUSY;
5793 >    private static final long CELLVALUE;
5794      private static final long ABASE;
5795      private static final int ASHIFT;
5796  
5797      static {
7193        int ss;
5798          try {
5799 <            UNSAFE = sun.misc.Unsafe.getUnsafe();
5799 >            U = sun.misc.Unsafe.getUnsafe();
5800              Class<?> k = ConcurrentHashMap.class;
5801 <            counterOffset = UNSAFE.objectFieldOffset
7198 <                (k.getDeclaredField("counter"));
7199 <            sizeCtlOffset = UNSAFE.objectFieldOffset
5801 >            SIZECTL = U.objectFieldOffset
5802                  (k.getDeclaredField("sizeCtl"));
5803 +            TRANSFERINDEX = U.objectFieldOffset
5804 +                (k.getDeclaredField("transferIndex"));
5805 +            TRANSFERORIGIN = U.objectFieldOffset
5806 +                (k.getDeclaredField("transferOrigin"));
5807 +            BASECOUNT = U.objectFieldOffset
5808 +                (k.getDeclaredField("baseCount"));
5809 +            CELLSBUSY = U.objectFieldOffset
5810 +                (k.getDeclaredField("cellsBusy"));
5811 +            Class<?> ck = Cell.class;
5812 +            CELLVALUE = U.objectFieldOffset
5813 +                (ck.getDeclaredField("value"));
5814              Class<?> sc = Node[].class;
5815 <            ABASE = UNSAFE.arrayBaseOffset(sc);
5816 <            ss = UNSAFE.arrayIndexScale(sc);
5815 >            ABASE = U.arrayBaseOffset(sc);
5816 >            int scale = U.arrayIndexScale(sc);
5817 >            if ((scale & (scale - 1)) != 0)
5818 >                throw new Error("data type scale not a power of two");
5819 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
5820          } catch (Exception e) {
5821              throw new Error(e);
5822          }
7207        if ((ss & (ss-1)) != 0)
7208            throw new Error("data type scale not a power of two");
7209        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
5823      }
5824   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines