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.220 by jsr166, Wed Jun 5 13:48:59 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 fully utilize the {@link
171 + * ForkJoinPool#commonPool()} that is used for all parallel
172 + * computations. Normally, you would initially choose one of these
173 + * extreme values, and then measure performance of using in-between
174 + * values that trade off overhead versus throughput.
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 type of the form "class C
687 +     * implements Comparable<C>", if one exists, else null.  See below
688 +     * for explanation.
689 +     */
690 +    static Class<?> comparableClassFor(Class<?> c) {
691 +        Class<?> s, cmpc; Type[] ts, as; Type t; ParameterizedType p;
692 +        if (c == String.class) // bypass checks
693 +            return c;
694 +        if (c != null && (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; Class<?> pc;
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 || pk == null ||
799 +                         ((pc = pk.getClass()) != cc &&
800 +                          comparableClassFor(pc) != cc) ||
801 +                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
802 +                    TreeNode<K,V> r, pr; // check both sides
803 +                    if ((pr = p.right) != null &&
804 +                        (r = getTreeNode(h, k, pr, cc)) != null)
805 +                        return r;
806 +                    else // continue left
807 +                        dir = -1;
808 +                }
809                  p = (dir > 0) ? p.right : p.left;
810              }
811              return null;
# Line 872 | Line 816 | public class ConcurrentHashMap<K, V>
816           * read-lock to call getTreeNode, but during failure to get
817           * lock, searches along next links.
818           */
819 <        final Object getValue(int h, Object k) {
820 <            Node r = null;
821 <            int c = getState(); // Must read lock state first
822 <            for (Node e = first; e != null; e = e.next) {
823 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
819 >        final V getValue(int h, Object k) {
820 >            Class<?> cc = comparableClassFor(k.getClass());
821 >            Node<K,V> r = null;
822 >            for (Node<K,V> e = first; e != null; e = e.next) {
823 >                long s;
824 >                if ((s = tryReadLock()) != 0L) {
825                      try {
826 <                        r = getTreeNode(h, k, root);
826 >                        r = getTreeNode(h, k, root, cc);
827                      } finally {
828 <                        releaseShared(0);
828 >                        unlockRead(s);
829                      }
830                      break;
831                  }
832 <                else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
832 >                else if (e.hash == h && k.equals(e.key)) {
833                      r = e;
834                      break;
835                  }
891                else
892                    c = getState();
836              }
837              return r == null ? null : r.val;
838          }
# Line 898 | Line 841 | public class ConcurrentHashMap<K, V>
841           * Finds or adds a node.
842           * @return null if added
843           */
844 <        @SuppressWarnings("unchecked") final TreeNode putTreeNode
845 <            (int h, Object k, Object v) {
846 <            Class<?> c = k.getClass();
904 <            TreeNode pp = root, p = null;
844 >        final TreeNode<K,V> putTreeNode(int h, Object k, V v) {
845 >            Class<?> cc = comparableClassFor(k.getClass());
846 >            TreeNode<K,V> pp = root, p = null;
847              int dir = 0;
848              while (pp != null) { // find existing node or leaf to insert at
849 <                int ph;  Object pk; Class<?> pc;
849 >                int ph; Object pk; Class<?> pc;
850                  p = pp;
851 <                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
851 >                if ((ph = p.hash) != h)
852                      dir = (h < ph) ? -1 : 1;
853 +                else if ((pk = p.key) == k || k.equals(pk))
854 +                    return p;
855 +                else if (cc == null || pk == null ||
856 +                         ((pc = pk.getClass()) != cc &&
857 +                          comparableClassFor(pc) != cc) ||
858 +                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
859 +                    TreeNode<K,V> r, pr;
860 +                    if ((pr = p.right) != null &&
861 +                        (r = getTreeNode(h, k, pr, cc)) != null)
862 +                        return r;
863 +                    else // continue left
864 +                        dir = -1;
865 +                }
866                  pp = (dir > 0) ? p.right : p.left;
867              }
868  
869 <            TreeNode f = first;
870 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
869 >            TreeNode<K,V> f = first;
870 >            TreeNode<K,V> x = first = new TreeNode<K,V>(h, k, v, f, p);
871              if (p == null)
872                  root = x;
873              else { // attach and rebalance; adapted from CLR
937                TreeNode xp, xpp;
874                  if (f != null)
875                      f.prev = x;
876                  if (dir <= 0)
# Line 942 | Line 878 | public class ConcurrentHashMap<K, V>
878                  else
879                      p.right = x;
880                  x.red = true;
881 <                while (x != null && (xp = x.parent) != null && xp.red &&
882 <                       (xpp = xp.parent) != null) {
883 <                    TreeNode xppl = xpp.left;
884 <                    if (xp == xppl) {
885 <                        TreeNode y = xpp.right;
886 <                        if (y != null && y.red) {
887 <                            y.red = false;
881 >                for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
882 >                    if ((xp = x.parent) == null) {
883 >                        (root = x).red = false;
884 >                        break;
885 >                    }
886 >                    else if (!xp.red || (xpp = xp.parent) == null) {
887 >                        TreeNode<K,V> r = root;
888 >                        if (r != null && r.red)
889 >                            r.red = false;
890 >                        break;
891 >                    }
892 >                    else if ((xppl = xpp.left) == xp) {
893 >                        if ((xppr = xpp.right) != null && xppr.red) {
894 >                            xppr.red = false;
895                              xp.red = false;
896                              xpp.red = true;
897                              x = xpp;
# Line 968 | Line 911 | public class ConcurrentHashMap<K, V>
911                          }
912                      }
913                      else {
914 <                        TreeNode y = xppl;
915 <                        if (y != null && y.red) {
973 <                            y.red = false;
914 >                        if (xppl != null && xppl.red) {
915 >                            xppl.red = false;
916                              xp.red = false;
917                              xpp.red = true;
918                              x = xpp;
# Line 990 | Line 932 | public class ConcurrentHashMap<K, V>
932                          }
933                      }
934                  }
993                TreeNode r = root;
994                if (r != null && r.red)
995                    r.red = false;
935              }
936 +            assert checkInvariants();
937              return null;
938          }
939  
# Line 1005 | Line 945 | public class ConcurrentHashMap<K, V>
945           * that are accessible independently of lock. So instead we
946           * swap the tree linkages.
947           */
948 <        final void deleteTreeNode(TreeNode p) {
949 <            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
950 <            TreeNode pred = p.prev;
948 >        final void deleteTreeNode(TreeNode<K,V> p) {
949 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
950 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
951              if (pred == null)
952                  first = next;
953              else
954                  pred.next = next;
955              if (next != null)
956                  next.prev = pred;
957 <            TreeNode replacement;
958 <            TreeNode pl = p.left;
959 <            TreeNode pr = p.right;
957 >            else if (pred == null) {
958 >                root = null;
959 >                return;
960 >            }
961 >            TreeNode<K,V> replacement;
962 >            TreeNode<K,V> pl = p.left;
963 >            TreeNode<K,V> pr = p.right;
964              if (pl != null && pr != null) {
965 <                TreeNode s = pr, sl;
965 >                TreeNode<K,V> s = pr, sl;
966                  while ((sl = s.left) != null) // find successor
967                      s = sl;
968                  boolean c = s.red; s.red = p.red; p.red = c; // swap colors
969 <                TreeNode sr = s.right;
970 <                TreeNode pp = p.parent;
969 >                TreeNode<K,V> sr = s.right;
970 >                TreeNode<K,V> pp = p.parent;
971                  if (s == pr) { // p was s's direct parent
972                      p.parent = s;
973                      s.right = p;
974                  }
975                  else {
976 <                    TreeNode sp = s.parent;
976 >                    TreeNode<K,V> sp = s.parent;
977                      if ((p.parent = sp) != null) {
978                          if (s == sp.left)
979                              sp.left = p;
# Line 1050 | Line 994 | public class ConcurrentHashMap<K, V>
994                      pp.left = s;
995                  else
996                      pp.right = s;
997 <                replacement = sr;
997 >                if (sr != null)
998 >                    replacement = sr;
999 >                else
1000 >                    replacement = p;
1001              }
1002 +            else if (pl != null)
1003 +                replacement = pl;
1004 +            else if (pr != null)
1005 +                replacement = pr;
1006              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                }
1007                  replacement = p;
1008 <            }
1009 <            else {
1066 <                replacement.parent = pp;
1008 >            if (replacement != p) {
1009 >                TreeNode<K,V> pp = replacement.parent = p.parent;
1010                  if (pp == null)
1011                      root = replacement;
1012                  else if (p == pp.left)
# Line 1073 | Line 1016 | public class ConcurrentHashMap<K, V>
1016                  p.left = p.right = p.parent = null;
1017              }
1018              if (!p.red) { // rebalance, from CLR
1019 <                TreeNode x = replacement;
1020 <                while (x != null) {
1078 <                    TreeNode xp, xpl;
1019 >                for (TreeNode<K,V> x = replacement; x != null; ) {
1020 >                    TreeNode<K,V> xp, xpl, xpr;
1021                      if (x.red || (xp = x.parent) == null) {
1022                          x.red = false;
1023                          break;
1024                      }
1025 <                    if (x == (xpl = xp.left)) {
1026 <                        TreeNode sib = xp.right;
1027 <                        if (sib != null && sib.red) {
1086 <                            sib.red = false;
1025 >                    else if ((xpl = xp.left) == x) {
1026 >                        if ((xpr = xp.right) != null && xpr.red) {
1027 >                            xpr.red = false;
1028                              xp.red = true;
1029                              rotateLeft(xp);
1030 <                            sib = (xp = x.parent) == null ? null : xp.right;
1030 >                            xpr = (xp = x.parent) == null ? null : xp.right;
1031                          }
1032 <                        if (sib == null)
1032 >                        if (xpr == null)
1033                              x = xp;
1034                          else {
1035 <                            TreeNode sl = sib.left, sr = sib.right;
1035 >                            TreeNode<K,V> sl = xpr.left, sr = xpr.right;
1036                              if ((sr == null || !sr.red) &&
1037                                  (sl == null || !sl.red)) {
1038 <                                sib.red = true;
1038 >                                xpr.red = true;
1039                                  x = xp;
1040                              }
1041                              else {
1042                                  if (sr == null || !sr.red) {
1043                                      if (sl != null)
1044                                          sl.red = false;
1045 <                                    sib.red = true;
1046 <                                    rotateRight(sib);
1047 <                                    sib = (xp = x.parent) == null ? null : xp.right;
1045 >                                    xpr.red = true;
1046 >                                    rotateRight(xpr);
1047 >                                    xpr = (xp = x.parent) == null ?
1048 >                                        null : xp.right;
1049                                  }
1050 <                                if (sib != null) {
1051 <                                    sib.red = (xp == null) ? false : xp.red;
1052 <                                    if ((sr = sib.right) != null)
1050 >                                if (xpr != null) {
1051 >                                    xpr.red = (xp == null) ? false : xp.red;
1052 >                                    if ((sr = xpr.right) != null)
1053                                          sr.red = false;
1054                                  }
1055                                  if (xp != null) {
# Line 1119 | Line 1061 | public class ConcurrentHashMap<K, V>
1061                          }
1062                      }
1063                      else { // symmetric
1064 <                        TreeNode sib = xpl;
1065 <                        if (sib != null && sib.red) {
1124 <                            sib.red = false;
1064 >                        if (xpl != null && xpl.red) {
1065 >                            xpl.red = false;
1066                              xp.red = true;
1067                              rotateRight(xp);
1068 <                            sib = (xp = x.parent) == null ? null : xp.left;
1068 >                            xpl = (xp = x.parent) == null ? null : xp.left;
1069                          }
1070 <                        if (sib == null)
1070 >                        if (xpl == null)
1071                              x = xp;
1072                          else {
1073 <                            TreeNode sl = sib.left, sr = sib.right;
1073 >                            TreeNode<K,V> sl = xpl.left, sr = xpl.right;
1074                              if ((sl == null || !sl.red) &&
1075                                  (sr == null || !sr.red)) {
1076 <                                sib.red = true;
1076 >                                xpl.red = true;
1077                                  x = xp;
1078                              }
1079                              else {
1080                                  if (sl == null || !sl.red) {
1081                                      if (sr != null)
1082                                          sr.red = false;
1083 <                                    sib.red = true;
1084 <                                    rotateLeft(sib);
1085 <                                    sib = (xp = x.parent) == null ? null : xp.left;
1083 >                                    xpl.red = true;
1084 >                                    rotateLeft(xpl);
1085 >                                    xpl = (xp = x.parent) == null ?
1086 >                                        null : xp.left;
1087                                  }
1088 <                                if (sib != null) {
1089 <                                    sib.red = (xp == null) ? false : xp.red;
1090 <                                    if ((sl = sib.left) != null)
1088 >                                if (xpl != null) {
1089 >                                    xpl.red = (xp == null) ? false : xp.red;
1090 >                                    if ((sl = xpl.left) != null)
1091                                          sl.red = false;
1092                                  }
1093                                  if (xp != null) {
# Line 1158 | Line 1100 | public class ConcurrentHashMap<K, V>
1100                      }
1101                  }
1102              }
1103 <            if (p == replacement && (pp = p.parent) != null) {
1104 <                if (p == pp.left) // detach pointers
1105 <                    pp.left = null;
1106 <                else if (p == pp.right)
1107 <                    pp.right = null;
1108 <                p.parent = null;
1103 >            if (p == replacement) {  // detach pointers
1104 >                TreeNode<K,V> pp;
1105 >                if ((pp = p.parent) != null) {
1106 >                    if (p == pp.left)
1107 >                        pp.left = null;
1108 >                    else if (p == pp.right)
1109 >                        pp.right = null;
1110 >                    p.parent = null;
1111 >                }
1112              }
1113 +            assert checkInvariants();
1114 +        }
1115 +
1116 +        /**
1117 +         * Checks linkage and balance invariants at root
1118 +         */
1119 +        final boolean checkInvariants() {
1120 +            TreeNode<K,V> r = root;
1121 +            if (r == null)
1122 +                return (first == null);
1123 +            else
1124 +                return (first != null) && checkTreeNode(r);
1125 +        }
1126 +
1127 +        /**
1128 +         * Recursive invariant check
1129 +         */
1130 +        final boolean checkTreeNode(TreeNode<K,V> t) {
1131 +            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
1132 +                tb = t.prev, tn = (TreeNode<K,V>)t.next;
1133 +            if (tb != null && tb.next != t)
1134 +                return false;
1135 +            if (tn != null && tn.prev != t)
1136 +                return false;
1137 +            if (tp != null && t != tp.left && t != tp.right)
1138 +                return false;
1139 +            if (tl != null && (tl.parent != t || tl.hash > t.hash))
1140 +                return false;
1141 +            if (tr != null && (tr.parent != t || tr.hash < t.hash))
1142 +                return false;
1143 +            if (t.red && tl != null && tl.red && tr != null && tr.red)
1144 +                return false;
1145 +            if (tl != null && !checkTreeNode(tl))
1146 +                return false;
1147 +            if (tr != null && !checkTreeNode(tr))
1148 +                return false;
1149 +            return true;
1150          }
1151      }
1152  
1153      /* ---------------- Collision reduction methods -------------- */
1154  
1155      /**
1156 <     * Spreads higher bits to lower, and also forces top 2 bits to 0.
1156 >     * Spreads higher bits to lower, and also forces top bit to 0.
1157       * Because the table uses power-of-two masking, sets of hashes
1158       * that vary only in bits above the current mask will always
1159       * collide. (Among known examples are sets of Float keys holding
# Line 1189 | Line 1171 | public class ConcurrentHashMap<K, V>
1171      }
1172  
1173      /**
1174 <     * Replaces a list bin with a tree bin. Call only when locked.
1175 <     * Fails to replace if the given key is non-comparable or table
1176 <     * is, or needs, resizing.
1177 <     */
1178 <    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1179 <        if ((key instanceof Comparable) &&
1180 <            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
1181 <            TreeBin t = new TreeBin();
1182 <            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));
1174 >     * Replaces a list bin with a tree bin if key is comparable.  Call
1175 >     * only when locked.
1176 >     */
1177 >    private final void replaceWithTreeBin(Node<K,V>[] tab, int index, Object key) {
1178 >        if (tab != null && comparableClassFor(key.getClass()) != null) {
1179 >            TreeBin<K,V> t = new TreeBin<K,V>();
1180 >            for (Node<K,V> e = tabAt(tab, index); e != null; e = e.next)
1181 >                t.putTreeNode(e.hash, e.key, e.val);
1182 >            setTabAt(tab, index, new Node<K,V>(MOVED, t, null, null));
1183          }
1184      }
1185  
1186      /* ---------------- Internal access and update methods -------------- */
1187  
1188      /** Implementation for get and containsKey */
1189 <    private final Object internalGet(Object k) {
1189 >    private final V internalGet(Object k) {
1190          int h = spread(k.hashCode());
1191 <        retry: for (Node[] tab = table; tab != null;) {
1192 <            Node e, p; Object ek, ev; int eh;      // locals to read fields once
1193 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1194 <                if ((eh = e.hash) == MOVED) {
1195 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1196 <                        return ((TreeBin)ek).getValue(h, k);
1197 <                    else {                        // restart with new table
1198 <                        tab = (Node[])ek;
1199 <                        continue retry;
1200 <                    }
1201 <                }
1202 <                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1203 <                         ((ek = e.key) == k || k.equals(ek)))
1204 <                    return ev;
1191 >        V v = null;
1192 >        Node<K,V>[] tab; Node<K,V> e;
1193 >        if ((tab = table) != null &&
1194 >            (e = tabAt(tab, (tab.length - 1) & h)) != null) {
1195 >            for (;;) {
1196 >                int eh; Object ek;
1197 >                if ((eh = e.hash) < 0) {
1198 >                    if ((ek = e.key) instanceof TreeBin) { // search TreeBin
1199 >                        v = ((TreeBin<K,V>)ek).getValue(h, k);
1200 >                        break;
1201 >                    }
1202 >                    else if (!(ek instanceof Node[]) ||    // try new table
1203 >                             (e = tabAt(tab = (Node<K,V>[])ek,
1204 >                                        (tab.length - 1) & h)) == null)
1205 >                        break;
1206 >                }
1207 >                else if (eh == h && ((ek = e.key) == k || k.equals(ek))) {
1208 >                    v = e.val;
1209 >                    break;
1210 >                }
1211 >                else if ((e = e.next) == null)
1212 >                    break;
1213              }
1226            break;
1214          }
1215 <        return null;
1215 >        return v;
1216      }
1217  
1218      /**
# Line 1233 | Line 1220 | public class ConcurrentHashMap<K, V>
1220       * Replaces node value with v, conditional upon match of cv if
1221       * non-null.  If resulting value is null, delete.
1222       */
1223 <    private final Object internalReplace(Object k, Object v, Object cv) {
1223 >    private final V internalReplace(Object k, V v, Object cv) {
1224          int h = spread(k.hashCode());
1225 <        Object oldVal = null;
1226 <        for (Node[] tab = table;;) {
1227 <            Node f; int i, fh; Object fk;
1225 >        V oldVal = null;
1226 >        for (Node<K,V>[] tab = table;;) {
1227 >            Node<K,V> f; int i, fh; Object fk;
1228              if (tab == null ||
1229                  (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1230                  break;
1231 <            else if ((fh = f.hash) == MOVED) {
1231 >            else if ((fh = f.hash) < 0) {
1232                  if ((fk = f.key) instanceof TreeBin) {
1233 <                    TreeBin t = (TreeBin)fk;
1233 >                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1234 >                    long stamp = t.writeLock();
1235                      boolean validated = false;
1236                      boolean deleted = false;
1249                    t.acquire(0);
1237                      try {
1238                          if (tabAt(tab, i) == f) {
1239                              validated = true;
1240 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1240 >                            Class<?> cc = comparableClassFor(k.getClass());
1241 >                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
1242                              if (p != null) {
1243 <                                Object pv = p.val;
1243 >                                V pv = p.val;
1244                                  if (cv == null || cv == pv || cv.equals(pv)) {
1245                                      oldVal = pv;
1246 <                                    if ((p.val = v) == null) {
1246 >                                    if (v != null)
1247 >                                        p.val = v;
1248 >                                    else {
1249                                          deleted = true;
1250                                          t.deleteTreeNode(p);
1251                                      }
# Line 1263 | Line 1253 | public class ConcurrentHashMap<K, V>
1253                              }
1254                          }
1255                      } finally {
1256 <                        t.release(0);
1256 >                        t.unlockWrite(stamp);
1257                      }
1258                      if (validated) {
1259                          if (deleted)
1260 <                            counter.add(-1L);
1260 >                            addCount(-1L, -1);
1261                          break;
1262                      }
1263                  }
1264                  else
1265 <                    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);
1265 >                    tab = (Node<K,V>[])fk;
1266              }
1267 <            else if (f.casHash(fh, fh | LOCKED)) {
1267 >            else {
1268                  boolean validated = false;
1269                  boolean deleted = false;
1270 <                try {
1270 >                synchronized (f) {
1271                      if (tabAt(tab, i) == f) {
1272                          validated = true;
1273 <                        for (Node e = f, pred = null;;) {
1274 <                            Object ek, ev;
1275 <                            if ((e.hash & HASH_BITS) == h &&
1292 <                                ((ev = e.val) != null) &&
1273 >                        for (Node<K,V> e = f, pred = null;;) {
1274 >                            Object ek;
1275 >                            if (e.hash == h &&
1276                                  ((ek = e.key) == k || k.equals(ek))) {
1277 +                                V ev = e.val;
1278                                  if (cv == null || cv == ev || cv.equals(ev)) {
1279                                      oldVal = ev;
1280 <                                    if ((e.val = v) == null) {
1280 >                                    if (v != null)
1281 >                                        e.val = v;
1282 >                                    else {
1283                                          deleted = true;
1284 <                                        Node en = e.next;
1284 >                                        Node<K,V> en = e.next;
1285                                          if (pred != null)
1286                                              pred.next = en;
1287                                          else
# Line 1309 | Line 1295 | public class ConcurrentHashMap<K, V>
1295                                  break;
1296                          }
1297                      }
1312                } finally {
1313                    if (!f.casHash(fh | LOCKED, fh)) {
1314                        f.hash = fh;
1315                        synchronized (f) { f.notifyAll(); };
1316                    }
1298                  }
1299                  if (validated) {
1300                      if (deleted)
1301 <                        counter.add(-1L);
1301 >                        addCount(-1L, -1);
1302                      break;
1303                  }
1304              }
# Line 1326 | Line 1307 | public class ConcurrentHashMap<K, V>
1307      }
1308  
1309      /*
1310 <     * Internal versions of the six insertion methods, each a
1311 <     * little more complicated than the last. All have
1331 <     * the same basic structure as the first (internalPut):
1310 >     * Internal versions of insertion methods
1311 >     * All have the same basic structure as the first (internalPut):
1312       *  1. If table uninitialized, create
1313       *  2. If bin empty, try to CAS new node
1314       *  3. If bin stale, use new table
1315       *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1316       *  5. Lock and validate; if valid, scan and add or update
1317       *
1318 <     * The others interweave other checks and/or alternative actions:
1319 <     *  * Plain put checks for and performs resize after insertion.
1320 <     *  * putIfAbsent prescans for mapping without lock (and fails to add
1321 <     *    if present), which also makes pre-emptive resize checks worthwhile.
1322 <     *  * computeIfAbsent extends form used in putIfAbsent with additional
1323 <     *    mechanics to deal with, calls, potential exceptions and null
1324 <     *    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.
1318 >     * The putAll method differs mainly in attempting to pre-allocate
1319 >     * enough table space, and also more lazily performs count updates
1320 >     * and checks.
1321 >     *
1322 >     * Most of the function-accepting methods can't be factored nicely
1323 >     * because they require different functional forms, so instead
1324 >     * sprawl out similar mechanics.
1325       */
1326  
1327 <    /** Implementation for put */
1328 <    private final Object internalPut(Object k, Object v) {
1327 >    /** Implementation for put and putIfAbsent */
1328 >    private final V internalPut(K k, V v, boolean onlyIfAbsent) {
1329 >        if (k == null || v == null) throw new NullPointerException();
1330          int h = spread(k.hashCode());
1331 <        int count = 0;
1332 <        for (Node[] tab = table;;) {
1333 <            int i; Node f; int fh; Object fk;
1331 >        int len = 0;
1332 >        for (Node<K,V>[] tab = table;;) {
1333 >            int i, fh; Node<K,V> f; Object fk;
1334              if (tab == null)
1335                  tab = initTable();
1336              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1337 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1337 >                if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null)))
1338                      break;                   // no lock when adding to empty bin
1339              }
1340 <            else if ((fh = f.hash) == MOVED) {
1340 >            else if ((fh = f.hash) < 0) {
1341                  if ((fk = f.key) instanceof TreeBin) {
1342 <                    TreeBin t = (TreeBin)fk;
1343 <                    Object oldVal = null;
1344 <                    t.acquire(0);
1342 >                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1343 >                    long stamp = t.writeLock();
1344 >                    V oldVal = null;
1345                      try {
1346                          if (tabAt(tab, i) == f) {
1347 <                            count = 2;
1348 <                            TreeNode p = t.putTreeNode(h, k, v);
1347 >                            len = 2;
1348 >                            TreeNode<K,V> p = t.putTreeNode(h, k, v);
1349                              if (p != null) {
1350                                  oldVal = p.val;
1351 <                                p.val = v;
1351 >                                if (!onlyIfAbsent)
1352 >                                    p.val = v;
1353                              }
1354                          }
1355                      } finally {
1356 <                        t.release(0);
1356 >                        t.unlockWrite(stamp);
1357                      }
1358 <                    if (count != 0) {
1358 >                    if (len != 0) {
1359                          if (oldVal != null)
1360                              return oldVal;
1361                          break;
1362                      }
1363                  }
1364                  else
1365 <                    tab = (Node[])fk;
1365 >                    tab = (Node<K,V>[])fk;
1366              }
1367 <            else if ((fh & LOCKED) != 0) {
1368 <                checkForResize();
1369 <                f.tryAwaitLock(tab, i);
1397 <            }
1398 <            else if (f.casHash(fh, fh | LOCKED)) {
1399 <                Object oldVal = null;
1400 <                try {                        // needed in case equals() throws
1367 >            else {
1368 >                V oldVal = null;
1369 >                synchronized (f) {
1370                      if (tabAt(tab, i) == f) {
1371 <                        count = 1;
1372 <                        for (Node e = f;; ++count) {
1373 <                            Object ek, ev;
1374 <                            if ((e.hash & HASH_BITS) == h &&
1406 <                                (ev = e.val) != null &&
1371 >                        len = 1;
1372 >                        for (Node<K,V> e = f;; ++len) {
1373 >                            Object ek;
1374 >                            if (e.hash == h &&
1375                                  ((ek = e.key) == k || k.equals(ek))) {
1376 <                                oldVal = ev;
1377 <                                e.val = v;
1376 >                                oldVal = e.val;
1377 >                                if (!onlyIfAbsent)
1378 >                                    e.val = v;
1379                                  break;
1380                              }
1381 <                            Node last = e;
1381 >                            Node<K,V> last = e;
1382                              if ((e = e.next) == null) {
1383 <                                last.next = new Node(h, k, v, null);
1384 <                                if (count >= TREE_THRESHOLD)
1383 >                                last.next = new Node<K,V>(h, k, v, null);
1384 >                                if (len > TREE_THRESHOLD)
1385                                      replaceWithTreeBin(tab, i, k);
1386                                  break;
1387                              }
1388                          }
1389                      }
1421                } finally {                  // unlock and signal if needed
1422                    if (!f.casHash(fh | LOCKED, fh)) {
1423                        f.hash = fh;
1424                        synchronized (f) { f.notifyAll(); };
1425                    }
1390                  }
1391 <                if (count != 0) {
1391 >                if (len != 0) {
1392                      if (oldVal != null)
1393                          return oldVal;
1430                    if (tab.length <= 64)
1431                        count = 2;
1394                      break;
1395                  }
1396              }
1397          }
1398 <        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();
1398 >        addCount(1L, len);
1399          return null;
1400      }
1401  
1402      /** Implementation for computeIfAbsent */
1403 <    private final Object internalComputeIfAbsent(K k,
1404 <                                                 Fun<? super K, ?> mf) {
1403 >    private final V internalComputeIfAbsent(K k, Function<? super K, ? extends V> mf) {
1404 >        if (k == null || mf == null)
1405 >            throw new NullPointerException();
1406          int h = spread(k.hashCode());
1407 <        Object val = null;
1408 <        int count = 0;
1409 <        for (Node[] tab = table;;) {
1410 <            Node f; int i, fh; Object fk, fv;
1407 >        V val = null;
1408 >        int len = 0;
1409 >        for (Node<K,V>[] tab = table;;) {
1410 >            Node<K,V> f; int i; Object fk;
1411              if (tab == null)
1412                  tab = initTable();
1413              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1414 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1415 <                if (casTabAt(tab, i, null, node)) {
1416 <                    count = 1;
1417 <                    try {
1418 <                        if ((val = mf.apply(k)) != null)
1419 <                            node.val = val;
1420 <                    } finally {
1421 <                        if (val == null)
1422 <                            setTabAt(tab, i, null);
1423 <                        if (!node.casHash(fh, h)) {
1564 <                            node.hash = h;
1565 <                            synchronized (node) { node.notifyAll(); };
1414 >                Node<K,V> node = new Node<K,V>(h, k, null, null);
1415 >                synchronized (node) {
1416 >                    if (casTabAt(tab, i, null, node)) {
1417 >                        len = 1;
1418 >                        try {
1419 >                            if ((val = mf.apply(k)) != null)
1420 >                                node.val = val;
1421 >                        } finally {
1422 >                            if (val == null)
1423 >                                setTabAt(tab, i, null);
1424                          }
1425                      }
1426                  }
1427 <                if (count != 0)
1427 >                if (len != 0)
1428                      break;
1429              }
1430 <            else if ((fh = f.hash) == MOVED) {
1430 >            else if (f.hash < 0) {
1431                  if ((fk = f.key) instanceof TreeBin) {
1432 <                    TreeBin t = (TreeBin)fk;
1432 >                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1433 >                    long stamp = t.writeLock();
1434                      boolean added = false;
1576                    t.acquire(0);
1435                      try {
1436                          if (tabAt(tab, i) == f) {
1437 <                            count = 1;
1438 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1437 >                            len = 2;
1438 >                            Class<?> cc = comparableClassFor(k.getClass());
1439 >                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
1440                              if (p != null)
1441                                  val = p.val;
1442                              else if ((val = mf.apply(k)) != null) {
1443                                  added = true;
1585                                count = 2;
1444                                  t.putTreeNode(h, k, val);
1445                              }
1446                          }
1447                      } finally {
1448 <                        t.release(0);
1448 >                        t.unlockWrite(stamp);
1449                      }
1450 <                    if (count != 0) {
1450 >                    if (len != 0) {
1451                          if (!added)
1452                              return val;
1453                          break;
1454                      }
1455                  }
1456                  else
1457 <                    tab = (Node[])fk;
1457 >                    tab = (Node<K,V>[])fk;
1458              }
1601            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1602                     ((fk = f.key) == k || k.equals(fk)))
1603                return fv;
1459              else {
1460 <                Node g = f.next;
1461 <                if (g != null) {
1462 <                    for (Node e = g;;) {
1463 <                        Object ek, ev;
1464 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1465 <                            ((ek = e.key) == k || k.equals(ek)))
1466 <                            return ev;
1467 <                        if ((e = e.next) == null) {
1468 <                            checkForResize();
1469 <                            break;
1470 <                        }
1471 <                    }
1472 <                }
1473 <                if (((fh = f.hash) & LOCKED) != 0) {
1474 <                    checkForResize();
1475 <                    f.tryAwaitLock(tab, i);
1476 <                }
1477 <                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;
1460 >                boolean added = false;
1461 >                synchronized (f) {
1462 >                    if (tabAt(tab, i) == f) {
1463 >                        len = 1;
1464 >                        for (Node<K,V> e = f;; ++len) {
1465 >                            Object ek; V ev;
1466 >                            if (e.hash == h &&
1467 >                                ((ek = e.key) == k || k.equals(ek))) {
1468 >                                val = e.val;
1469 >                                break;
1470 >                            }
1471 >                            Node<K,V> last = e;
1472 >                            if ((e = e.next) == null) {
1473 >                                if ((val = mf.apply(k)) != null) {
1474 >                                    added = true;
1475 >                                    last.next = new Node<K,V>(h, k, val, null);
1476 >                                    if (len > TREE_THRESHOLD)
1477 >                                        replaceWithTreeBin(tab, i, k);
1478                                  }
1479 +                                break;
1480                              }
1481                          }
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;
1482                      }
1483                  }
1484 +                if (len != 0) {
1485 +                    if (!added)
1486 +                        return val;
1487 +                    break;
1488 +                }
1489              }
1490          }
1491 <        if (val != null) {
1492 <            counter.add(1L);
1665 <            if (count > 1)
1666 <                checkForResize();
1667 <        }
1491 >        if (val != null)
1492 >            addCount(1L, len);
1493          return val;
1494      }
1495  
1496      /** Implementation for compute */
1497 <    @SuppressWarnings("unchecked") private final Object internalCompute
1498 <        (K k, boolean onlyIfPresent, BiFun<? super K, ? super V, ? extends V> mf) {
1497 >    private final V internalCompute(K k, boolean onlyIfPresent,
1498 >                                    BiFunction<? super K, ? super V, ? extends V> mf) {
1499 >        if (k == null || mf == null)
1500 >            throw new NullPointerException();
1501          int h = spread(k.hashCode());
1502 <        Object val = null;
1502 >        V val = null;
1503          int delta = 0;
1504 <        int count = 0;
1505 <        for (Node[] tab = table;;) {
1506 <            Node f; int i, fh; Object fk;
1504 >        int len = 0;
1505 >        for (Node<K,V>[] tab = table;;) {
1506 >            Node<K,V> f; int i, fh; Object fk;
1507              if (tab == null)
1508                  tab = initTable();
1509              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1510                  if (onlyIfPresent)
1511                      break;
1512 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1513 <                if (casTabAt(tab, i, null, node)) {
1514 <                    try {
1515 <                        count = 1;
1516 <                        if ((val = mf.apply(k, null)) != null) {
1517 <                            node.val = val;
1518 <                            delta = 1;
1519 <                        }
1520 <                    } finally {
1521 <                        if (delta == 0)
1522 <                            setTabAt(tab, i, null);
1523 <                        if (!node.casHash(fh, h)) {
1697 <                            node.hash = h;
1698 <                            synchronized (node) { node.notifyAll(); };
1512 >                Node<K,V> node = new Node<K,V>(h, k, null, null);
1513 >                synchronized (node) {
1514 >                    if (casTabAt(tab, i, null, node)) {
1515 >                        try {
1516 >                            len = 1;
1517 >                            if ((val = mf.apply(k, null)) != null) {
1518 >                                node.val = val;
1519 >                                delta = 1;
1520 >                            }
1521 >                        } finally {
1522 >                            if (delta == 0)
1523 >                                setTabAt(tab, i, null);
1524                          }
1525                      }
1526                  }
1527 <                if (count != 0)
1527 >                if (len != 0)
1528                      break;
1529              }
1530 <            else if ((fh = f.hash) == MOVED) {
1530 >            else if ((fh = f.hash) < 0) {
1531                  if ((fk = f.key) instanceof TreeBin) {
1532 <                    TreeBin t = (TreeBin)fk;
1533 <                    t.acquire(0);
1532 >                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1533 >                    long stamp = t.writeLock();
1534                      try {
1535                          if (tabAt(tab, i) == f) {
1536 <                            count = 1;
1537 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1538 <                            Object pv = (p == null) ? null : p.val;
1539 <                            if ((val = mf.apply(k, (V)pv)) != null) {
1540 <                                if (p != null)
1541 <                                    p.val = val;
1542 <                                else {
1543 <                                    count = 2;
1544 <                                    delta = 1;
1545 <                                    t.putTreeNode(h, k, val);
1536 >                            len = 2;
1537 >                            Class<?> cc = comparableClassFor(k.getClass());
1538 >                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
1539 >                            if (p != null || !onlyIfPresent) {
1540 >                                V pv = (p == null) ? null : p.val;
1541 >                                if ((val = mf.apply(k, pv)) != null) {
1542 >                                    if (p != null)
1543 >                                        p.val = val;
1544 >                                    else {
1545 >                                        delta = 1;
1546 >                                        t.putTreeNode(h, k, val);
1547 >                                    }
1548 >                                }
1549 >                                else if (p != null) {
1550 >                                    delta = -1;
1551 >                                    t.deleteTreeNode(p);
1552                                  }
1722                            }
1723                            else if (p != null) {
1724                                delta = -1;
1725                                t.deleteTreeNode(p);
1553                              }
1554                          }
1555                      } finally {
1556 <                        t.release(0);
1556 >                        t.unlockWrite(stamp);
1557                      }
1558 <                    if (count != 0)
1558 >                    if (len != 0)
1559                          break;
1560                  }
1561                  else
1562 <                    tab = (Node[])fk;
1736 <            }
1737 <            else if ((fh & LOCKED) != 0) {
1738 <                checkForResize();
1739 <                f.tryAwaitLock(tab, i);
1562 >                    tab = (Node<K,V>[])fk;
1563              }
1564 <            else if (f.casHash(fh, fh | LOCKED)) {
1565 <                try {
1564 >            else {
1565 >                synchronized (f) {
1566                      if (tabAt(tab, i) == f) {
1567 <                        count = 1;
1568 <                        for (Node e = f, pred = null;; ++count) {
1569 <                            Object ek, ev;
1570 <                            if ((e.hash & HASH_BITS) == h &&
1748 <                                (ev = e.val) != null &&
1567 >                        len = 1;
1568 >                        for (Node<K,V> e = f, pred = null;; ++len) {
1569 >                            Object ek;
1570 >                            if (e.hash == h &&
1571                                  ((ek = e.key) == k || k.equals(ek))) {
1572 <                                val = mf.apply(k, (V)ev);
1572 >                                val = mf.apply(k, e.val);
1573                                  if (val != null)
1574                                      e.val = val;
1575                                  else {
1576                                      delta = -1;
1577 <                                    Node en = e.next;
1577 >                                    Node<K,V> en = e.next;
1578                                      if (pred != null)
1579                                          pred.next = en;
1580                                      else
# Line 1762 | Line 1584 | public class ConcurrentHashMap<K, V>
1584                              }
1585                              pred = e;
1586                              if ((e = e.next) == null) {
1587 <                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1588 <                                    pred.next = new Node(h, k, val, null);
1587 >                                if (!onlyIfPresent &&
1588 >                                    (val = mf.apply(k, null)) != null) {
1589 >                                    pred.next = new Node<K,V>(h, k, val, null);
1590                                      delta = 1;
1591 <                                    if (count >= TREE_THRESHOLD)
1591 >                                    if (len > TREE_THRESHOLD)
1592                                          replaceWithTreeBin(tab, i, k);
1593                                  }
1594                                  break;
1595                              }
1596                          }
1597                      }
1775                } finally {
1776                    if (!f.casHash(fh | LOCKED, fh)) {
1777                        f.hash = fh;
1778                        synchronized (f) { f.notifyAll(); };
1779                    }
1598                  }
1599 <                if (count != 0) {
1782 <                    if (tab.length <= 64)
1783 <                        count = 2;
1599 >                if (len != 0)
1600                      break;
1785                }
1601              }
1602          }
1603 <        if (delta != 0) {
1604 <            counter.add((long)delta);
1790 <            if (count > 1)
1791 <                checkForResize();
1792 <        }
1603 >        if (delta != 0)
1604 >            addCount((long)delta, len);
1605          return val;
1606      }
1607  
1608      /** Implementation for merge */
1609 <    @SuppressWarnings("unchecked") private final Object internalMerge
1610 <        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1609 >    private final V internalMerge(K k, V v,
1610 >                                  BiFunction<? super V, ? super V, ? extends V> mf) {
1611 >        if (k == null || v == null || mf == null)
1612 >            throw new NullPointerException();
1613          int h = spread(k.hashCode());
1614 <        Object val = null;
1614 >        V val = null;
1615          int delta = 0;
1616 <        int count = 0;
1617 <        for (Node[] tab = table;;) {
1618 <            int i; Node f; int fh; Object fk, fv;
1616 >        int len = 0;
1617 >        for (Node<K,V>[] tab = table;;) {
1618 >            int i; Node<K,V> f; Object fk;
1619              if (tab == null)
1620                  tab = initTable();
1621              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1622 <                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1622 >                if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null))) {
1623                      delta = 1;
1624                      val = v;
1625                      break;
1626                  }
1627              }
1628 <            else if ((fh = f.hash) == MOVED) {
1628 >            else if (f.hash < 0) {
1629                  if ((fk = f.key) instanceof TreeBin) {
1630 <                    TreeBin t = (TreeBin)fk;
1631 <                    t.acquire(0);
1630 >                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1631 >                    long stamp = t.writeLock();
1632                      try {
1633                          if (tabAt(tab, i) == f) {
1634 <                            count = 1;
1635 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1636 <                            val = (p == null) ? v : mf.apply((V)p.val, v);
1634 >                            len = 2;
1635 >                            Class<?> cc = comparableClassFor(k.getClass());
1636 >                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
1637 >                            val = (p == null) ? v : mf.apply(p.val, v);
1638                              if (val != null) {
1639                                  if (p != null)
1640                                      p.val = val;
1641                                  else {
1827                                    count = 2;
1642                                      delta = 1;
1643                                      t.putTreeNode(h, k, val);
1644                                  }
# Line 1835 | Line 1649 | public class ConcurrentHashMap<K, V>
1649                              }
1650                          }
1651                      } finally {
1652 <                        t.release(0);
1652 >                        t.unlockWrite(stamp);
1653                      }
1654 <                    if (count != 0)
1654 >                    if (len != 0)
1655                          break;
1656                  }
1657                  else
1658 <                    tab = (Node[])fk;
1658 >                    tab = (Node<K,V>[])fk;
1659              }
1660 <            else if ((fh & LOCKED) != 0) {
1661 <                checkForResize();
1848 <                f.tryAwaitLock(tab, i);
1849 <            }
1850 <            else if (f.casHash(fh, fh | LOCKED)) {
1851 <                try {
1660 >            else {
1661 >                synchronized (f) {
1662                      if (tabAt(tab, i) == f) {
1663 <                        count = 1;
1664 <                        for (Node e = f, pred = null;; ++count) {
1665 <                            Object ek, ev;
1666 <                            if ((e.hash & HASH_BITS) == h &&
1857 <                                (ev = e.val) != null &&
1663 >                        len = 1;
1664 >                        for (Node<K,V> e = f, pred = null;; ++len) {
1665 >                            Object ek;
1666 >                            if (e.hash == h &&
1667                                  ((ek = e.key) == k || k.equals(ek))) {
1668 <                                val = mf.apply(v, (V)ev);
1668 >                                val = mf.apply(e.val, v);
1669                                  if (val != null)
1670                                      e.val = val;
1671                                  else {
1672                                      delta = -1;
1673 <                                    Node en = e.next;
1673 >                                    Node<K,V> en = e.next;
1674                                      if (pred != null)
1675                                          pred.next = en;
1676                                      else
# Line 1871 | Line 1680 | public class ConcurrentHashMap<K, V>
1680                              }
1681                              pred = e;
1682                              if ((e = e.next) == null) {
1874                                val = v;
1875                                pred.next = new Node(h, k, val, null);
1683                                  delta = 1;
1684 <                                if (count >= TREE_THRESHOLD)
1684 >                                val = v;
1685 >                                pred.next = new Node<K,V>(h, k, val, null);
1686 >                                if (len > TREE_THRESHOLD)
1687                                      replaceWithTreeBin(tab, i, k);
1688                                  break;
1689                              }
1690                          }
1691                      }
1883                } finally {
1884                    if (!f.casHash(fh | LOCKED, fh)) {
1885                        f.hash = fh;
1886                        synchronized (f) { f.notifyAll(); };
1887                    }
1692                  }
1693 <                if (count != 0) {
1890 <                    if (tab.length <= 64)
1891 <                        count = 2;
1693 >                if (len != 0)
1694                      break;
1893                }
1695              }
1696          }
1697 <        if (delta != 0) {
1698 <            counter.add((long)delta);
1898 <            if (count > 1)
1899 <                checkForResize();
1900 <        }
1697 >        if (delta != 0)
1698 >            addCount((long)delta, len);
1699          return val;
1700      }
1701  
1702      /** Implementation for putAll */
1703 <    private final void internalPutAll(Map<?, ?> m) {
1703 >    private final void internalPutAll(Map<? extends K, ? extends V> m) {
1704          tryPresize(m.size());
1705          long delta = 0L;     // number of uncommitted additions
1706          boolean npe = false; // to throw exception on exit for nulls
1707          try {                // to clean up counts on other exceptions
1708 <            for (Map.Entry<?, ?> entry : m.entrySet()) {
1709 <                Object k, v;
1708 >            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
1709 >                Object k; V v;
1710                  if (entry == null || (k = entry.getKey()) == null ||
1711                      (v = entry.getValue()) == null) {
1712                      npe = true;
1713                      break;
1714                  }
1715                  int h = spread(k.hashCode());
1716 <                for (Node[] tab = table;;) {
1717 <                    int i; Node f; int fh; Object fk;
1716 >                for (Node<K,V>[] tab = table;;) {
1717 >                    int i; Node<K,V> f; int fh; Object fk;
1718                      if (tab == null)
1719                          tab = initTable();
1720                      else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1721 <                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1721 >                        if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null))) {
1722                              ++delta;
1723                              break;
1724                          }
1725                      }
1726 <                    else if ((fh = f.hash) == MOVED) {
1726 >                    else if ((fh = f.hash) < 0) {
1727                          if ((fk = f.key) instanceof TreeBin) {
1728 <                            TreeBin t = (TreeBin)fk;
1728 >                            TreeBin<K,V> t = (TreeBin<K,V>)fk;
1729 >                            long stamp = t.writeLock();
1730                              boolean validated = false;
1932                            t.acquire(0);
1731                              try {
1732                                  if (tabAt(tab, i) == f) {
1733                                      validated = true;
1734 <                                    TreeNode p = t.getTreeNode(h, k, t.root);
1734 >                                    Class<?> cc = comparableClassFor(k.getClass());
1735 >                                    TreeNode<K,V> p = t.getTreeNode(h, k,
1736 >                                                                    t.root, cc);
1737                                      if (p != null)
1738                                          p.val = v;
1739                                      else {
1940                                        t.putTreeNode(h, k, v);
1740                                          ++delta;
1741 +                                        t.putTreeNode(h, k, v);
1742                                      }
1743                                  }
1744                              } finally {
1745 <                                t.release(0);
1745 >                                t.unlockWrite(stamp);
1746                              }
1747                              if (validated)
1748                                  break;
1749                          }
1750                          else
1751 <                            tab = (Node[])fk;
1952 <                    }
1953 <                    else if ((fh & LOCKED) != 0) {
1954 <                        counter.add(delta);
1955 <                        delta = 0L;
1956 <                        checkForResize();
1957 <                        f.tryAwaitLock(tab, i);
1751 >                            tab = (Node<K,V>[])fk;
1752                      }
1753 <                    else if (f.casHash(fh, fh | LOCKED)) {
1754 <                        int count = 0;
1755 <                        try {
1753 >                    else {
1754 >                        int len = 0;
1755 >                        synchronized (f) {
1756                              if (tabAt(tab, i) == f) {
1757 <                                count = 1;
1758 <                                for (Node e = f;; ++count) {
1759 <                                    Object ek, ev;
1760 <                                    if ((e.hash & HASH_BITS) == h &&
1967 <                                        (ev = e.val) != null &&
1757 >                                len = 1;
1758 >                                for (Node<K,V> e = f;; ++len) {
1759 >                                    Object ek;
1760 >                                    if (e.hash == h &&
1761                                          ((ek = e.key) == k || k.equals(ek))) {
1762                                          e.val = v;
1763                                          break;
1764                                      }
1765 <                                    Node last = e;
1765 >                                    Node<K,V> last = e;
1766                                      if ((e = e.next) == null) {
1767                                          ++delta;
1768 <                                        last.next = new Node(h, k, v, null);
1769 <                                        if (count >= TREE_THRESHOLD)
1768 >                                        last.next = new Node<K,V>(h, k, v, null);
1769 >                                        if (len > TREE_THRESHOLD)
1770                                              replaceWithTreeBin(tab, i, k);
1771                                          break;
1772                                      }
1773                                  }
1774                              }
1982                        } finally {
1983                            if (!f.casHash(fh | LOCKED, fh)) {
1984                                f.hash = fh;
1985                                synchronized (f) { f.notifyAll(); };
1986                            }
1775                          }
1776 <                        if (count != 0) {
1777 <                            if (count > 1) {
1778 <                                counter.add(delta);
1776 >                        if (len != 0) {
1777 >                            if (len > 1) {
1778 >                                addCount(delta, len);
1779                                  delta = 0L;
1992                                checkForResize();
1780                              }
1781                              break;
1782                          }
# Line 1997 | Line 1784 | public class ConcurrentHashMap<K, V>
1784                  }
1785              }
1786          } finally {
1787 <            if (delta != 0)
1788 <                counter.add(delta);
1787 >            if (delta != 0L)
1788 >                addCount(delta, 2);
1789          }
1790          if (npe)
1791              throw new NullPointerException();
1792      }
1793  
1794 +    /**
1795 +     * Implementation for clear. Steps through each bin, removing all
1796 +     * nodes.
1797 +     */
1798 +    private final void internalClear() {
1799 +        long delta = 0L; // negative number of deletions
1800 +        int i = 0;
1801 +        Node<K,V>[] tab = table;
1802 +        while (tab != null && i < tab.length) {
1803 +            Node<K,V> f = tabAt(tab, i);
1804 +            if (f == null)
1805 +                ++i;
1806 +            else if (f.hash < 0) {
1807 +                Object fk;
1808 +                if ((fk = f.key) instanceof TreeBin) {
1809 +                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
1810 +                    long stamp = t.writeLock();
1811 +                    try {
1812 +                        if (tabAt(tab, i) == f) {
1813 +                            for (Node<K,V> p = t.first; p != null; p = p.next)
1814 +                                --delta;
1815 +                            t.first = null;
1816 +                            t.root = null;
1817 +                            ++i;
1818 +                        }
1819 +                    } finally {
1820 +                        t.unlockWrite(stamp);
1821 +                    }
1822 +                }
1823 +                else
1824 +                    tab = (Node<K,V>[])fk;
1825 +            }
1826 +            else {
1827 +                synchronized (f) {
1828 +                    if (tabAt(tab, i) == f) {
1829 +                        for (Node<K,V> e = f; e != null; e = e.next)
1830 +                            --delta;
1831 +                        setTabAt(tab, i, null);
1832 +                        ++i;
1833 +                    }
1834 +                }
1835 +            }
1836 +        }
1837 +        if (delta != 0L)
1838 +            addCount(delta, -1);
1839 +    }
1840 +
1841      /* ---------------- Table Initialization and Resizing -------------- */
1842  
1843      /**
# Line 2023 | Line 1857 | public class ConcurrentHashMap<K, V>
1857      /**
1858       * Initializes table, using the size recorded in sizeCtl.
1859       */
1860 <    private final Node[] initTable() {
1861 <        Node[] tab; int sc;
1860 >    private final Node<K,V>[] initTable() {
1861 >        Node<K,V>[] tab; int sc;
1862          while ((tab = table) == null) {
1863              if ((sc = sizeCtl) < 0)
1864                  Thread.yield(); // lost initialization race; just spin
1865 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1865 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1866                  try {
1867                      if ((tab = table) == null) {
1868                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1869 <                        tab = table = new Node[n];
1869 >                        table = tab = (Node<K,V>[])new Node[n];
1870                          sc = n - (n >>> 2);
1871                      }
1872                  } finally {
# Line 2045 | Line 1879 | public class ConcurrentHashMap<K, V>
1879      }
1880  
1881      /**
1882 <     * If table is too small and not already resizing, creates next
1883 <     * table and transfers bins.  Rechecks occupancy after a transfer
1884 <     * to see if another resize is already needed because resizings
1885 <     * are lagging additions.
1886 <     */
1887 <    private final void checkForResize() {
1888 <        Node[] tab; int n, sc;
1889 <        while ((tab = table) != null &&
1890 <               (n = tab.length) < MAXIMUM_CAPACITY &&
1891 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1892 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1893 <            try {
1894 <                if (tab == table) {
1895 <                    table = rebuild(tab);
1896 <                    sc = (n << 1) - (n >>> 1);
1882 >     * Adds to count, and if table is too small and not already
1883 >     * resizing, initiates transfer. If already resizing, helps
1884 >     * perform transfer if work is available.  Rechecks occupancy
1885 >     * after a transfer to see if another resize is already needed
1886 >     * because resizings are lagging additions.
1887 >     *
1888 >     * @param x the count to add
1889 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
1890 >     */
1891 >    private final void addCount(long x, int check) {
1892 >        Cell[] as; long b, s;
1893 >        if ((as = counterCells) != null ||
1894 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
1895 >            Cell a; long v; int m;
1896 >            boolean uncontended = true;
1897 >            if (as == null || (m = as.length - 1) < 0 ||
1898 >                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
1899 >                !(uncontended =
1900 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
1901 >                fullAddCount(x, uncontended);
1902 >                return;
1903 >            }
1904 >            if (check <= 1)
1905 >                return;
1906 >            s = sumCount();
1907 >        }
1908 >        if (check >= 0) {
1909 >            Node<K,V>[] tab, nt; int sc;
1910 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
1911 >                   tab.length < MAXIMUM_CAPACITY) {
1912 >                if (sc < 0) {
1913 >                    if (sc == -1 || transferIndex <= transferOrigin ||
1914 >                        (nt = nextTable) == null)
1915 >                        break;
1916 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
1917 >                        transfer(tab, nt);
1918                  }
1919 <            } finally {
1920 <                sizeCtl = sc;
1919 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
1920 >                    transfer(tab, null);
1921 >                s = sumCount();
1922              }
1923          }
1924      }
# Line 2077 | Line 1933 | public class ConcurrentHashMap<K, V>
1933              tableSizeFor(size + (size >>> 1) + 1);
1934          int sc;
1935          while ((sc = sizeCtl) >= 0) {
1936 <            Node[] tab = table; int n;
1936 >            Node<K,V>[] tab = table; int n;
1937              if (tab == null || (n = tab.length) == 0) {
1938                  n = (sc > c) ? sc : c;
1939 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1939 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1940                      try {
1941                          if (table == tab) {
1942 <                            table = new Node[n];
1942 >                            table = (Node<K,V>[])new Node[n];
1943                              sc = n - (n >>> 2);
1944                          }
1945                      } finally {
# Line 2093 | Line 1949 | public class ConcurrentHashMap<K, V>
1949              }
1950              else if (c <= sc || n >= MAXIMUM_CAPACITY)
1951                  break;
1952 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1953 <                try {
1954 <                    if (table == tab) {
2099 <                        table = rebuild(tab);
2100 <                        sc = (n << 1) - (n >>> 1);
2101 <                    }
2102 <                } finally {
2103 <                    sizeCtl = sc;
2104 <                }
2105 <            }
1952 >            else if (tab == table &&
1953 >                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
1954 >                transfer(tab, null);
1955          }
1956      }
1957  
1958 <    /*
1958 >    /**
1959       * Moves and/or copies the nodes in each bin to new table. See
1960       * above for explanation.
2112     *
2113     * @return the new table
1961       */
1962 <    private static final Node[] rebuild(Node[] tab) {
1963 <        int n = tab.length;
1964 <        Node[] nextTab = new Node[n << 1];
1965 <        Node fwd = new Node(MOVED, nextTab, null, null);
1966 <        int[] buffer = null;       // holds bins to revisit; null until needed
1967 <        Node rev = null;           // reverse forwarder; null until needed
1968 <        int nbuffered = 0;         // the number of bins in buffer list
1969 <        int bufferIndex = 0;       // buffer index of current buffered bin
1970 <        int bin = n - 1;           // current non-buffered bin or -1 if none
1971 <
1972 <        for (int i = bin;;) {      // start upwards sweep
1973 <            int fh; Node f;
1974 <            if ((f = tabAt(tab, i)) == null) {
1975 <                if (bin >= 0) {    // Unbuffered; no lock needed (or available)
1976 <                    if (!casTabAt(tab, i, f, fwd))
1977 <                        continue;
1962 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
1963 >        int n = tab.length, stride;
1964 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
1965 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
1966 >        if (nextTab == null) {            // initiating
1967 >            try {
1968 >                nextTab = (Node<K,V>[])new Node[n << 1];
1969 >            } catch (Throwable ex) {      // try to cope with OOME
1970 >                sizeCtl = Integer.MAX_VALUE;
1971 >                return;
1972 >            }
1973 >            nextTable = nextTab;
1974 >            transferOrigin = n;
1975 >            transferIndex = n;
1976 >            Node<K,V> rev = new Node<K,V>(MOVED, tab, null, null);
1977 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
1978 >                int nextk = (k > stride) ? k - stride : 0;
1979 >                for (int m = nextk; m < k; ++m)
1980 >                    nextTab[m] = rev;
1981 >                for (int m = n + nextk; m < n + k; ++m)
1982 >                    nextTab[m] = rev;
1983 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
1984 >            }
1985 >        }
1986 >        int nextn = nextTab.length;
1987 >        Node<K,V> fwd = new Node<K,V>(MOVED, nextTab, null, null);
1988 >        boolean advance = true;
1989 >        for (int i = 0, bound = 0;;) {
1990 >            int nextIndex, nextBound; Node<K,V> f; Object fk;
1991 >            while (advance) {
1992 >                if (--i >= bound)
1993 >                    advance = false;
1994 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
1995 >                    i = -1;
1996 >                    advance = false;
1997 >                }
1998 >                else if (U.compareAndSwapInt
1999 >                         (this, TRANSFERINDEX, nextIndex,
2000 >                          nextBound = (nextIndex > stride ?
2001 >                                       nextIndex - stride : 0))) {
2002 >                    bound = nextBound;
2003 >                    i = nextIndex - 1;
2004 >                    advance = false;
2005 >                }
2006 >            }
2007 >            if (i < 0 || i >= n || i + n >= nextn) {
2008 >                for (int sc;;) {
2009 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2010 >                        if (sc == -1) {
2011 >                            nextTable = null;
2012 >                            table = nextTab;
2013 >                            sizeCtl = (n << 1) - (n >>> 1);
2014 >                        }
2015 >                        return;
2016 >                    }
2017                  }
2018 <                else {             // transiently use a locked forwarding node
2019 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2020 <                    if (!casTabAt(tab, i, f, g))
2135 <                        continue;
2018 >            }
2019 >            else if ((f = tabAt(tab, i)) == null) {
2020 >                if (casTabAt(tab, i, null, fwd)) {
2021                      setTabAt(nextTab, i, null);
2022                      setTabAt(nextTab, i + n, null);
2023 <                    setTabAt(tab, i, fwd);
2139 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2140 <                        g.hash = MOVED;
2141 <                        synchronized (g) { g.notifyAll(); }
2142 <                    }
2023 >                    advance = true;
2024                  }
2025              }
2026 <            else if ((fh = f.hash) == MOVED) {
2027 <                Object fk = f.key;
2028 <                if (fk instanceof TreeBin) {
2029 <                    TreeBin t = (TreeBin)fk;
2030 <                    boolean validated = false;
2031 <                    t.acquire(0);
2032 <                    try {
2033 <                        if (tabAt(tab, i) == f) {
2034 <                            validated = true;
2035 <                            splitTreeBin(nextTab, i, t);
2036 <                            setTabAt(tab, i, fwd);
2026 >            else if (f.hash >= 0) {
2027 >                synchronized (f) {
2028 >                    if (tabAt(tab, i) == f) {
2029 >                        int runBit = f.hash & n;
2030 >                        Node<K,V> lastRun = f, lo = null, hi = null;
2031 >                        for (Node<K,V> p = f.next; p != null; p = p.next) {
2032 >                            int b = p.hash & n;
2033 >                            if (b != runBit) {
2034 >                                runBit = b;
2035 >                                lastRun = p;
2036 >                            }
2037                          }
2038 <                    } finally {
2039 <                        t.release(0);
2038 >                        if (runBit == 0)
2039 >                            lo = lastRun;
2040 >                        else
2041 >                            hi = lastRun;
2042 >                        for (Node<K,V> p = f; p != lastRun; p = p.next) {
2043 >                            int ph = p.hash; Object pk = p.key; V pv = p.val;
2044 >                            if ((ph & n) == 0)
2045 >                                lo = new Node<K,V>(ph, pk, pv, lo);
2046 >                            else
2047 >                                hi = new Node<K,V>(ph, pk, pv, hi);
2048 >                        }
2049 >                        setTabAt(nextTab, i, lo);
2050 >                        setTabAt(nextTab, i + n, hi);
2051 >                        setTabAt(tab, i, fwd);
2052 >                        advance = true;
2053                      }
2160                    if (!validated)
2161                        continue;
2054                  }
2055              }
2056 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2057 <                boolean validated = false;
2058 <                try {              // split to lo and hi lists; copying as needed
2056 >            else if ((fk = f.key) instanceof TreeBin) {
2057 >                TreeBin<K,V> t = (TreeBin<K,V>)fk;
2058 >                long stamp = t.writeLock();
2059 >                try {
2060                      if (tabAt(tab, i) == f) {
2061 <                        validated = true;
2062 <                        splitBin(nextTab, i, f);
2061 >                        TreeNode<K,V> root;
2062 >                        Node<K,V> ln = null, hn = null;
2063 >                        if ((root = t.root) != null) {
2064 >                            Node<K,V> e, p; TreeNode<K,V> lr, rr; int lh;
2065 >                            TreeBin<K,V> lt = null, ht = null;
2066 >                            for (lr = root; lr.left != null; lr = lr.left);
2067 >                            for (rr = root; rr.right != null; rr = rr.right);
2068 >                            if ((lh = lr.hash) == rr.hash) { // move entire tree
2069 >                                if ((lh & n) == 0)
2070 >                                    lt = t;
2071 >                                else
2072 >                                    ht = t;
2073 >                            }
2074 >                            else {
2075 >                                lt = new TreeBin<K,V>();
2076 >                                ht = new TreeBin<K,V>();
2077 >                                int lc = 0, hc = 0;
2078 >                                for (e = t.first; e != null; e = e.next) {
2079 >                                    int h = e.hash;
2080 >                                    Object k = e.key; V v = e.val;
2081 >                                    if ((h & n) == 0) {
2082 >                                        ++lc;
2083 >                                        lt.putTreeNode(h, k, v);
2084 >                                    }
2085 >                                    else {
2086 >                                        ++hc;
2087 >                                        ht.putTreeNode(h, k, v);
2088 >                                    }
2089 >                                }
2090 >                                if (lc < TREE_THRESHOLD) { // throw away
2091 >                                    for (p = lt.first; p != null; p = p.next)
2092 >                                        ln = new Node<K,V>(p.hash, p.key,
2093 >                                                           p.val, ln);
2094 >                                    lt = null;
2095 >                                }
2096 >                                if (hc < TREE_THRESHOLD) {
2097 >                                    for (p = ht.first; p != null; p = p.next)
2098 >                                        hn = new Node<K,V>(p.hash, p.key,
2099 >                                                           p.val, hn);
2100 >                                    ht = null;
2101 >                                }
2102 >                            }
2103 >                            if (ln == null && lt != null)
2104 >                                ln = new Node<K,V>(MOVED, lt, null, null);
2105 >                            if (hn == null && ht != null)
2106 >                                hn = new Node<K,V>(MOVED, ht, null, null);
2107 >                        }
2108 >                        setTabAt(nextTab, i, ln);
2109 >                        setTabAt(nextTab, i + n, hn);
2110                          setTabAt(tab, i, fwd);
2111 +                        advance = true;
2112                      }
2113                  } finally {
2114 <                    if (!f.casHash(fh | LOCKED, fh)) {
2174 <                        f.hash = fh;
2175 <                        synchronized (f) { f.notifyAll(); };
2176 <                    }
2114 >                    t.unlockWrite(stamp);
2115                  }
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];
2116              }
2117              else
2118 <                return nextTab;
2118 >                advance = true; // already processed
2119          }
2120      }
2121  
2122 <    /**
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 <    }
2122 >    /* ---------------- Counter support -------------- */
2123  
2124 <    /**
2125 <     * Splits a tree bin into lo and hi parts; installs in given table.
2126 <     */
2127 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2128 <        int bit = nextTab.length >>> 1;
2129 <        TreeBin lt = new TreeBin();
2130 <        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);
2124 >    final long sumCount() {
2125 >        Cell[] as = counterCells; Cell a;
2126 >        long sum = baseCount;
2127 >        if (as != null) {
2128 >            for (int i = 0; i < as.length; ++i) {
2129 >                if ((a = as[i]) != null)
2130 >                    sum += a.value;
2131              }
2132          }
2133 <        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);
2133 >        return sum;
2134      }
2135  
2136 <    /**
2137 <     * Implementation for clear. Steps through each bin, removing all
2138 <     * nodes.
2139 <     */
2140 <    private final void internalClear() {
2141 <        long delta = 0L; // negative number of deletions
2142 <        int i = 0;
2143 <        Node[] tab = table;
2144 <        while (tab != null && i < tab.length) {
2145 <            int fh; Object fk;
2146 <            Node f = tabAt(tab, i);
2147 <            if (f == null)
2148 <                ++i;
2149 <            else if ((fh = f.hash) == MOVED) {
2150 <                if ((fk = f.key) instanceof TreeBin) {
2151 <                    TreeBin t = (TreeBin)fk;
2152 <                    t.acquire(0);
2153 <                    try {
2154 <                        if (tabAt(tab, i) == f) {
2155 <                            for (Node p = t.first; p != null; p = p.next) {
2156 <                                if (p.val != null) { // (currently always true)
2157 <                                    p.val = null;
2158 <                                    --delta;
2136 >    // See LongAdder version for explanation
2137 >    private final void fullAddCount(long x, boolean wasUncontended) {
2138 >        int h;
2139 >        if ((h = ThreadLocalRandom.getProbe()) == 0) {
2140 >            ThreadLocalRandom.localInit();      // force initialization
2141 >            h = ThreadLocalRandom.getProbe();
2142 >            wasUncontended = true;
2143 >        }
2144 >        boolean collide = false;                // True if last slot nonempty
2145 >        for (;;) {
2146 >            Cell[] as; Cell a; int n; long v;
2147 >            if ((as = counterCells) != null && (n = as.length) > 0) {
2148 >                if ((a = as[(n - 1) & h]) == null) {
2149 >                    if (cellsBusy == 0) {            // Try to attach new Cell
2150 >                        Cell r = new Cell(x); // Optimistic create
2151 >                        if (cellsBusy == 0 &&
2152 >                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2153 >                            boolean created = false;
2154 >                            try {               // Recheck under lock
2155 >                                Cell[] rs; int m, j;
2156 >                                if ((rs = counterCells) != null &&
2157 >                                    (m = rs.length) > 0 &&
2158 >                                    rs[j = (m - 1) & h] == null) {
2159 >                                    rs[j] = r;
2160 >                                    created = true;
2161                                  }
2162 +                            } finally {
2163 +                                cellsBusy = 0;
2164                              }
2165 <                            t.first = null;
2166 <                            t.root = null;
2167 <                            ++i;
2165 >                            if (created)
2166 >                                break;
2167 >                            continue;           // Slot is now non-empty
2168 >                        }
2169 >                    }
2170 >                    collide = false;
2171 >                }
2172 >                else if (!wasUncontended)       // CAS already known to fail
2173 >                    wasUncontended = true;      // Continue after rehash
2174 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2175 >                    break;
2176 >                else if (counterCells != as || n >= NCPU)
2177 >                    collide = false;            // At max size or stale
2178 >                else if (!collide)
2179 >                    collide = true;
2180 >                else if (cellsBusy == 0 &&
2181 >                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2182 >                    try {
2183 >                        if (counterCells == as) {// Expand table unless stale
2184 >                            Cell[] rs = new Cell[n << 1];
2185 >                            for (int i = 0; i < n; ++i)
2186 >                                rs[i] = as[i];
2187 >                            counterCells = rs;
2188                          }
2189                      } finally {
2190 <                        t.release(0);
2190 >                        cellsBusy = 0;
2191                      }
2192 +                    collide = false;
2193 +                    continue;                   // Retry with expanded table
2194                  }
2195 <                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);
2195 >                h = ThreadLocalRandom.advanceProbe(h);
2196              }
2197 <            else if (f.casHash(fh, fh | LOCKED)) {
2198 <                try {
2199 <                    if (tabAt(tab, i) == f) {
2200 <                        for (Node e = f; e != null; e = e.next) {
2201 <                            if (e.val != null) {  // (currently always true)
2202 <                                e.val = null;
2203 <                                --delta;
2204 <                            }
2205 <                        }
2334 <                        setTabAt(tab, i, null);
2335 <                        ++i;
2197 >            else if (cellsBusy == 0 && counterCells == as &&
2198 >                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2199 >                boolean init = false;
2200 >                try {                           // Initialize table
2201 >                    if (counterCells == as) {
2202 >                        Cell[] rs = new Cell[2];
2203 >                        rs[h & 1] = new Cell(x);
2204 >                        counterCells = rs;
2205 >                        init = true;
2206                      }
2207                  } finally {
2208 <                    if (!f.casHash(fh | LOCKED, fh)) {
2339 <                        f.hash = fh;
2340 <                        synchronized (f) { f.notifyAll(); };
2341 <                    }
2208 >                    cellsBusy = 0;
2209                  }
2210 +                if (init)
2211 +                    break;
2212              }
2213 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2214 +                break;                          // Fall back on using base
2215          }
2345        if (delta != 0)
2346            counter.add(delta);
2216      }
2217  
2218      /* ----------------Table Traversal -------------- */
2219  
2220      /**
2221       * Encapsulates traversal for methods such as containsValue; also
2222 <     * serves as a base class for other iterators and bulk tasks.
2222 >     * serves as a base class for other iterators and spliterators.
2223       *
2224 <     * 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
2224 >     * Method advance visits once each still-valid node that was
2225       * reachable upon iterator construction. It might miss some that
2226       * were added to a bin after the bin was visited, which is OK wrt
2227       * consistency guarantees. Maintaining this property in the face
# Line 2385 | Line 2237 | public class ConcurrentHashMap<K, V>
2237       * paranoically cope with potential sharing by users of iterators
2238       * across threads, iteration terminates if a bounds checks fails
2239       * for a table read.
2240 <     *
2241 <     * This class extends ForkJoinTask to streamline parallel
2242 <     * iteration in bulk operations (see BulkTask). This adds only an
2243 <     * int of space overhead, which is close enough to negligible in
2244 <     * cases where it is not needed to not worry about it.  Because
2245 <     * ForkJoinTask is Serializable, but iterators need not be, we
2246 <     * need to add warning suppressions.
2247 <     */
2248 <    @SuppressWarnings("serial") static class Traverser<K,V,R> extends ForkJoinTask<R> {
2249 <        final ConcurrentHashMap<K, V> map;
2250 <        Node next;           // the next entry to use
2251 <        Object nextKey;      // cached key field of next
2252 <        Object nextVal;      // cached val field of next
2253 <        Node[] tab;          // current table; updated if resized
2254 <        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;
2240 >     */
2241 >    static class Traverser<K,V> {
2242 >        Node<K,V>[] tab;        // current table; updated if resized
2243 >        Node<K,V> next;         // the next entry to use
2244 >        int index;              // index of bin to use next
2245 >        int baseIndex;          // current index of initial table
2246 >        int baseLimit;          // index bound for initial table
2247 >        final int baseSize;     // initial table size
2248 >
2249 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
2250 >            this.tab = tab;
2251 >            this.baseSize = size;
2252 >            this.baseIndex = this.index = index;
2253 >            this.baseLimit = limit;
2254 >            this.next = null;
2255          }
2256  
2257          /**
2258 <         * Advances next; returns nextVal or null if terminated.
2259 <         * See above for explanation.
2260 <         */
2261 <        final Object advance() {
2262 <            Node e = next;
2263 <            Object ev = null;
2264 <            outer: do {
2265 <                if (e != null)                  // advance past used/skipped node
2266 <                    e = e.next;
2267 <                while (e == null) {             // get to next non-null bin
2268 <                    ConcurrentHashMap<K, V> m;
2269 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2270 <                    if ((t = tab) != null)
2271 <                        n = t.length;
2272 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2273 <                        n = baseLimit = baseSize = t.length;
2274 <                    else
2275 <                        break outer;
2276 <                    if ((b = baseIndex) >= baseLimit ||
2277 <                        (i = index) < 0 || i >= n)
2278 <                        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);
2258 >         * Advances if possible, returning next valid node, or null if none.
2259 >         */
2260 >        final Node<K,V> advance() {
2261 >            Node<K,V> e;
2262 >            if ((e = next) != null)
2263 >                e = e.next;
2264 >            for (;;) {
2265 >                Node<K,V>[] t; int i, n; Object ek;  // must use locals in checks
2266 >                if (e != null)
2267 >                    return next = e;
2268 >                if (baseIndex >= baseLimit || (t = tab) == null ||
2269 >                    (n = t.length) <= (i = index) || i < 0)
2270 >                    return next = null;
2271 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
2272 >                    if ((ek = e.key) instanceof TreeBin)
2273 >                        e = ((TreeBin<K,V>)ek).first;
2274 >                    else {
2275 >                        tab = (Node<K,V>[])ek;
2276 >                        e = null;
2277 >                        continue;
2278 >                    }
2279                  }
2280 <                nextKey = e.key;
2281 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2282 <            next = e;
2461 <            return nextVal = ev;
2280 >                if ((index += baseSize) >= n)
2281 >                    index = ++baseIndex;    // visit upper slots if present
2282 >            }
2283          }
2284 +    }
2285 +
2286 +    /**
2287 +     * Base of key, value, and entry Iterators. Adds fields to
2288 +     * Traverser to support iterator.remove
2289 +     */
2290 +    static class BaseIterator<K,V> extends Traverser<K,V> {
2291 +        final ConcurrentHashMap<K,V> map;
2292 +        Node<K,V> lastReturned;
2293 +        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
2294 +                    ConcurrentHashMap<K,V> map) {
2295 +            super(tab, size, index, limit);
2296 +            this.map = map;
2297 +            advance();
2298 +        }
2299 +
2300 +        public final boolean hasNext() { return next != null; }
2301 +        public final boolean hasMoreElements() { return next != null; }
2302  
2303          public final void remove() {
2304 <            Object k = nextKey;
2305 <            if (k == null && (advance() == null || (k = nextKey) == null))
2304 >            Node<K,V> p;
2305 >            if ((p = lastReturned) == null)
2306                  throw new IllegalStateException();
2307 <            map.internalReplace(k, null, null);
2307 >            lastReturned = null;
2308 >            map.internalReplace((K)p.key, null, null);
2309 >        }
2310 >    }
2311 >
2312 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
2313 >        implements Iterator<K>, Enumeration<K> {
2314 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
2315 >                    ConcurrentHashMap<K,V> map) {
2316 >            super(tab, index, size, limit, map);
2317 >        }
2318 >
2319 >        public final K next() {
2320 >            Node<K,V> p;
2321 >            if ((p = next) == null)
2322 >                throw new NoSuchElementException();
2323 >            K k = (K)p.key;
2324 >            lastReturned = p;
2325 >            advance();
2326 >            return k;
2327 >        }
2328 >
2329 >        public final K nextElement() { return next(); }
2330 >    }
2331 >
2332 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
2333 >        implements Iterator<V>, Enumeration<V> {
2334 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
2335 >                      ConcurrentHashMap<K,V> map) {
2336 >            super(tab, index, size, limit, map);
2337 >        }
2338 >
2339 >        public final V next() {
2340 >            Node<K,V> p;
2341 >            if ((p = next) == null)
2342 >                throw new NoSuchElementException();
2343 >            V v = p.val;
2344 >            lastReturned = p;
2345 >            advance();
2346 >            return v;
2347 >        }
2348 >
2349 >        public final V nextElement() { return next(); }
2350 >    }
2351 >
2352 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
2353 >        implements Iterator<Map.Entry<K,V>> {
2354 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
2355 >                      ConcurrentHashMap<K,V> map) {
2356 >            super(tab, index, size, limit, map);
2357 >        }
2358 >
2359 >        public final Map.Entry<K,V> next() {
2360 >            Node<K,V> p;
2361 >            if ((p = next) == null)
2362 >                throw new NoSuchElementException();
2363 >            K k = (K)p.key;
2364 >            V v = p.val;
2365 >            lastReturned = p;
2366 >            advance();
2367 >            return new MapEntry<K,V>(k, v, map);
2368 >        }
2369 >    }
2370 >
2371 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
2372 >        implements Spliterator<K> {
2373 >        long est;               // size estimate
2374 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
2375 >                       long est) {
2376 >            super(tab, size, index, limit);
2377 >            this.est = est;
2378 >        }
2379 >
2380 >        public Spliterator<K> trySplit() {
2381 >            int i, f, h;
2382 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
2383 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
2384 >                                        f, est >>>= 1);
2385 >        }
2386 >
2387 >        public void forEachRemaining(Consumer<? super K> action) {
2388 >            if (action == null) throw new NullPointerException();
2389 >            for (Node<K,V> p; (p = advance()) != null;)
2390 >                action.accept((K)p.key);
2391 >        }
2392 >
2393 >        public boolean tryAdvance(Consumer<? super K> action) {
2394 >            if (action == null) throw new NullPointerException();
2395 >            Node<K,V> p;
2396 >            if ((p = advance()) == null)
2397 >                return false;
2398 >            action.accept((K)p.key);
2399 >            return true;
2400 >        }
2401 >
2402 >        public long estimateSize() { return est; }
2403 >
2404 >        public int characteristics() {
2405 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
2406 >                Spliterator.NONNULL;
2407 >        }
2408 >    }
2409 >
2410 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
2411 >        implements Spliterator<V> {
2412 >        long est;               // size estimate
2413 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
2414 >                         long est) {
2415 >            super(tab, size, index, limit);
2416 >            this.est = est;
2417 >        }
2418 >
2419 >        public Spliterator<V> trySplit() {
2420 >            int i, f, h;
2421 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
2422 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
2423 >                                          f, est >>>= 1);
2424 >        }
2425 >
2426 >        public void forEachRemaining(Consumer<? super V> action) {
2427 >            if (action == null) throw new NullPointerException();
2428 >            for (Node<K,V> p; (p = advance()) != null;)
2429 >                action.accept(p.val);
2430 >        }
2431 >
2432 >        public boolean tryAdvance(Consumer<? super V> action) {
2433 >            if (action == null) throw new NullPointerException();
2434 >            Node<K,V> p;
2435 >            if ((p = advance()) == null)
2436 >                return false;
2437 >            action.accept(p.val);
2438 >            return true;
2439 >        }
2440 >
2441 >        public long estimateSize() { return est; }
2442 >
2443 >        public int characteristics() {
2444 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
2445 >        }
2446 >    }
2447 >
2448 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
2449 >        implements Spliterator<Map.Entry<K,V>> {
2450 >        final ConcurrentHashMap<K,V> map; // To export MapEntry
2451 >        long est;               // size estimate
2452 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
2453 >                         long est, ConcurrentHashMap<K,V> map) {
2454 >            super(tab, size, index, limit);
2455 >            this.map = map;
2456 >            this.est = est;
2457          }
2458  
2459 <        public final boolean hasNext() {
2460 <            return nextVal != null || advance() != null;
2459 >        public Spliterator<Map.Entry<K,V>> trySplit() {
2460 >            int i, f, h;
2461 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
2462 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
2463 >                                          f, est >>>= 1, map);
2464          }
2465  
2466 <        public final boolean hasMoreElements() { return hasNext(); }
2467 <        public final void setRawResult(Object x) { }
2468 <        public R getRawResult() { return null; }
2469 <        public boolean exec() { return true; }
2466 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
2467 >            if (action == null) throw new NullPointerException();
2468 >            for (Node<K,V> p; (p = advance()) != null; )
2469 >                action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
2470 >        }
2471 >
2472 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
2473 >            if (action == null) throw new NullPointerException();
2474 >            Node<K,V> p;
2475 >            if ((p = advance()) == null)
2476 >                return false;
2477 >            action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
2478 >            return true;
2479 >        }
2480 >
2481 >        public long estimateSize() { return est; }
2482 >
2483 >        public int characteristics() {
2484 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
2485 >                Spliterator.NONNULL;
2486 >        }
2487      }
2488  
2489 +
2490      /* ---------------- Public operations -------------- */
2491  
2492      /**
2493       * Creates a new, empty map with the default initial table size (16).
2494       */
2495      public ConcurrentHashMap() {
2487        this.counter = new LongAdder();
2496      }
2497  
2498      /**
# Line 2503 | Line 2511 | public class ConcurrentHashMap<K, V>
2511          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2512                     MAXIMUM_CAPACITY :
2513                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2506        this.counter = new LongAdder();
2514          this.sizeCtl = cap;
2515      }
2516  
# Line 2513 | Line 2520 | public class ConcurrentHashMap<K, V>
2520       * @param m the map
2521       */
2522      public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2516        this.counter = new LongAdder();
2523          this.sizeCtl = DEFAULT_CAPACITY;
2524          internalPutAll(m);
2525      }
# Line 2556 | Line 2562 | public class ConcurrentHashMap<K, V>
2562       * nonpositive
2563       */
2564      public ConcurrentHashMap(int initialCapacity,
2565 <                               float loadFactor, int concurrencyLevel) {
2565 >                             float loadFactor, int concurrencyLevel) {
2566          if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2567              throw new IllegalArgumentException();
2568          if (initialCapacity < concurrencyLevel)   // Use at least as many bins
# Line 2564 | Line 2570 | public class ConcurrentHashMap<K, V>
2570          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2571          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2572              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2567        this.counter = new LongAdder();
2573          this.sizeCtl = cap;
2574      }
2575  
# Line 2573 | Line 2578 | public class ConcurrentHashMap<K, V>
2578       * from the given type to {@code Boolean.TRUE}.
2579       *
2580       * @return the new set
2581 +     * @since 1.8
2582       */
2583      public static <K> KeySetView<K,Boolean> newKeySet() {
2584 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(),
2585 <                                      Boolean.TRUE);
2584 >        return new KeySetView<K,Boolean>
2585 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2586      }
2587  
2588      /**
# Line 2588 | Line 2594 | public class ConcurrentHashMap<K, V>
2594       * @throws IllegalArgumentException if the initial capacity of
2595       * elements is negative
2596       * @return the new set
2597 +     * @since 1.8
2598       */
2599      public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2600 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(initialCapacity),
2601 <                                      Boolean.TRUE);
2600 >        return new KeySetView<K,Boolean>
2601 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2602      }
2603  
2604      /**
2605       * {@inheritDoc}
2606       */
2607      public boolean isEmpty() {
2608 <        return counter.sum() <= 0L; // ignore transient negative values
2608 >        return sumCount() <= 0L; // ignore transient negative values
2609      }
2610  
2611      /**
2612       * {@inheritDoc}
2613       */
2614      public int size() {
2615 <        long n = counter.sum();
2615 >        long n = sumCount();
2616          return ((n < 0L) ? 0 :
2617                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2618                  (int)n);
# Line 2615 | Line 2622 | public class ConcurrentHashMap<K, V>
2622       * Returns the number of mappings. This method should be used
2623       * instead of {@link #size} because a ConcurrentHashMap may
2624       * contain more mappings than can be represented as an int. The
2625 <     * value returned is a snapshot; the actual count may differ if
2626 <     * there are ongoing concurrent insertions or removals.
2625 >     * value returned is an estimate; the actual count may differ if
2626 >     * there are concurrent insertions or removals.
2627       *
2628       * @return the number of mappings
2629 +     * @since 1.8
2630       */
2631      public long mappingCount() {
2632 <        long n = counter.sum();
2632 >        long n = sumCount();
2633          return (n < 0L) ? 0L : n; // ignore transient negative values
2634      }
2635  
# Line 2636 | Line 2644 | public class ConcurrentHashMap<K, V>
2644       *
2645       * @throws NullPointerException if the specified key is null
2646       */
2647 <    @SuppressWarnings("unchecked") public V get(Object key) {
2648 <        if (key == null)
2641 <            throw new NullPointerException();
2642 <        return (V)internalGet(key);
2647 >    public V get(Object key) {
2648 >        return internalGet(key);
2649      }
2650  
2651      /**
2652 <     * Returns the value to which the specified key is mapped,
2653 <     * or the given defaultValue if this map contains no mapping for the key.
2652 >     * Returns the value to which the specified key is mapped, or the
2653 >     * given default value if this map contains no mapping for the
2654 >     * key.
2655       *
2656 <     * @param key the key
2656 >     * @param key the key whose associated value is to be returned
2657       * @param defaultValue the value to return if this map contains
2658       * no mapping for the given key
2659 <     * @return the mapping for the key, if present; else the defaultValue
2659 >     * @return the mapping for the key, if present; else the default value
2660       * @throws NullPointerException if the specified key is null
2661       */
2662 <    @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) {
2663 <        if (key == null)
2664 <            throw new NullPointerException();
2658 <        V v = (V) internalGet(key);
2659 <        return v == null ? defaultValue : v;
2662 >    public V getOrDefault(Object key, V defaultValue) {
2663 >        V v;
2664 >        return (v = internalGet(key)) == null ? defaultValue : v;
2665      }
2666  
2667      /**
2668       * Tests if the specified object is a key in this table.
2669       *
2670 <     * @param  key   possible key
2670 >     * @param  key possible key
2671       * @return {@code true} if and only if the specified object
2672       *         is a key in this table, as determined by the
2673       *         {@code equals} method; {@code false} otherwise
2674       * @throws NullPointerException if the specified key is null
2675       */
2676      public boolean containsKey(Object key) {
2672        if (key == null)
2673            throw new NullPointerException();
2677          return internalGet(key) != null;
2678      }
2679  
# Line 2687 | Line 2690 | public class ConcurrentHashMap<K, V>
2690      public boolean containsValue(Object value) {
2691          if (value == null)
2692              throw new NullPointerException();
2693 <        Object v;
2694 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2695 <        while ((v = it.advance()) != null) {
2696 <            if (v == value || value.equals(v))
2697 <                return true;
2693 >        Node<K,V>[] t;
2694 >        if ((t = table) != null) {
2695 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
2696 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
2697 >                V v;
2698 >                if ((v = p.val) == value || value.equals(v))
2699 >                    return true;
2700 >            }
2701          }
2702          return false;
2703      }
# Line 2699 | Line 2705 | public class ConcurrentHashMap<K, V>
2705      /**
2706       * Legacy method testing if some key maps into the specified value
2707       * in this table.  This method is identical in functionality to
2708 <     * {@link #containsValue}, and exists solely to ensure
2708 >     * {@link #containsValue(Object)}, and exists solely to ensure
2709       * full compatibility with class {@link java.util.Hashtable},
2710       * which supported this method prior to introduction of the
2711       * Java Collections framework.
# Line 2711 | Line 2717 | public class ConcurrentHashMap<K, V>
2717       *         {@code false} otherwise
2718       * @throws NullPointerException if the specified value is null
2719       */
2720 <    public boolean contains(Object value) {
2720 >    @Deprecated public boolean contains(Object value) {
2721          return containsValue(value);
2722      }
2723  
# Line 2719 | Line 2725 | public class ConcurrentHashMap<K, V>
2725       * Maps the specified key to the specified value in this table.
2726       * Neither the key nor the value can be null.
2727       *
2728 <     * <p> The value can be retrieved by calling the {@code get} method
2728 >     * <p>The value can be retrieved by calling the {@code get} method
2729       * with a key that is equal to the original key.
2730       *
2731       * @param key key with which the specified value is to be associated
# Line 2728 | Line 2734 | public class ConcurrentHashMap<K, V>
2734       *         {@code null} if there was no mapping for {@code key}
2735       * @throws NullPointerException if the specified key or value is null
2736       */
2737 <    @SuppressWarnings("unchecked") public V put(K key, V value) {
2738 <        if (key == null || value == null)
2733 <            throw new NullPointerException();
2734 <        return (V)internalPut(key, value);
2737 >    public V put(K key, V value) {
2738 >        return internalPut(key, value, false);
2739      }
2740  
2741      /**
# Line 2741 | Line 2745 | public class ConcurrentHashMap<K, V>
2745       *         or {@code null} if there was no mapping for the key
2746       * @throws NullPointerException if the specified key or value is null
2747       */
2748 <    @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) {
2749 <        if (key == null || value == null)
2746 <            throw new NullPointerException();
2747 <        return (V)internalPutIfAbsent(key, value);
2748 >    public V putIfAbsent(K key, V value) {
2749 >        return internalPut(key, value, true);
2750      }
2751  
2752      /**
# Line 2760 | Line 2762 | public class ConcurrentHashMap<K, V>
2762  
2763      /**
2764       * If the specified key is not already associated with a value,
2765 <     * computes its value using the given mappingFunction and enters
2766 <     * it into the map unless null.  This is equivalent to
2767 <     * <pre> {@code
2768 <     * if (map.containsKey(key))
2769 <     *   return map.get(key);
2770 <     * value = mappingFunction.apply(key);
2771 <     * 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>
2765 >     * attempts to compute its value using the given mapping function
2766 >     * and enters it into this map unless {@code null}.  The entire
2767 >     * method invocation is performed atomically, so the function is
2768 >     * applied at most once per key.  Some attempted update operations
2769 >     * on this map by other threads may be blocked while computation
2770 >     * is in progress, so the computation should be short and simple,
2771 >     * and must not attempt to update any other mappings of this map.
2772       *
2773       * @param key key with which the specified value is to be associated
2774       * @param mappingFunction the function to compute a value
# Line 2797 | Line 2782 | public class ConcurrentHashMap<K, V>
2782       * @throws RuntimeException or Error if the mappingFunction does so,
2783       *         in which case the mapping is left unestablished
2784       */
2785 <    @SuppressWarnings("unchecked") public V computeIfAbsent
2786 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
2802 <        if (key == null || mappingFunction == null)
2803 <            throw new NullPointerException();
2804 <        return (V)internalComputeIfAbsent(key, mappingFunction);
2785 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
2786 >        return internalComputeIfAbsent(key, mappingFunction);
2787      }
2788  
2789      /**
2790 <     * If the given key is present, computes a new mapping value given a key and
2791 <     * its current mapped value. This is equivalent to
2792 <     *  <pre> {@code
2793 <     *   if (map.containsKey(key)) {
2794 <     *     value = remappingFunction.apply(key, map.get(key));
2795 <     *     if (value != null)
2796 <     *       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:
2790 >     * If the value for the specified key is present, attempts to
2791 >     * compute a new mapping given the key and its current mapped
2792 >     * value.  The entire method invocation is performed atomically.
2793 >     * Some attempted update operations on this map by other threads
2794 >     * may be blocked while computation is in progress, so the
2795 >     * computation should be short and simple, and must not attempt to
2796 >     * update any other mappings of this map.
2797       *
2798 <     * @param key key with which the specified value is to be associated
2798 >     * @param key key with which a value may be associated
2799       * @param remappingFunction the function to compute a value
2800       * @return the new value associated with the specified key, or null if none
2801       * @throws NullPointerException if the specified key or remappingFunction
# Line 2838 | Line 2806 | public class ConcurrentHashMap<K, V>
2806       * @throws RuntimeException or Error if the remappingFunction does so,
2807       *         in which case the mapping is unchanged
2808       */
2809 <    @SuppressWarnings("unchecked") public V computeIfPresent
2810 <        (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);
2809 >    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2810 >        return internalCompute(key, true, remappingFunction);
2811      }
2812  
2813      /**
2814 <     * Computes a new mapping value given a key and
2815 <     * its current mapped value (or {@code null} if there is no current
2816 <     * mapping). This is equivalent to
2817 <     *  <pre> {@code
2818 <     *   value = remappingFunction.apply(key, map.get(key));
2819 <     *   if (value != null)
2820 <     *     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>
2814 >     * Attempts to compute a mapping for the specified key and its
2815 >     * current mapped value (or {@code null} if there is no current
2816 >     * mapping). The entire method invocation is performed atomically.
2817 >     * Some attempted update operations on this map by other threads
2818 >     * may be blocked while computation is in progress, so the
2819 >     * computation should be short and simple, and must not attempt to
2820 >     * update any other mappings of this Map.
2821       *
2822       * @param key key with which the specified value is to be associated
2823       * @param remappingFunction the function to compute a value
# Line 2885 | Line 2830 | public class ConcurrentHashMap<K, V>
2830       * @throws RuntimeException or Error if the remappingFunction does so,
2831       *         in which case the mapping is unchanged
2832       */
2833 <    @SuppressWarnings("unchecked") public V compute
2834 <        (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);
2833 >    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2834 >        return internalCompute(key, false, remappingFunction);
2835      }
2836  
2837      /**
2838 <     * If the specified key is not already associated
2839 <     * with a value, associate it with the given value.
2840 <     * Otherwise, replace the value with the results of
2841 <     * the given remapping function. This is equivalent to:
2842 <     *  <pre> {@code
2843 <     *   if (!map.containsKey(key))
2844 <     *     map.put(value);
2845 <     *   else {
2846 <     *     newValue = remappingFunction.apply(map.get(key), value);
2847 <     *     if (value != null)
2848 <     *       map.put(key, value);
2849 <     *     else
2850 <     *       map.remove(key);
2851 <     *   }
2852 <     * }</pre>
2853 <     * except that the action is performed atomically.  If the
2854 <     * function returns {@code null}, the mapping is removed.  If the
2855 <     * function itself throws an (unchecked) exception, the exception
2856 <     * is rethrown to its caller, and the current mapping is left
2857 <     * unchanged.  Some attempted update operations on this map by
2858 <     * 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);
2838 >     * If the specified key is not already associated with a
2839 >     * (non-null) value, associates it with the given value.
2840 >     * Otherwise, replaces the value with the results of the given
2841 >     * remapping function, or removes if {@code null}. The entire
2842 >     * method invocation is performed atomically.  Some attempted
2843 >     * update operations on this map by other threads may be blocked
2844 >     * while computation is in progress, so the computation should be
2845 >     * short and simple, and must not attempt to update any other
2846 >     * mappings of this Map.
2847 >     *
2848 >     * @param key key with which the specified value is to be associated
2849 >     * @param value the value to use if absent
2850 >     * @param remappingFunction the function to recompute a value if present
2851 >     * @return the new value associated with the specified key, or null if none
2852 >     * @throws NullPointerException if the specified key or the
2853 >     *         remappingFunction is null
2854 >     * @throws RuntimeException or Error if the remappingFunction does so,
2855 >     *         in which case the mapping is unchanged
2856 >     */
2857 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2858 >        return internalMerge(key, value, remappingFunction);
2859      }
2860  
2861      /**
# Line 2933 | Line 2867 | public class ConcurrentHashMap<K, V>
2867       *         {@code null} if there was no mapping for {@code key}
2868       * @throws NullPointerException if the specified key is null
2869       */
2870 <    @SuppressWarnings("unchecked") public V remove(Object key) {
2871 <        if (key == null)
2938 <            throw new NullPointerException();
2939 <        return (V)internalReplace(key, null, null);
2870 >    public V remove(Object key) {
2871 >        return internalReplace(key, null, null);
2872      }
2873  
2874      /**
# Line 2947 | Line 2879 | public class ConcurrentHashMap<K, V>
2879      public boolean remove(Object key, Object value) {
2880          if (key == null)
2881              throw new NullPointerException();
2882 <        if (value == null)
2951 <            return false;
2952 <        return internalReplace(key, null, value) != null;
2882 >        return value != null && internalReplace(key, null, value) != null;
2883      }
2884  
2885      /**
# Line 2970 | Line 2900 | public class ConcurrentHashMap<K, V>
2900       *         or {@code null} if there was no mapping for the key
2901       * @throws NullPointerException if the specified key or value is null
2902       */
2903 <    @SuppressWarnings("unchecked") public V replace(K key, V value) {
2903 >    public V replace(K key, V value) {
2904          if (key == null || value == null)
2905              throw new NullPointerException();
2906 <        return (V)internalReplace(key, value, null);
2906 >        return internalReplace(key, value, null);
2907      }
2908  
2909      /**
# Line 2986 | Line 2916 | public class ConcurrentHashMap<K, V>
2916      /**
2917       * Returns a {@link Set} view of the keys contained in this map.
2918       * The set is backed by the map, so changes to the map are
2919 <     * reflected in the set, and vice-versa.
2919 >     * reflected in the set, and vice-versa. The set supports element
2920 >     * removal, which removes the corresponding mapping from this map,
2921 >     * via the {@code Iterator.remove}, {@code Set.remove},
2922 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
2923 >     * operations.  It does not support the {@code add} or
2924 >     * {@code addAll} operations.
2925 >     *
2926 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2927 >     * that will never throw {@link ConcurrentModificationException},
2928 >     * and guarantees to traverse elements as they existed upon
2929 >     * construction of the iterator, and may (but is not guaranteed to)
2930 >     * reflect any modifications subsequent to construction.
2931       *
2932       * @return the set view
2933       */
# Line 2998 | Line 2939 | public class ConcurrentHashMap<K, V>
2939      /**
2940       * Returns a {@link Set} view of the keys in this map, using the
2941       * given common mapped value for any additions (i.e., {@link
2942 <     * Collection#add} and {@link Collection#addAll}). This is of
2943 <     * course only appropriate if it is acceptable to use the same
2944 <     * value for all additions from this view.
2942 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2943 >     * This is of course only appropriate if it is acceptable to use
2944 >     * the same value for all additions from this view.
2945       *
2946 <     * @param mappedValue the mapped value to use for any
3006 <     * additions.
2946 >     * @param mappedValue the mapped value to use for any additions
2947       * @return the set view
2948       * @throws NullPointerException if the mappedValue is null
2949       */
# Line 3016 | Line 2956 | public class ConcurrentHashMap<K, V>
2956      /**
2957       * Returns a {@link Collection} view of the values contained in this map.
2958       * The collection is backed by the map, so changes to the map are
2959 <     * reflected in the collection, and vice-versa.
2959 >     * reflected in the collection, and vice-versa.  The collection
2960 >     * supports element removal, which removes the corresponding
2961 >     * mapping from this map, via the {@code Iterator.remove},
2962 >     * {@code Collection.remove}, {@code removeAll},
2963 >     * {@code retainAll}, and {@code clear} operations.  It does not
2964 >     * support the {@code add} or {@code addAll} operations.
2965 >     *
2966 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2967 >     * that will never throw {@link ConcurrentModificationException},
2968 >     * and guarantees to traverse elements as they existed upon
2969 >     * construction of the iterator, and may (but is not guaranteed to)
2970 >     * reflect any modifications subsequent to construction.
2971 >     *
2972 >     * @return the collection view
2973       */
2974 <    public ValuesView<K,V> values() {
2974 >    public Collection<V> values() {
2975          ValuesView<K,V> vs = values;
2976          return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2977      }
# Line 3030 | Line 2983 | public class ConcurrentHashMap<K, V>
2983       * removal, which removes the corresponding mapping from the map,
2984       * via the {@code Iterator.remove}, {@code Set.remove},
2985       * {@code removeAll}, {@code retainAll}, and {@code clear}
2986 <     * operations.  It does not support the {@code add} or
3034 <     * {@code addAll} operations.
2986 >     * operations.
2987       *
2988       * <p>The view's {@code iterator} is a "weakly consistent" iterator
2989       * that will never throw {@link ConcurrentModificationException},
2990       * and guarantees to traverse elements as they existed upon
2991       * construction of the iterator, and may (but is not guaranteed to)
2992       * reflect any modifications subsequent to construction.
2993 +     *
2994 +     * @return the set view
2995       */
2996      public Set<Map.Entry<K,V>> entrySet() {
2997          EntrySetView<K,V> es = entrySet;
# Line 3051 | Line 3005 | public class ConcurrentHashMap<K, V>
3005       * @see #keySet()
3006       */
3007      public Enumeration<K> keys() {
3008 <        return new KeyIterator<K,V>(this);
3008 >        Node<K,V>[] t;
3009 >        int f = (t = table) == null ? 0 : t.length;
3010 >        return new KeyIterator<K,V>(t, f, 0, f, this);
3011      }
3012  
3013      /**
# Line 3061 | Line 3017 | public class ConcurrentHashMap<K, V>
3017       * @see #values()
3018       */
3019      public Enumeration<V> elements() {
3020 <        return new ValueIterator<K,V>(this);
3021 <    }
3022 <
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);
3020 >        Node<K,V>[] t;
3021 >        int f = (t = table) == null ? 0 : t.length;
3022 >        return new ValueIterator<K,V>(t, f, 0, f, this);
3023      }
3024  
3025      /**
# Line 3100 | Line 3031 | public class ConcurrentHashMap<K, V>
3031       */
3032      public int hashCode() {
3033          int h = 0;
3034 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3035 <        Object v;
3036 <        while ((v = it.advance()) != null) {
3037 <            h += it.nextKey.hashCode() ^ v.hashCode();
3034 >        Node<K,V>[] t;
3035 >        if ((t = table) != null) {
3036 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3037 >            for (Node<K,V> p; (p = it.advance()) != null; )
3038 >                h += p.key.hashCode() ^ p.val.hashCode();
3039          }
3040          return h;
3041      }
# Line 3120 | Line 3052 | public class ConcurrentHashMap<K, V>
3052       * @return a string representation of this map
3053       */
3054      public String toString() {
3055 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3055 >        Node<K,V>[] t;
3056 >        int f = (t = table) == null ? 0 : t.length;
3057 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
3058          StringBuilder sb = new StringBuilder();
3059          sb.append('{');
3060 <        Object v;
3061 <        if ((v = it.advance()) != null) {
3060 >        Node<K,V> p;
3061 >        if ((p = it.advance()) != null) {
3062              for (;;) {
3063 <                Object k = it.nextKey;
3063 >                K k = (K)p.key;
3064 >                V v = p.val;
3065                  sb.append(k == this ? "(this Map)" : k);
3066                  sb.append('=');
3067                  sb.append(v == this ? "(this Map)" : v);
3068 <                if ((v = it.advance()) == null)
3068 >                if ((p = it.advance()) == null)
3069                      break;
3070                  sb.append(',').append(' ');
3071              }
# Line 3153 | Line 3088 | public class ConcurrentHashMap<K, V>
3088              if (!(o instanceof Map))
3089                  return false;
3090              Map<?,?> m = (Map<?,?>) o;
3091 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3092 <            Object val;
3093 <            while ((val = it.advance()) != null) {
3094 <                Object v = m.get(it.nextKey);
3091 >            Node<K,V>[] t;
3092 >            int f = (t = table) == null ? 0 : t.length;
3093 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
3094 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
3095 >                V val = p.val;
3096 >                Object v = m.get(p.key);
3097                  if (v == null || (v != val && !v.equals(val)))
3098                      return false;
3099              }
# Line 3172 | Line 3109 | public class ConcurrentHashMap<K, V>
3109          return true;
3110      }
3111  
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
3112      /* ---------------- Serialization Support -------------- */
3113  
3114      /**
3115       * Stripped-down version of helper class used in previous version,
3116       * declared for the sake of serialization compatibility
3117       */
3118 <    static class Segment<K,V> implements Serializable {
3118 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
3119          private static final long serialVersionUID = 2249069246763182397L;
3120          final float loadFactor;
3121          Segment(float lf) { this.loadFactor = lf; }
# Line 3305 | Line 3130 | public class ConcurrentHashMap<K, V>
3130       * for each key-value mapping, followed by a null pair.
3131       * The key-value mappings are emitted in no particular order.
3132       */
3133 <    @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s)
3133 >    private void writeObject(java.io.ObjectOutputStream s)
3134          throws java.io.IOException {
3135 <        if (segments == null) { // for serialization compatibility
3136 <            segments = (Segment<K,V>[])
3137 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3138 <            for (int i = 0; i < segments.length; ++i)
3139 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3140 <        }
3141 <        s.defaultWriteObject();
3142 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3143 <        Object v;
3144 <        while ((v = it.advance()) != null) {
3145 <            s.writeObject(it.nextKey);
3146 <            s.writeObject(v);
3135 >        // For serialization compatibility
3136 >        // Emulate segment calculation from previous version of this class
3137 >        int sshift = 0;
3138 >        int ssize = 1;
3139 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
3140 >            ++sshift;
3141 >            ssize <<= 1;
3142 >        }
3143 >        int segmentShift = 32 - sshift;
3144 >        int segmentMask = ssize - 1;
3145 >        Segment<K,V>[] segments = (Segment<K,V>[])
3146 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3147 >        for (int i = 0; i < segments.length; ++i)
3148 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
3149 >        s.putFields().put("segments", segments);
3150 >        s.putFields().put("segmentShift", segmentShift);
3151 >        s.putFields().put("segmentMask", segmentMask);
3152 >        s.writeFields();
3153 >
3154 >        Node<K,V>[] t;
3155 >        if ((t = table) != null) {
3156 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3157 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
3158 >                s.writeObject(p.key);
3159 >                s.writeObject(p.val);
3160 >            }
3161          }
3162          s.writeObject(null);
3163          s.writeObject(null);
# Line 3329 | Line 3168 | public class ConcurrentHashMap<K, V>
3168       * Reconstitutes the instance from a stream (that is, deserializes it).
3169       * @param s the stream
3170       */
3171 <    @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
3171 >    private void readObject(java.io.ObjectInputStream s)
3172          throws java.io.IOException, ClassNotFoundException {
3173          s.defaultReadObject();
3335        this.segments = null; // unneeded
3336        // initialize transient final field
3337        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
3174  
3175          // Create all nodes, then place in table once size is known
3176          long size = 0L;
3177 <        Node p = null;
3177 >        Node<K,V> p = null;
3178          for (;;) {
3179              K k = (K) s.readObject();
3180              V v = (V) s.readObject();
3181              if (k != null && v != null) {
3182                  int h = spread(k.hashCode());
3183 <                p = new Node(h, k, v, p);
3183 >                p = new Node<K,V>(h, k, v, p);
3184                  ++size;
3185              }
3186              else
# Line 3362 | Line 3198 | public class ConcurrentHashMap<K, V>
3198              int sc = sizeCtl;
3199              boolean collide = false;
3200              if (n > sc &&
3201 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3201 >                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3202                  try {
3203                      if (table == null) {
3204                          init = true;
3205 <                        Node[] tab = new Node[n];
3205 >                        Node<K,V>[] tab = (Node<K,V>[])new Node[n];
3206                          int mask = n - 1;
3207                          while (p != null) {
3208                              int j = p.hash & mask;
3209 <                            Node next = p.next;
3210 <                            Node q = p.next = tabAt(tab, j);
3209 >                            Node<K,V> next = p.next;
3210 >                            Node<K,V> q = p.next = tabAt(tab, j);
3211                              setTabAt(tab, j, p);
3212                              if (!collide && q != null && q.hash == p.hash)
3213                                  collide = true;
3214                              p = next;
3215                          }
3216                          table = tab;
3217 <                        counter.add(size);
3217 >                        addCount(size, -1);
3218                          sc = n - (n >>> 2);
3219                      }
3220                  } finally {
3221                      sizeCtl = sc;
3222                  }
3223                  if (collide) { // rescan and convert to TreeBins
3224 <                    Node[] tab = table;
3224 >                    Node<K,V>[] tab = table;
3225                      for (int i = 0; i < tab.length; ++i) {
3226                          int c = 0;
3227 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3227 >                        for (Node<K,V> e = tabAt(tab, i); e != null; e = e.next) {
3228                              if (++c > TREE_THRESHOLD &&
3229                                  (e.key instanceof Comparable)) {
3230                                  replaceWithTreeBin(tab, i, e.key);
# Line 3400 | Line 3236 | public class ConcurrentHashMap<K, V>
3236              }
3237              if (!init) { // Can only happen if unsafely published.
3238                  while (p != null) {
3239 <                    internalPut(p.key, p.val);
3239 >                    internalPut((K)p.key, p.val, false);
3240                      p = p.next;
3241                  }
3242              }
3243          }
3244      }
3245  
3410
3246      // -------------------------------------------------------
3247  
3248 <    // 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); }
3248 >    // Overrides of other default Map methods
3249  
3250 +    public void forEach(BiConsumer<? super K, ? super V> action) {
3251 +        if (action == null) throw new NullPointerException();
3252 +        Node<K,V>[] t;
3253 +        if ((t = table) != null) {
3254 +            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3255 +            for (Node<K,V> p; (p = it.advance()) != null; ) {
3256 +                action.accept((K)p.key, p.val);
3257 +            }
3258 +        }
3259 +    }
3260 +
3261 +    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3262 +        if (function == null) throw new NullPointerException();
3263 +        Node<K,V>[] t;
3264 +        if ((t = table) != null) {
3265 +            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3266 +            for (Node<K,V> p; (p = it.advance()) != null; ) {
3267 +                K k = (K)p.key;
3268 +                internalPut(k, function.apply(k, p.val), false);
3269 +            }
3270 +        }
3271 +    }
3272  
3273      // -------------------------------------------------------
3274  
3275 +    // Parallel bulk operations
3276 +
3277 +    /**
3278 +     * Computes initial batch value for bulk tasks. The returned value
3279 +     * is approximately exp2 of the number of times (minus one) to
3280 +     * split task by two before executing leaf action. This value is
3281 +     * faster to compute and more convenient to use as a guide to
3282 +     * splitting than is the depth, since it is used while dividing by
3283 +     * two anyway.
3284 +     */
3285 +    final int batchFor(long b) {
3286 +        long n;
3287 +        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3288 +            return 0;
3289 +        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3290 +        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3291 +    }
3292 +
3293      /**
3294       * Performs the given action for each (key, value).
3295       *
3296 +     * @param parallelismThreshold the (estimated) number of elements
3297 +     * needed for this operation to be executed in parallel
3298       * @param action the action
3299 +     * @since 1.8
3300       */
3301 <    public void forEach(BiAction<K,V> action) {
3302 <        ForkJoinTasks.forEach
3303 <            (this, action).invoke();
3301 >    public void forEach(long parallelismThreshold,
3302 >                        BiConsumer<? super K,? super V> action) {
3303 >        if (action == null) throw new NullPointerException();
3304 >        new ForEachMappingTask<K,V>
3305 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3306 >             action).invoke();
3307      }
3308  
3309      /**
3310       * Performs the given action for each non-null transformation
3311       * of each (key, value).
3312       *
3313 +     * @param parallelismThreshold the (estimated) number of elements
3314 +     * needed for this operation to be executed in parallel
3315       * @param transformer a function returning the transformation
3316 <     * for an element, or null of there is no transformation (in
3317 <     * which case the action is not applied).
3316 >     * for an element, or null if there is no transformation (in
3317 >     * which case the action is not applied)
3318       * @param action the action
3319 +     * @since 1.8
3320       */
3321 <    public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3322 <                            Action<U> action) {
3323 <        ForkJoinTasks.forEach
3324 <            (this, transformer, action).invoke();
3321 >    public <U> void forEach(long parallelismThreshold,
3322 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3323 >                            Consumer<? super U> action) {
3324 >        if (transformer == null || action == null)
3325 >            throw new NullPointerException();
3326 >        new ForEachTransformedMappingTask<K,V,U>
3327 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3328 >             transformer, action).invoke();
3329      }
3330  
3331      /**
# Line 3481 | Line 3335 | public class ConcurrentHashMap<K, V>
3335       * results of any other parallel invocations of the search
3336       * function are ignored.
3337       *
3338 +     * @param parallelismThreshold the (estimated) number of elements
3339 +     * needed for this operation to be executed in parallel
3340       * @param searchFunction a function returning a non-null
3341       * result on success, else null
3342       * @return a non-null result from applying the given search
3343       * function on each (key, value), or null if none
3344 +     * @since 1.8
3345       */
3346 <    public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3347 <        return ForkJoinTasks.search
3348 <            (this, searchFunction).invoke();
3346 >    public <U> U search(long parallelismThreshold,
3347 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3348 >        if (searchFunction == null) throw new NullPointerException();
3349 >        return new SearchMappingsTask<K,V,U>
3350 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3351 >             searchFunction, new AtomicReference<U>()).invoke();
3352      }
3353  
3354      /**
# Line 3496 | Line 3356 | public class ConcurrentHashMap<K, V>
3356       * of all (key, value) pairs using the given reducer to
3357       * combine values, or null if none.
3358       *
3359 +     * @param parallelismThreshold the (estimated) number of elements
3360 +     * needed for this operation to be executed in parallel
3361       * @param transformer a function returning the transformation
3362 <     * for an element, or null of there is no transformation (in
3363 <     * which case it is not combined).
3362 >     * for an element, or null if there is no transformation (in
3363 >     * which case it is not combined)
3364       * @param reducer a commutative associative combining function
3365       * @return the result of accumulating the given transformation
3366       * of all (key, value) pairs
3367 +     * @since 1.8
3368       */
3369 <    public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3370 <                        BiFun<? super U, ? super U, ? extends U> reducer) {
3371 <        return ForkJoinTasks.reduce
3372 <            (this, transformer, reducer).invoke();
3369 >    public <U> U reduce(long parallelismThreshold,
3370 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3371 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3372 >        if (transformer == null || reducer == null)
3373 >            throw new NullPointerException();
3374 >        return new MapReduceMappingsTask<K,V,U>
3375 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3376 >             null, transformer, reducer).invoke();
3377      }
3378  
3379      /**
# Line 3514 | Line 3381 | public class ConcurrentHashMap<K, V>
3381       * of all (key, value) pairs using the given reducer to
3382       * combine values, and the given basis as an identity value.
3383       *
3384 +     * @param parallelismThreshold the (estimated) number of elements
3385 +     * needed for this operation to be executed in parallel
3386       * @param transformer a function returning the transformation
3387       * for an element
3388       * @param basis the identity (initial default value) for the reduction
3389       * @param reducer a commutative associative combining function
3390       * @return the result of accumulating the given transformation
3391       * of all (key, value) pairs
3392 +     * @since 1.8
3393       */
3394 <    public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
3395 <                                 double basis,
3396 <                                 DoubleByDoubleToDouble reducer) {
3397 <        return ForkJoinTasks.reduceToDouble
3398 <            (this, transformer, basis, reducer).invoke();
3394 >    public double reduceToDoubleIn(long parallelismThreshold,
3395 >                                   ToDoubleBiFunction<? super K, ? super V> transformer,
3396 >                                   double basis,
3397 >                                   DoubleBinaryOperator reducer) {
3398 >        if (transformer == null || reducer == null)
3399 >            throw new NullPointerException();
3400 >        return new MapReduceMappingsToDoubleTask<K,V>
3401 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3402 >             null, transformer, basis, reducer).invoke();
3403      }
3404  
3405      /**
# Line 3533 | Line 3407 | public class ConcurrentHashMap<K, V>
3407       * of all (key, value) pairs using the given reducer to
3408       * combine values, and the given basis as an identity value.
3409       *
3410 +     * @param parallelismThreshold the (estimated) number of elements
3411 +     * needed for this operation to be executed in parallel
3412       * @param transformer a function returning the transformation
3413       * for an element
3414       * @param basis the identity (initial default value) for the reduction
3415       * @param reducer a commutative associative combining function
3416       * @return the result of accumulating the given transformation
3417       * of all (key, value) pairs
3418 +     * @since 1.8
3419       */
3420 <    public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
3420 >    public long reduceToLong(long parallelismThreshold,
3421 >                             ToLongBiFunction<? super K, ? super V> transformer,
3422                               long basis,
3423 <                             LongByLongToLong reducer) {
3424 <        return ForkJoinTasks.reduceToLong
3425 <            (this, transformer, basis, reducer).invoke();
3423 >                             LongBinaryOperator reducer) {
3424 >        if (transformer == null || reducer == null)
3425 >            throw new NullPointerException();
3426 >        return new MapReduceMappingsToLongTask<K,V>
3427 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3428 >             null, transformer, basis, reducer).invoke();
3429      }
3430  
3431      /**
# Line 3552 | Line 3433 | public class ConcurrentHashMap<K, V>
3433       * of all (key, value) pairs using the given reducer to
3434       * combine values, and the given basis as an identity value.
3435       *
3436 +     * @param parallelismThreshold the (estimated) number of elements
3437 +     * needed for this operation to be executed in parallel
3438       * @param transformer a function returning the transformation
3439       * for an element
3440       * @param basis the identity (initial default value) for the reduction
3441       * @param reducer a commutative associative combining function
3442       * @return the result of accumulating the given transformation
3443       * of all (key, value) pairs
3444 +     * @since 1.8
3445       */
3446 <    public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
3446 >    public int reduceToInt(long parallelismThreshold,
3447 >                           ToIntBiFunction<? super K, ? super V> transformer,
3448                             int basis,
3449 <                           IntByIntToInt reducer) {
3450 <        return ForkJoinTasks.reduceToInt
3451 <            (this, transformer, basis, reducer).invoke();
3449 >                           IntBinaryOperator reducer) {
3450 >        if (transformer == null || reducer == null)
3451 >            throw new NullPointerException();
3452 >        return new MapReduceMappingsToIntTask<K,V>
3453 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3454 >             null, transformer, basis, reducer).invoke();
3455      }
3456  
3457      /**
3458       * Performs the given action for each key.
3459       *
3460 +     * @param parallelismThreshold the (estimated) number of elements
3461 +     * needed for this operation to be executed in parallel
3462       * @param action the action
3463 +     * @since 1.8
3464       */
3465 <    public void forEachKey(Action<K> action) {
3466 <        ForkJoinTasks.forEachKey
3467 <            (this, action).invoke();
3465 >    public void forEachKey(long parallelismThreshold,
3466 >                           Consumer<? super K> action) {
3467 >        if (action == null) throw new NullPointerException();
3468 >        new ForEachKeyTask<K,V>
3469 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3470 >             action).invoke();
3471      }
3472  
3473      /**
3474       * Performs the given action for each non-null transformation
3475       * of each key.
3476       *
3477 +     * @param parallelismThreshold the (estimated) number of elements
3478 +     * needed for this operation to be executed in parallel
3479       * @param transformer a function returning the transformation
3480 <     * for an element, or null of there is no transformation (in
3481 <     * which case the action is not applied).
3480 >     * for an element, or null if there is no transformation (in
3481 >     * which case the action is not applied)
3482       * @param action the action
3483 +     * @since 1.8
3484       */
3485 <    public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
3486 <                               Action<U> action) {
3487 <        ForkJoinTasks.forEachKey
3488 <            (this, transformer, action).invoke();
3485 >    public <U> void forEachKey(long parallelismThreshold,
3486 >                               Function<? super K, ? extends U> transformer,
3487 >                               Consumer<? super U> action) {
3488 >        if (transformer == null || action == null)
3489 >            throw new NullPointerException();
3490 >        new ForEachTransformedKeyTask<K,V,U>
3491 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3492 >             transformer, action).invoke();
3493      }
3494  
3495      /**
# Line 3598 | Line 3499 | public class ConcurrentHashMap<K, V>
3499       * any other parallel invocations of the search function are
3500       * ignored.
3501       *
3502 +     * @param parallelismThreshold the (estimated) number of elements
3503 +     * needed for this operation to be executed in parallel
3504       * @param searchFunction a function returning a non-null
3505       * result on success, else null
3506       * @return a non-null result from applying the given search
3507       * function on each key, or null if none
3508 +     * @since 1.8
3509       */
3510 <    public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
3511 <        return ForkJoinTasks.searchKeys
3512 <            (this, searchFunction).invoke();
3510 >    public <U> U searchKeys(long parallelismThreshold,
3511 >                            Function<? super K, ? extends U> searchFunction) {
3512 >        if (searchFunction == null) throw new NullPointerException();
3513 >        return new SearchKeysTask<K,V,U>
3514 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3515 >             searchFunction, new AtomicReference<U>()).invoke();
3516      }
3517  
3518      /**
3519       * Returns the result of accumulating all keys using the given
3520       * reducer to combine values, or null if none.
3521       *
3522 +     * @param parallelismThreshold the (estimated) number of elements
3523 +     * needed for this operation to be executed in parallel
3524       * @param reducer a commutative associative combining function
3525       * @return the result of accumulating all keys using the given
3526       * reducer to combine values, or null if none
3527 +     * @since 1.8
3528       */
3529 <    public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
3530 <        return ForkJoinTasks.reduceKeys
3531 <            (this, reducer).invoke();
3529 >    public K reduceKeys(long parallelismThreshold,
3530 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3531 >        if (reducer == null) throw new NullPointerException();
3532 >        return new ReduceKeysTask<K,V>
3533 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3534 >             null, reducer).invoke();
3535      }
3536  
3537      /**
# Line 3626 | Line 3539 | public class ConcurrentHashMap<K, V>
3539       * of all keys using the given reducer to combine values, or
3540       * null if none.
3541       *
3542 +     * @param parallelismThreshold the (estimated) number of elements
3543 +     * needed for this operation to be executed in parallel
3544       * @param transformer a function returning the transformation
3545 <     * for an element, or null of there is no transformation (in
3546 <     * which case it is not combined).
3545 >     * for an element, or null if there is no transformation (in
3546 >     * which case it is not combined)
3547       * @param reducer a commutative associative combining function
3548       * @return the result of accumulating the given transformation
3549       * of all keys
3550 +     * @since 1.8
3551       */
3552 <    public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
3553 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
3554 <        return ForkJoinTasks.reduceKeys
3555 <            (this, transformer, reducer).invoke();
3552 >    public <U> U reduceKeys(long parallelismThreshold,
3553 >                            Function<? super K, ? extends U> transformer,
3554 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3555 >        if (transformer == null || reducer == null)
3556 >            throw new NullPointerException();
3557 >        return new MapReduceKeysTask<K,V,U>
3558 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3559 >             null, transformer, reducer).invoke();
3560      }
3561  
3562      /**
# Line 3644 | Line 3564 | public class ConcurrentHashMap<K, V>
3564       * of all keys using the given reducer to combine values, and
3565       * the given basis as an identity value.
3566       *
3567 +     * @param parallelismThreshold the (estimated) number of elements
3568 +     * needed for this operation to be executed in parallel
3569       * @param transformer a function returning the transformation
3570       * for an element
3571       * @param basis the identity (initial default value) for the reduction
3572       * @param reducer a commutative associative combining function
3573 <     * @return  the result of accumulating the given transformation
3573 >     * @return the result of accumulating the given transformation
3574       * of all keys
3575 +     * @since 1.8
3576       */
3577 <    public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
3577 >    public double reduceKeysToDouble(long parallelismThreshold,
3578 >                                     ToDoubleFunction<? super K> transformer,
3579                                       double basis,
3580 <                                     DoubleByDoubleToDouble reducer) {
3581 <        return ForkJoinTasks.reduceKeysToDouble
3582 <            (this, transformer, basis, reducer).invoke();
3580 >                                     DoubleBinaryOperator reducer) {
3581 >        if (transformer == null || reducer == null)
3582 >            throw new NullPointerException();
3583 >        return new MapReduceKeysToDoubleTask<K,V>
3584 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3585 >             null, transformer, basis, reducer).invoke();
3586      }
3587  
3588      /**
# Line 3663 | Line 3590 | public class ConcurrentHashMap<K, V>
3590       * of all keys using the given reducer to combine values, and
3591       * the given basis as an identity value.
3592       *
3593 +     * @param parallelismThreshold the (estimated) number of elements
3594 +     * needed for this operation to be executed in parallel
3595       * @param transformer a function returning the transformation
3596       * for an element
3597       * @param basis the identity (initial default value) for the reduction
3598       * @param reducer a commutative associative combining function
3599       * @return the result of accumulating the given transformation
3600       * of all keys
3601 +     * @since 1.8
3602       */
3603 <    public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3603 >    public long reduceKeysToLong(long parallelismThreshold,
3604 >                                 ToLongFunction<? super K> transformer,
3605                                   long basis,
3606 <                                 LongByLongToLong reducer) {
3607 <        return ForkJoinTasks.reduceKeysToLong
3608 <            (this, transformer, basis, reducer).invoke();
3606 >                                 LongBinaryOperator reducer) {
3607 >        if (transformer == null || reducer == null)
3608 >            throw new NullPointerException();
3609 >        return new MapReduceKeysToLongTask<K,V>
3610 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3611 >             null, transformer, basis, reducer).invoke();
3612      }
3613  
3614      /**
# Line 3682 | Line 3616 | public class ConcurrentHashMap<K, V>
3616       * of all keys using the given reducer to combine values, and
3617       * the given basis as an identity value.
3618       *
3619 +     * @param parallelismThreshold the (estimated) number of elements
3620 +     * needed for this operation to be executed in parallel
3621       * @param transformer a function returning the transformation
3622       * for an element
3623       * @param basis the identity (initial default value) for the reduction
3624       * @param reducer a commutative associative combining function
3625       * @return the result of accumulating the given transformation
3626       * of all keys
3627 +     * @since 1.8
3628       */
3629 <    public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3629 >    public int reduceKeysToInt(long parallelismThreshold,
3630 >                               ToIntFunction<? super K> transformer,
3631                                 int basis,
3632 <                               IntByIntToInt reducer) {
3633 <        return ForkJoinTasks.reduceKeysToInt
3634 <            (this, transformer, basis, reducer).invoke();
3632 >                               IntBinaryOperator reducer) {
3633 >        if (transformer == null || reducer == null)
3634 >            throw new NullPointerException();
3635 >        return new MapReduceKeysToIntTask<K,V>
3636 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3637 >             null, transformer, basis, reducer).invoke();
3638      }
3639  
3640      /**
3641       * Performs the given action for each value.
3642       *
3643 +     * @param parallelismThreshold the (estimated) number of elements
3644 +     * needed for this operation to be executed in parallel
3645       * @param action the action
3646 +     * @since 1.8
3647       */
3648 <    public void forEachValue(Action<V> action) {
3649 <        ForkJoinTasks.forEachValue
3650 <            (this, action).invoke();
3648 >    public void forEachValue(long parallelismThreshold,
3649 >                             Consumer<? super V> action) {
3650 >        if (action == null)
3651 >            throw new NullPointerException();
3652 >        new ForEachValueTask<K,V>
3653 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3654 >             action).invoke();
3655      }
3656  
3657      /**
3658       * Performs the given action for each non-null transformation
3659       * of each value.
3660       *
3661 +     * @param parallelismThreshold the (estimated) number of elements
3662 +     * needed for this operation to be executed in parallel
3663       * @param transformer a function returning the transformation
3664 <     * for an element, or null of there is no transformation (in
3665 <     * which case the action is not applied).
3664 >     * for an element, or null if there is no transformation (in
3665 >     * which case the action is not applied)
3666 >     * @param action the action
3667 >     * @since 1.8
3668       */
3669 <    public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
3670 <                                 Action<U> action) {
3671 <        ForkJoinTasks.forEachValue
3672 <            (this, transformer, action).invoke();
3669 >    public <U> void forEachValue(long parallelismThreshold,
3670 >                                 Function<? super V, ? extends U> transformer,
3671 >                                 Consumer<? super U> action) {
3672 >        if (transformer == null || action == null)
3673 >            throw new NullPointerException();
3674 >        new ForEachTransformedValueTask<K,V,U>
3675 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3676 >             transformer, action).invoke();
3677      }
3678  
3679      /**
# Line 3727 | Line 3683 | public class ConcurrentHashMap<K, V>
3683       * any other parallel invocations of the search function are
3684       * ignored.
3685       *
3686 +     * @param parallelismThreshold the (estimated) number of elements
3687 +     * needed for this operation to be executed in parallel
3688       * @param searchFunction a function returning a non-null
3689       * result on success, else null
3690       * @return a non-null result from applying the given search
3691       * function on each value, or null if none
3692 <     *
3692 >     * @since 1.8
3693       */
3694 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
3695 <        return ForkJoinTasks.searchValues
3696 <            (this, searchFunction).invoke();
3694 >    public <U> U searchValues(long parallelismThreshold,
3695 >                              Function<? super V, ? extends U> searchFunction) {
3696 >        if (searchFunction == null) throw new NullPointerException();
3697 >        return new SearchValuesTask<K,V,U>
3698 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3699 >             searchFunction, new AtomicReference<U>()).invoke();
3700      }
3701  
3702      /**
3703       * Returns the result of accumulating all values using the
3704       * given reducer to combine values, or null if none.
3705       *
3706 +     * @param parallelismThreshold the (estimated) number of elements
3707 +     * needed for this operation to be executed in parallel
3708       * @param reducer a commutative associative combining function
3709 <     * @return  the result of accumulating all values
3709 >     * @return the result of accumulating all values
3710 >     * @since 1.8
3711       */
3712 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
3713 <        return ForkJoinTasks.reduceValues
3714 <            (this, reducer).invoke();
3712 >    public V reduceValues(long parallelismThreshold,
3713 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
3714 >        if (reducer == null) throw new NullPointerException();
3715 >        return new ReduceValuesTask<K,V>
3716 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3717 >             null, reducer).invoke();
3718      }
3719  
3720      /**
# Line 3755 | Line 3722 | public class ConcurrentHashMap<K, V>
3722       * of all values using the given reducer to combine values, or
3723       * null if none.
3724       *
3725 +     * @param parallelismThreshold the (estimated) number of elements
3726 +     * needed for this operation to be executed in parallel
3727       * @param transformer a function returning the transformation
3728 <     * for an element, or null of there is no transformation (in
3729 <     * which case it is not combined).
3728 >     * for an element, or null if there is no transformation (in
3729 >     * which case it is not combined)
3730       * @param reducer a commutative associative combining function
3731       * @return the result of accumulating the given transformation
3732       * of all values
3733 +     * @since 1.8
3734       */
3735 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
3736 <                              BiFun<? super U, ? super U, ? extends U> reducer) {
3737 <        return ForkJoinTasks.reduceValues
3738 <            (this, transformer, reducer).invoke();
3735 >    public <U> U reduceValues(long parallelismThreshold,
3736 >                              Function<? super V, ? extends U> transformer,
3737 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
3738 >        if (transformer == null || reducer == null)
3739 >            throw new NullPointerException();
3740 >        return new MapReduceValuesTask<K,V,U>
3741 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3742 >             null, transformer, reducer).invoke();
3743      }
3744  
3745      /**
# Line 3773 | Line 3747 | public class ConcurrentHashMap<K, V>
3747       * of all values using the given reducer to combine values,
3748       * and the given basis as an identity value.
3749       *
3750 +     * @param parallelismThreshold the (estimated) number of elements
3751 +     * needed for this operation to be executed in parallel
3752       * @param transformer a function returning the transformation
3753       * for an element
3754       * @param basis the identity (initial default value) for the reduction
3755       * @param reducer a commutative associative combining function
3756       * @return the result of accumulating the given transformation
3757       * of all values
3758 +     * @since 1.8
3759       */
3760 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
3760 >    public double reduceValuesToDouble(long parallelismThreshold,
3761 >                                       ToDoubleFunction<? super V> transformer,
3762                                         double basis,
3763 <                                       DoubleByDoubleToDouble reducer) {
3764 <        return ForkJoinTasks.reduceValuesToDouble
3765 <            (this, transformer, basis, reducer).invoke();
3763 >                                       DoubleBinaryOperator reducer) {
3764 >        if (transformer == null || reducer == null)
3765 >            throw new NullPointerException();
3766 >        return new MapReduceValuesToDoubleTask<K,V>
3767 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3768 >             null, transformer, basis, reducer).invoke();
3769      }
3770  
3771      /**
# Line 3792 | Line 3773 | public class ConcurrentHashMap<K, V>
3773       * of all values using the given reducer to combine values,
3774       * and the given basis as an identity value.
3775       *
3776 +     * @param parallelismThreshold the (estimated) number of elements
3777 +     * needed for this operation to be executed in parallel
3778       * @param transformer a function returning the transformation
3779       * for an element
3780       * @param basis the identity (initial default value) for the reduction
3781       * @param reducer a commutative associative combining function
3782       * @return the result of accumulating the given transformation
3783       * of all values
3784 +     * @since 1.8
3785       */
3786 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
3786 >    public long reduceValuesToLong(long parallelismThreshold,
3787 >                                   ToLongFunction<? super V> transformer,
3788                                     long basis,
3789 <                                   LongByLongToLong reducer) {
3790 <        return ForkJoinTasks.reduceValuesToLong
3791 <            (this, transformer, basis, reducer).invoke();
3789 >                                   LongBinaryOperator reducer) {
3790 >        if (transformer == null || reducer == null)
3791 >            throw new NullPointerException();
3792 >        return new MapReduceValuesToLongTask<K,V>
3793 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3794 >             null, transformer, basis, reducer).invoke();
3795      }
3796  
3797      /**
# Line 3811 | Line 3799 | public class ConcurrentHashMap<K, V>
3799       * of all values using the given reducer to combine values,
3800       * and the given basis as an identity value.
3801       *
3802 +     * @param parallelismThreshold the (estimated) number of elements
3803 +     * needed for this operation to be executed in parallel
3804       * @param transformer a function returning the transformation
3805       * for an element
3806       * @param basis the identity (initial default value) for the reduction
3807       * @param reducer a commutative associative combining function
3808       * @return the result of accumulating the given transformation
3809       * of all values
3810 +     * @since 1.8
3811       */
3812 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
3812 >    public int reduceValuesToInt(long parallelismThreshold,
3813 >                                 ToIntFunction<? super V> transformer,
3814                                   int basis,
3815 <                                 IntByIntToInt reducer) {
3816 <        return ForkJoinTasks.reduceValuesToInt
3817 <            (this, transformer, basis, reducer).invoke();
3815 >                                 IntBinaryOperator reducer) {
3816 >        if (transformer == null || reducer == null)
3817 >            throw new NullPointerException();
3818 >        return new MapReduceValuesToIntTask<K,V>
3819 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3820 >             null, transformer, basis, reducer).invoke();
3821      }
3822  
3823      /**
3824       * Performs the given action for each entry.
3825       *
3826 +     * @param parallelismThreshold the (estimated) number of elements
3827 +     * needed for this operation to be executed in parallel
3828       * @param action the action
3829 +     * @since 1.8
3830       */
3831 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
3832 <        ForkJoinTasks.forEachEntry
3833 <            (this, action).invoke();
3831 >    public void forEachEntry(long parallelismThreshold,
3832 >                             Consumer<? super Map.Entry<K,V>> action) {
3833 >        if (action == null) throw new NullPointerException();
3834 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
3835 >                                  action).invoke();
3836      }
3837  
3838      /**
3839       * Performs the given action for each non-null transformation
3840       * of each entry.
3841       *
3842 +     * @param parallelismThreshold the (estimated) number of elements
3843 +     * needed for this operation to be executed in parallel
3844       * @param transformer a function returning the transformation
3845 <     * for an element, or null of there is no transformation (in
3846 <     * which case the action is not applied).
3845 >     * for an element, or null if there is no transformation (in
3846 >     * which case the action is not applied)
3847       * @param action the action
3848 +     * @since 1.8
3849       */
3850 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
3851 <                                 Action<U> action) {
3852 <        ForkJoinTasks.forEachEntry
3853 <            (this, transformer, action).invoke();
3850 >    public <U> void forEachEntry(long parallelismThreshold,
3851 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
3852 >                                 Consumer<? super U> action) {
3853 >        if (transformer == null || action == null)
3854 >            throw new NullPointerException();
3855 >        new ForEachTransformedEntryTask<K,V,U>
3856 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3857 >             transformer, action).invoke();
3858      }
3859  
3860      /**
# Line 3857 | Line 3864 | public class ConcurrentHashMap<K, V>
3864       * any other parallel invocations of the search function are
3865       * ignored.
3866       *
3867 +     * @param parallelismThreshold the (estimated) number of elements
3868 +     * needed for this operation to be executed in parallel
3869       * @param searchFunction a function returning a non-null
3870       * result on success, else null
3871       * @return a non-null result from applying the given search
3872       * function on each entry, or null if none
3873 +     * @since 1.8
3874       */
3875 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
3876 <        return ForkJoinTasks.searchEntries
3877 <            (this, searchFunction).invoke();
3875 >    public <U> U searchEntries(long parallelismThreshold,
3876 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
3877 >        if (searchFunction == null) throw new NullPointerException();
3878 >        return new SearchEntriesTask<K,V,U>
3879 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3880 >             searchFunction, new AtomicReference<U>()).invoke();
3881      }
3882  
3883      /**
3884       * Returns the result of accumulating all entries using the
3885       * given reducer to combine values, or null if none.
3886       *
3887 +     * @param parallelismThreshold the (estimated) number of elements
3888 +     * needed for this operation to be executed in parallel
3889       * @param reducer a commutative associative combining function
3890       * @return the result of accumulating all entries
3891 +     * @since 1.8
3892       */
3893 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3894 <        return ForkJoinTasks.reduceEntries
3895 <            (this, reducer).invoke();
3893 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
3894 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3895 >        if (reducer == null) throw new NullPointerException();
3896 >        return new ReduceEntriesTask<K,V>
3897 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3898 >             null, reducer).invoke();
3899      }
3900  
3901      /**
# Line 3884 | Line 3903 | public class ConcurrentHashMap<K, V>
3903       * of all entries using the given reducer to combine values,
3904       * or null if none.
3905       *
3906 +     * @param parallelismThreshold the (estimated) number of elements
3907 +     * needed for this operation to be executed in parallel
3908       * @param transformer a function returning the transformation
3909 <     * for an element, or null of there is no transformation (in
3910 <     * which case it is not combined).
3909 >     * for an element, or null if there is no transformation (in
3910 >     * which case it is not combined)
3911       * @param reducer a commutative associative combining function
3912       * @return the result of accumulating the given transformation
3913       * of all entries
3914 +     * @since 1.8
3915       */
3916 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
3917 <                               BiFun<? super U, ? super U, ? extends U> reducer) {
3918 <        return ForkJoinTasks.reduceEntries
3919 <            (this, transformer, reducer).invoke();
3916 >    public <U> U reduceEntries(long parallelismThreshold,
3917 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
3918 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
3919 >        if (transformer == null || reducer == null)
3920 >            throw new NullPointerException();
3921 >        return new MapReduceEntriesTask<K,V,U>
3922 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3923 >             null, transformer, reducer).invoke();
3924      }
3925  
3926      /**
# Line 3902 | Line 3928 | public class ConcurrentHashMap<K, V>
3928       * of all entries using the given reducer to combine values,
3929       * and the given basis as an identity value.
3930       *
3931 +     * @param parallelismThreshold the (estimated) number of elements
3932 +     * needed for this operation to be executed in parallel
3933       * @param transformer a function returning the transformation
3934       * for an element
3935       * @param basis the identity (initial default value) for the reduction
3936       * @param reducer a commutative associative combining function
3937       * @return the result of accumulating the given transformation
3938       * of all entries
3939 +     * @since 1.8
3940       */
3941 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
3941 >    public double reduceEntriesToDouble(long parallelismThreshold,
3942 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
3943                                          double basis,
3944 <                                        DoubleByDoubleToDouble reducer) {
3945 <        return ForkJoinTasks.reduceEntriesToDouble
3946 <            (this, transformer, basis, reducer).invoke();
3944 >                                        DoubleBinaryOperator reducer) {
3945 >        if (transformer == null || reducer == null)
3946 >            throw new NullPointerException();
3947 >        return new MapReduceEntriesToDoubleTask<K,V>
3948 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3949 >             null, transformer, basis, reducer).invoke();
3950      }
3951  
3952      /**
# Line 3921 | Line 3954 | public class ConcurrentHashMap<K, V>
3954       * of all entries using the given reducer to combine values,
3955       * and the given basis as an identity value.
3956       *
3957 +     * @param parallelismThreshold the (estimated) number of elements
3958 +     * needed for this operation to be executed in parallel
3959       * @param transformer a function returning the transformation
3960       * for an element
3961       * @param basis the identity (initial default value) for the reduction
3962       * @param reducer a commutative associative combining function
3963 <     * @return  the result of accumulating the given transformation
3963 >     * @return the result of accumulating the given transformation
3964       * of all entries
3965       */
3966 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
3966 >    public long reduceEntriesToLong(long parallelismThreshold,
3967 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
3968                                      long basis,
3969 <                                    LongByLongToLong reducer) {
3970 <        return ForkJoinTasks.reduceEntriesToLong
3971 <            (this, transformer, basis, reducer).invoke();
3969 >                                    LongBinaryOperator reducer) {
3970 >        if (transformer == null || reducer == null)
3971 >            throw new NullPointerException();
3972 >        return new MapReduceEntriesToLongTask<K,V>
3973 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3974 >             null, transformer, basis, reducer).invoke();
3975      }
3976  
3977      /**
# Line 3940 | Line 3979 | public class ConcurrentHashMap<K, V>
3979       * of all entries using the given reducer to combine values,
3980       * and the given basis as an identity value.
3981       *
3982 +     * @param parallelismThreshold the (estimated) number of elements
3983 +     * needed for this operation to be executed in parallel
3984       * @param transformer a function returning the transformation
3985       * for an element
3986       * @param basis the identity (initial default value) for the reduction
# Line 3947 | Line 3988 | public class ConcurrentHashMap<K, V>
3988       * @return the result of accumulating the given transformation
3989       * of all entries
3990       */
3991 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
3991 >    public int reduceEntriesToInt(long parallelismThreshold,
3992 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
3993                                    int basis,
3994 <                                  IntByIntToInt reducer) {
3995 <        return ForkJoinTasks.reduceEntriesToInt
3996 <            (this, transformer, basis, reducer).invoke();
3994 >                                  IntBinaryOperator reducer) {
3995 >        if (transformer == null || reducer == null)
3996 >            throw new NullPointerException();
3997 >        return new MapReduceEntriesToIntTask<K,V>
3998 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3999 >             null, transformer, basis, reducer).invoke();
4000      }
4001  
4002 +
4003      /* ----------------Views -------------- */
4004  
4005      /**
4006       * Base class for views.
4007       */
4008 <    static abstract class CHMView<K, V> {
4009 <        final ConcurrentHashMap<K, V> map;
4010 <        CHMView(ConcurrentHashMap<K, V> map)  { this.map = map; }
4008 >    abstract static class CollectionView<K,V,E>
4009 >        implements Collection<E>, java.io.Serializable {
4010 >        private static final long serialVersionUID = 7249069246763182397L;
4011 >        final ConcurrentHashMap<K,V> map;
4012 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4013  
4014          /**
4015           * Returns the map backing this view.
# Line 3970 | Line 4018 | public class ConcurrentHashMap<K, V>
4018           */
4019          public ConcurrentHashMap<K,V> getMap() { return map; }
4020  
4021 <        public final int size()                 { return map.size(); }
4022 <        public final boolean isEmpty()          { return map.isEmpty(); }
4023 <        public final void clear()               { map.clear(); }
4021 >        /**
4022 >         * Removes all of the elements from this view, by removing all
4023 >         * the mappings from the map backing this view.
4024 >         */
4025 >        public final void clear()      { map.clear(); }
4026 >        public final int size()        { return map.size(); }
4027 >        public final boolean isEmpty() { return map.isEmpty(); }
4028  
4029          // implementations below rely on concrete classes supplying these
4030 <        abstract public Iterator<?> iterator();
4031 <        abstract public boolean contains(Object o);
4032 <        abstract public boolean remove(Object o);
4030 >        // abstract methods
4031 >        /**
4032 >         * Returns a "weakly consistent" iterator that will never
4033 >         * throw {@link ConcurrentModificationException}, and
4034 >         * guarantees to traverse elements as they existed upon
4035 >         * construction of the iterator, and may (but is not
4036 >         * guaranteed to) reflect any modifications subsequent to
4037 >         * construction.
4038 >         */
4039 >        public abstract Iterator<E> iterator();
4040 >        public abstract boolean contains(Object o);
4041 >        public abstract boolean remove(Object o);
4042  
4043          private static final String oomeMsg = "Required array size too large";
4044  
4045          public final Object[] toArray() {
4046              long sz = map.mappingCount();
4047 <            if (sz > (long)(MAX_ARRAY_SIZE))
4047 >            if (sz > MAX_ARRAY_SIZE)
4048                  throw new OutOfMemoryError(oomeMsg);
4049              int n = (int)sz;
4050              Object[] r = new Object[n];
4051              int i = 0;
4052 <            Iterator<?> it = iterator();
3992 <            while (it.hasNext()) {
4052 >            for (E e : this) {
4053                  if (i == n) {
4054                      if (n >= MAX_ARRAY_SIZE)
4055                          throw new OutOfMemoryError(oomeMsg);
# Line 3999 | Line 4059 | public class ConcurrentHashMap<K, V>
4059                          n += (n >>> 1) + 1;
4060                      r = Arrays.copyOf(r, n);
4061                  }
4062 <                r[i++] = it.next();
4062 >                r[i++] = e;
4063              }
4064              return (i == n) ? r : Arrays.copyOf(r, i);
4065          }
4066  
4067 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4067 >        public final <T> T[] toArray(T[] a) {
4068              long sz = map.mappingCount();
4069 <            if (sz > (long)(MAX_ARRAY_SIZE))
4069 >            if (sz > MAX_ARRAY_SIZE)
4070                  throw new OutOfMemoryError(oomeMsg);
4071              int m = (int)sz;
4072              T[] r = (a.length >= m) ? a :
# Line 4014 | Line 4074 | public class ConcurrentHashMap<K, V>
4074                  .newInstance(a.getClass().getComponentType(), m);
4075              int n = r.length;
4076              int i = 0;
4077 <            Iterator<?> it = iterator();
4018 <            while (it.hasNext()) {
4077 >            for (E e : this) {
4078                  if (i == n) {
4079                      if (n >= MAX_ARRAY_SIZE)
4080                          throw new OutOfMemoryError(oomeMsg);
# Line 4025 | Line 4084 | public class ConcurrentHashMap<K, V>
4084                          n += (n >>> 1) + 1;
4085                      r = Arrays.copyOf(r, n);
4086                  }
4087 <                r[i++] = (T)it.next();
4087 >                r[i++] = (T)e;
4088              }
4089              if (a == r && i < n) {
4090                  r[i] = null; // null-terminate
# Line 4034 | Line 4093 | public class ConcurrentHashMap<K, V>
4093              return (i == n) ? r : Arrays.copyOf(r, i);
4094          }
4095  
4096 <        public final int hashCode() {
4097 <            int h = 0;
4098 <            for (Iterator<?> it = iterator(); it.hasNext();)
4099 <                h += it.next().hashCode();
4100 <            return h;
4101 <        }
4102 <
4096 >        /**
4097 >         * Returns a string representation of this collection.
4098 >         * The string representation consists of the string representations
4099 >         * of the collection's elements in the order they are returned by
4100 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4101 >         * Adjacent elements are separated by the characters {@code ", "}
4102 >         * (comma and space).  Elements are converted to strings as by
4103 >         * {@link String#valueOf(Object)}.
4104 >         *
4105 >         * @return a string representation of this collection
4106 >         */
4107          public final String toString() {
4108              StringBuilder sb = new StringBuilder();
4109              sb.append('[');
4110 <            Iterator<?> it = iterator();
4110 >            Iterator<E> it = iterator();
4111              if (it.hasNext()) {
4112                  for (;;) {
4113                      Object e = it.next();
# Line 4059 | Line 4122 | public class ConcurrentHashMap<K, V>
4122  
4123          public final boolean containsAll(Collection<?> c) {
4124              if (c != this) {
4125 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4063 <                    Object e = it.next();
4125 >                for (Object e : c) {
4126                      if (e == null || !contains(e))
4127                          return false;
4128                  }
# Line 4070 | Line 4132 | public class ConcurrentHashMap<K, V>
4132  
4133          public final boolean removeAll(Collection<?> c) {
4134              boolean modified = false;
4135 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4135 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4136                  if (c.contains(it.next())) {
4137                      it.remove();
4138                      modified = true;
# Line 4081 | Line 4143 | public class ConcurrentHashMap<K, V>
4143  
4144          public final boolean retainAll(Collection<?> c) {
4145              boolean modified = false;
4146 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4146 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4147                  if (!c.contains(it.next())) {
4148                      it.remove();
4149                      modified = true;
# Line 4095 | Line 4157 | public class ConcurrentHashMap<K, V>
4157      /**
4158       * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4159       * which additions may optionally be enabled by mapping to a
4160 <     * common value.  This class cannot be directly instantiated. See
4161 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4162 <     * {@link #newKeySet(int)}.
4160 >     * common value.  This class cannot be directly instantiated.
4161 >     * See {@link #keySet() keySet()},
4162 >     * {@link #keySet(Object) keySet(V)},
4163 >     * {@link #newKeySet() newKeySet()},
4164 >     * {@link #newKeySet(int) newKeySet(int)}.
4165       */
4166 <    public static class KeySetView<K,V> extends CHMView<K,V> implements Set<K>, java.io.Serializable {
4166 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4167 >        implements Set<K>, java.io.Serializable {
4168          private static final long serialVersionUID = 7249069246763182397L;
4169          private final V value;
4170 <        KeySetView(ConcurrentHashMap<K, V> map, V value) {  // non-public
4170 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4171              super(map);
4172              this.value = value;
4173          }
# Line 4112 | Line 4177 | public class ConcurrentHashMap<K, V>
4177           * or {@code null} if additions are not supported.
4178           *
4179           * @return the default mapped value for additions, or {@code null}
4180 <         * if not supported.
4180 >         * if not supported
4181           */
4182          public V getMappedValue() { return value; }
4183  
4184 <        // implement Set API
4185 <
4184 >        /**
4185 >         * {@inheritDoc}
4186 >         * @throws NullPointerException if the specified key is null
4187 >         */
4188          public boolean contains(Object o) { return map.containsKey(o); }
4122        public boolean remove(Object o)   { return map.remove(o) != null; }
4189  
4190          /**
4191 <         * Returns a "weakly consistent" iterator that will never
4192 <         * throw {@link ConcurrentModificationException}, and
4193 <         * guarantees to traverse elements as they existed upon
4194 <         * construction of the iterator, and may (but is not
4195 <         * guaranteed to) reflect any modifications subsequent to
4196 <         * construction.
4191 >         * Removes the key from this map view, by removing the key (and its
4192 >         * corresponding value) from the backing map.  This method does
4193 >         * nothing if the key is not in the map.
4194 >         *
4195 >         * @param  o the key to be removed from the backing map
4196 >         * @return {@code true} if the backing map contained the specified key
4197 >         * @throws NullPointerException if the specified key is null
4198 >         */
4199 >        public boolean remove(Object o) { return map.remove(o) != null; }
4200 >
4201 >        /**
4202 >         * @return an iterator over the keys of the backing map
4203 >         */
4204 >        public Iterator<K> iterator() {
4205 >            Node<K,V>[] t;
4206 >            ConcurrentHashMap<K,V> m = map;
4207 >            int f = (t = m.table) == null ? 0 : t.length;
4208 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4209 >        }
4210 >
4211 >        /**
4212 >         * Adds the specified key to this set view by mapping the key to
4213 >         * the default mapped value in the backing map, if defined.
4214           *
4215 <         * @return an iterator over the keys of this map
4215 >         * @param e key to be added
4216 >         * @return {@code true} if this set changed as a result of the call
4217 >         * @throws NullPointerException if the specified key is null
4218 >         * @throws UnsupportedOperationException if no default mapped value
4219 >         * for additions was provided
4220           */
4134        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4221          public boolean add(K e) {
4222              V v;
4223              if ((v = value) == null)
4224                  throw new UnsupportedOperationException();
4225 <            if (e == null)
4140 <                throw new NullPointerException();
4141 <            return map.internalPutIfAbsent(e, v) == null;
4225 >            return map.internalPut(e, v, true) == null;
4226          }
4227 +
4228 +        /**
4229 +         * Adds all of the elements in the specified collection to this set,
4230 +         * as if by calling {@link #add} on each one.
4231 +         *
4232 +         * @param c the elements to be inserted into this set
4233 +         * @return {@code true} if this set changed as a result of the call
4234 +         * @throws NullPointerException if the collection or any of its
4235 +         * elements are {@code null}
4236 +         * @throws UnsupportedOperationException if no default mapped value
4237 +         * for additions was provided
4238 +         */
4239          public boolean addAll(Collection<? extends K> c) {
4240              boolean added = false;
4241              V v;
4242              if ((v = value) == null)
4243                  throw new UnsupportedOperationException();
4244              for (K e : c) {
4245 <                if (e == null)
4150 <                    throw new NullPointerException();
4151 <                if (map.internalPutIfAbsent(e, v) == null)
4245 >                if (map.internalPut(e, v, true) == null)
4246                      added = true;
4247              }
4248              return added;
4249          }
4250 +
4251 +        public int hashCode() {
4252 +            int h = 0;
4253 +            for (K e : this)
4254 +                h += e.hashCode();
4255 +            return h;
4256 +        }
4257 +
4258          public boolean equals(Object o) {
4259              Set<?> c;
4260              return ((o instanceof Set) &&
# Line 4160 | Line 4262 | public class ConcurrentHashMap<K, V>
4262                       (containsAll(c) && c.containsAll(this))));
4263          }
4264  
4265 <        /**
4266 <         * Performs the given action for each key.
4267 <         *
4268 <         * @param action the action
4269 <         */
4270 <        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();
4265 >        public Spliterator<K> spliterator() {
4266 >            Node<K,V>[] t;
4267 >            ConcurrentHashMap<K,V> m = map;
4268 >            long n = m.sumCount();
4269 >            int f = (t = m.table) == null ? 0 : t.length;
4270 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4271          }
4272  
4273 <        /**
4274 <         * Returns the result of accumulating the given transformation
4275 <         * of all keys using the given reducer to combine values, and
4276 <         * the given basis as an identity value.
4277 <         *
4278 <         * @param transformer a function returning the transformation
4279 <         * for an element
4280 <         * @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();
4273 >        public void forEach(Consumer<? super K> action) {
4274 >            if (action == null) throw new NullPointerException();
4275 >            Node<K,V>[] t;
4276 >            if ((t = map.table) != null) {
4277 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4278 >                for (Node<K,V> p; (p = it.advance()) != null; )
4279 >                    action.accept((K)p.key);
4280 >            }
4281          }
4275
4282      }
4283  
4284      /**
4285       * A view of a ConcurrentHashMap as a {@link Collection} of
4286       * values, in which additions are disabled. This class cannot be
4287 <     * 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.
4287 >     * directly instantiated. See {@link #values()}.
4288       */
4289 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4290 <        implements Collection<V> {
4291 <        ValuesView(ConcurrentHashMap<K, V> map)   { super(map); }
4292 <        public final boolean contains(Object o) { return map.containsValue(o); }
4289 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4290 >        implements Collection<V>, java.io.Serializable {
4291 >        private static final long serialVersionUID = 2249069246763182397L;
4292 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4293 >        public final boolean contains(Object o) {
4294 >            return map.containsValue(o);
4295 >        }
4296 >
4297          public final boolean remove(Object o) {
4298              if (o != null) {
4299 <                Iterator<V> it = new ValueIterator<K,V>(map);
4296 <                while (it.hasNext()) {
4299 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4300                      if (o.equals(it.next())) {
4301                          it.remove();
4302                          return true;
# Line 4303 | Line 4306 | public class ConcurrentHashMap<K, V>
4306              return false;
4307          }
4308  
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         */
4309          public final Iterator<V> iterator() {
4310 <            return new ValueIterator<K,V>(map);
4310 >            ConcurrentHashMap<K,V> m = map;
4311 >            Node<K,V>[] t;
4312 >            int f = (t = m.table) == null ? 0 : t.length;
4313 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4314          }
4315 +
4316          public final boolean add(V e) {
4317              throw new UnsupportedOperationException();
4318          }
# Line 4323 | Line 4320 | public class ConcurrentHashMap<K, V>
4320              throw new UnsupportedOperationException();
4321          }
4322  
4323 <        /**
4324 <         * Performs the given action for each value.
4325 <         *
4326 <         * @param action the action
4327 <         */
4328 <        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();
4323 >        public Spliterator<V> spliterator() {
4324 >            Node<K,V>[] t;
4325 >            ConcurrentHashMap<K,V> m = map;
4326 >            long n = m.sumCount();
4327 >            int f = (t = m.table) == null ? 0 : t.length;
4328 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4329          }
4330  
4331 <        /**
4332 <         * Returns the result of accumulating the given transformation
4333 <         * of all values using the given reducer to combine values,
4334 <         * and the given basis as an identity value.
4335 <         *
4336 <         * @param transformer a function returning the transformation
4337 <         * for an element
4338 <         * @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();
4331 >        public void forEach(Consumer<? super V> action) {
4332 >            if (action == null) throw new NullPointerException();
4333 >            Node<K,V>[] t;
4334 >            if ((t = map.table) != null) {
4335 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4336 >                for (Node<K,V> p; (p = it.advance()) != null; )
4337 >                    action.accept(p.val);
4338 >            }
4339          }
4454
4340      }
4341  
4342      /**
4343       * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4344       * entries.  This class cannot be directly instantiated. See
4345 <     * {@link #entrySet}.
4345 >     * {@link #entrySet()}.
4346       */
4347 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4348 <        implements Set<Map.Entry<K,V>> {
4349 <        EntrySetView(ConcurrentHashMap<K, V> map) { super(map); }
4350 <        public final boolean contains(Object o) {
4347 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4348 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4349 >        private static final long serialVersionUID = 2249069246763182397L;
4350 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4351 >
4352 >        public boolean contains(Object o) {
4353              Object k, v, r; Map.Entry<?,?> e;
4354              return ((o instanceof Map.Entry) &&
4355                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4470 | Line 4357 | public class ConcurrentHashMap<K, V>
4357                      (v = e.getValue()) != null &&
4358                      (v == r || v.equals(r)));
4359          }
4360 <        public final boolean remove(Object o) {
4360 >
4361 >        public boolean remove(Object o) {
4362              Object k, v; Map.Entry<?,?> e;
4363              return ((o instanceof Map.Entry) &&
4364                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4479 | Line 4367 | public class ConcurrentHashMap<K, V>
4367          }
4368  
4369          /**
4370 <         * 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
4370 >         * @return an iterator over the entries of the backing map
4371           */
4372 <        public final Iterator<Map.Entry<K,V>> iterator() {
4373 <            return new EntryIterator<K,V>(map);
4372 >        public Iterator<Map.Entry<K,V>> iterator() {
4373 >            ConcurrentHashMap<K,V> m = map;
4374 >            Node<K,V>[] t;
4375 >            int f = (t = m.table) == null ? 0 : t.length;
4376 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4377          }
4378  
4379 <        public final boolean add(Entry<K,V> e) {
4380 <            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;
4379 >        public boolean add(Entry<K,V> e) {
4380 >            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4381          }
4382 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4382 >
4383 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4384              boolean added = false;
4385              for (Entry<K,V> e : c) {
4386                  if (add(e))
# Line 4507 | Line 4388 | public class ConcurrentHashMap<K, V>
4388              }
4389              return added;
4390          }
4391 <        public boolean equals(Object o) {
4391 >
4392 >        public final int hashCode() {
4393 >            int h = 0;
4394 >            Node<K,V>[] t;
4395 >            if ((t = map.table) != null) {
4396 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4397 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4398 >                    h += p.hashCode();
4399 >                }
4400 >            }
4401 >            return h;
4402 >        }
4403 >
4404 >        public final boolean equals(Object o) {
4405              Set<?> c;
4406              return ((o instanceof Set) &&
4407                      ((c = (Set<?>)o) == this ||
4408                       (containsAll(c) && c.containsAll(this))));
4409          }
4410  
4411 <        /**
4412 <         * Performs the given action for each entry.
4413 <         *
4414 <         * @param action the action
4415 <         */
4416 <        public void forEach(Action<Map.Entry<K,V>> action) {
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);
4411 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4412 >            Node<K,V>[] t;
4413 >            ConcurrentHashMap<K,V> m = map;
4414 >            long n = m.sumCount();
4415 >            int f = (t = m.table) == null ? 0 : t.length;
4416 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4417          }
4418  
4419 <        /**
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) {
4419 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4420              if (action == null) throw new NullPointerException();
4421 <            return new ForEachEntryTask<K,V>(map, null, -1, null, action);
4422 <        }
4423 <
4424 <        /**
4425 <         * Returns a task that when invoked, perform the given action
4426 <         * 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);
4421 >            Node<K,V>[] t;
4422 >            if ((t = map.table) != null) {
4423 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4424 >                for (Node<K,V> p; (p = it.advance()) != null; )
4425 >                    action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
4426 >            }
4427          }
4428  
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        }
4429      }
4430  
4431      // -------------------------------------------------------
4432  
4433      /**
4434 <     * Base for FJ tasks for bulk operations. This adds a variant of
4435 <     * 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
4434 >     * Base class for bulk tasks. Repeats some fields and code from
4435 >     * class Traverser, because we need to subclass CountedCompleter.
4436       */
4437 <    @SuppressWarnings("serial") static abstract class BulkAction<K,V,R> extends BulkTask<K,V,R> {
4438 <        BulkAction<K,V,?> nextTask;
4439 <        BulkAction(ConcurrentHashMap<K,V> map, BulkTask<K,V,?> parent,
4440 <                   int batch, BulkAction<K,V,?> nextTask) {
4441 <            super(map, parent, batch);
4442 <            this.nextTask = nextTask;
4437 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4438 >        Node<K,V>[] tab;        // same as Traverser
4439 >        Node<K,V> next;
4440 >        int index;
4441 >        int baseIndex;
4442 >        int baseLimit;
4443 >        final int baseSize;
4444 >        int batch;              // split control
4445 >
4446 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4447 >            super(par);
4448 >            this.batch = b;
4449 >            this.index = this.baseIndex = i;
4450 >            if ((this.tab = t) == null)
4451 >                this.baseSize = this.baseLimit = 0;
4452 >            else if (par == null)
4453 >                this.baseSize = this.baseLimit = t.length;
4454 >            else {
4455 >                this.baseLimit = f;
4456 >                this.baseSize = par.baseSize;
4457 >            }
4458          }
4459  
4460          /**
4461 <         * 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.
4461 >         * Same as Traverser version
4462           */
4463 <        final void tryComplete(BulkAction<K,V,?> subtasks) {
4464 <            BulkTask<K,V,?> a = this, s = a;
4465 <            for (int c;;) {
4466 <                if ((c = a.pending) == 0) {
4467 <                    if ((a = (s = a).parent) == null) {
4468 <                        s.quietlyComplete();
4469 <                        break;
4470 <                    }
4471 <                }
4472 <                else if (a.casPending(c, c - 1)) {
4473 <                    if (subtasks != null && !inForkJoinPool()) {
4474 <                        while ((s = a.parent) != null)
4475 <                            a = s;
4476 <                        while (!a.isDone()) {
4477 <                            BulkAction<K,V,?> next = subtasks.nextTask;
4478 <                            if (subtasks.tryUnfork())
4479 <                                subtasks.exec();
4480 <                            if ((subtasks = next) == null)
5461 <                                break;
5462 <                        }
4463 >        final Node<K,V> advance() {
4464 >            Node<K,V> e;
4465 >            if ((e = next) != null)
4466 >                e = e.next;
4467 >            for (;;) {
4468 >                Node<K,V>[] t; int i, n; Object ek;
4469 >                if (e != null)
4470 >                    return next = e;
4471 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4472 >                    (n = t.length) <= (i = index) || i < 0)
4473 >                    return next = null;
4474 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4475 >                    if ((ek = e.key) instanceof TreeBin)
4476 >                        e = ((TreeBin<K,V>)ek).first;
4477 >                    else {
4478 >                        tab = (Node<K,V>[])ek;
4479 >                        e = null;
4480 >                        continue;
4481                      }
5464                    break;
4482                  }
4483 +                if ((index += baseSize) >= n)
4484 +                    index = ++baseIndex;
4485              }
4486          }
5468
4487      }
4488  
4489      /*
4490       * Task classes. Coded in a regular but ugly format/style to
4491       * simplify checks that each variant differs in the right way from
4492 <     * others.
4492 >     * others. The null screenings exist because compilers cannot tell
4493 >     * that we've already null-checked task arguments, so we force
4494 >     * simplest hoisted bypass to help avoid convoluted traps.
4495       */
4496  
4497 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4498 <        extends BulkAction<K,V,Void> {
4499 <        final Action<K> action;
4497 >    static final class ForEachKeyTask<K,V>
4498 >        extends BulkTask<K,V,Void> {
4499 >        final Consumer<? super K> action;
4500          ForEachKeyTask
4501 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4502 <             ForEachKeyTask<K,V> nextTask,
4503 <             Action<K> action) {
5484 <            super(m, p, b, nextTask);
4501 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4502 >             Consumer<? super K> action) {
4503 >            super(p, b, i, f, t);
4504              this.action = action;
4505          }
4506 <        @SuppressWarnings("unchecked") public final boolean exec() {
4507 <            final Action<K> action = this.action;
4508 <            if (action == null)
4509 <                return abortOnNullFunction();
4510 <            ForEachKeyTask<K,V> subtasks = null;
4511 <            try {
4512 <                int b = batch(), c;
4513 <                while (b > 1 && baseIndex != baseLimit) {
4514 <                    do {} while (!casPending(c = pending, c+1));
4515 <                    (subtasks = new ForEachKeyTask<K,V>
4516 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4517 <                }
4518 <                while (advance() != null)
5500 <                    action.apply((K)nextKey);
5501 <            } catch (Throwable ex) {
5502 <                return tryCompleteComputation(ex);
4506 >        public final void compute() {
4507 >            final Consumer<? super K> action;
4508 >            if ((action = this.action) != null) {
4509 >                for (int i = baseIndex, f, h; batch > 0 &&
4510 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4511 >                    addToPendingCount(1);
4512 >                    new ForEachKeyTask<K,V>
4513 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4514 >                         action).fork();
4515 >                }
4516 >                for (Node<K,V> p; (p = advance()) != null;)
4517 >                    action.accept((K)p.key);
4518 >                propagateCompletion();
4519              }
5504            tryComplete(subtasks);
5505            return false;
4520          }
4521      }
4522  
4523 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4524 <        extends BulkAction<K,V,Void> {
4525 <        final Action<V> action;
4523 >    static final class ForEachValueTask<K,V>
4524 >        extends BulkTask<K,V,Void> {
4525 >        final Consumer<? super V> action;
4526          ForEachValueTask
4527 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4528 <             ForEachValueTask<K,V> nextTask,
4529 <             Action<V> action) {
5516 <            super(m, p, b, nextTask);
4527 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4528 >             Consumer<? super V> action) {
4529 >            super(p, b, i, f, t);
4530              this.action = action;
4531          }
4532 <        @SuppressWarnings("unchecked") public final boolean exec() {
4533 <            final Action<V> action = this.action;
4534 <            if (action == null)
4535 <                return abortOnNullFunction();
4536 <            ForEachValueTask<K,V> subtasks = null;
4537 <            try {
4538 <                int b = batch(), c;
4539 <                while (b > 1 && baseIndex != baseLimit) {
4540 <                    do {} while (!casPending(c = pending, c+1));
4541 <                    (subtasks = new ForEachValueTask<K,V>
4542 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4543 <                }
4544 <                Object v;
5532 <                while ((v = advance()) != null)
5533 <                    action.apply((V)v);
5534 <            } catch (Throwable ex) {
5535 <                return tryCompleteComputation(ex);
4532 >        public final void compute() {
4533 >            final Consumer<? super V> action;
4534 >            if ((action = this.action) != null) {
4535 >                for (int i = baseIndex, f, h; batch > 0 &&
4536 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4537 >                    addToPendingCount(1);
4538 >                    new ForEachValueTask<K,V>
4539 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4540 >                         action).fork();
4541 >                }
4542 >                for (Node<K,V> p; (p = advance()) != null;)
4543 >                    action.accept(p.val);
4544 >                propagateCompletion();
4545              }
5537            tryComplete(subtasks);
5538            return false;
4546          }
4547      }
4548  
4549 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4550 <        extends BulkAction<K,V,Void> {
4551 <        final Action<Entry<K,V>> action;
4549 >    static final class ForEachEntryTask<K,V>
4550 >        extends BulkTask<K,V,Void> {
4551 >        final Consumer<? super Entry<K,V>> action;
4552          ForEachEntryTask
4553 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4554 <             ForEachEntryTask<K,V> nextTask,
4555 <             Action<Entry<K,V>> action) {
5549 <            super(m, p, b, nextTask);
4553 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4554 >             Consumer<? super Entry<K,V>> action) {
4555 >            super(p, b, i, f, t);
4556              this.action = action;
4557          }
4558 <        @SuppressWarnings("unchecked") public final boolean exec() {
4559 <            final Action<Entry<K,V>> action = this.action;
4560 <            if (action == null)
4561 <                return abortOnNullFunction();
4562 <            ForEachEntryTask<K,V> subtasks = null;
4563 <            try {
4564 <                int b = batch(), c;
4565 <                while (b > 1 && baseIndex != baseLimit) {
4566 <                    do {} while (!casPending(c = pending, c+1));
4567 <                    (subtasks = new ForEachEntryTask<K,V>
4568 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4569 <                }
4570 <                Object v;
5565 <                while ((v = advance()) != null)
5566 <                    action.apply(entryFor((K)nextKey, (V)v));
5567 <            } catch (Throwable ex) {
5568 <                return tryCompleteComputation(ex);
4558 >        public final void compute() {
4559 >            final Consumer<? super Entry<K,V>> action;
4560 >            if ((action = this.action) != null) {
4561 >                for (int i = baseIndex, f, h; batch > 0 &&
4562 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4563 >                    addToPendingCount(1);
4564 >                    new ForEachEntryTask<K,V>
4565 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4566 >                         action).fork();
4567 >                }
4568 >                for (Node<K,V> p; (p = advance()) != null; )
4569 >                    action.accept(p);
4570 >                propagateCompletion();
4571              }
5570            tryComplete(subtasks);
5571            return false;
4572          }
4573      }
4574  
4575 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4576 <        extends BulkAction<K,V,Void> {
4577 <        final BiAction<K,V> action;
4575 >    static final class ForEachMappingTask<K,V>
4576 >        extends BulkTask<K,V,Void> {
4577 >        final BiConsumer<? super K, ? super V> action;
4578          ForEachMappingTask
4579 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4580 <             ForEachMappingTask<K,V> nextTask,
4581 <             BiAction<K,V> action) {
5582 <            super(m, p, b, nextTask);
4579 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4580 >             BiConsumer<? super K,? super V> action) {
4581 >            super(p, b, i, f, t);
4582              this.action = action;
4583          }
4584 <        @SuppressWarnings("unchecked") public final boolean exec() {
4585 <            final BiAction<K,V> action = this.action;
4586 <            if (action == null)
4587 <                return abortOnNullFunction();
4588 <            ForEachMappingTask<K,V> subtasks = null;
4589 <            try {
4590 <                int b = batch(), c;
4591 <                while (b > 1 && baseIndex != baseLimit) {
4592 <                    do {} while (!casPending(c = pending, c+1));
4593 <                    (subtasks = new ForEachMappingTask<K,V>
4594 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4595 <                }
4596 <                Object v;
5598 <                while ((v = advance()) != null)
5599 <                    action.apply((K)nextKey, (V)v);
5600 <            } catch (Throwable ex) {
5601 <                return tryCompleteComputation(ex);
4584 >        public final void compute() {
4585 >            final BiConsumer<? super K, ? super V> action;
4586 >            if ((action = this.action) != null) {
4587 >                for (int i = baseIndex, f, h; batch > 0 &&
4588 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4589 >                    addToPendingCount(1);
4590 >                    new ForEachMappingTask<K,V>
4591 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4592 >                         action).fork();
4593 >                }
4594 >                for (Node<K,V> p; (p = advance()) != null; )
4595 >                    action.accept((K)p.key, p.val);
4596 >                propagateCompletion();
4597              }
5603            tryComplete(subtasks);
5604            return false;
4598          }
4599      }
4600  
4601 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4602 <        extends BulkAction<K,V,Void> {
4603 <        final Fun<? super K, ? extends U> transformer;
4604 <        final Action<U> action;
4601 >    static final class ForEachTransformedKeyTask<K,V,U>
4602 >        extends BulkTask<K,V,Void> {
4603 >        final Function<? super K, ? extends U> transformer;
4604 >        final Consumer<? super U> action;
4605          ForEachTransformedKeyTask
4606 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4607 <             ForEachTransformedKeyTask<K,V,U> nextTask,
4608 <             Fun<? super K, ? extends U> transformer,
4609 <             Action<U> action) {
4610 <            super(m, p, b, nextTask);
4611 <            this.transformer = transformer;
4612 <            this.action = action;
4613 <
4614 <        }
4615 <        @SuppressWarnings("unchecked") public final boolean exec() {
4616 <            final Fun<? super K, ? extends U> transformer =
4617 <                this.transformer;
4618 <            final Action<U> action = this.action;
4619 <            if (transformer == null || action == null)
4620 <                return abortOnNullFunction();
4621 <            ForEachTransformedKeyTask<K,V,U> subtasks = null;
4622 <            try {
4623 <                int b = batch(), c;
4624 <                while (b > 1 && baseIndex != baseLimit) {
4625 <                    do {} while (!casPending(c = pending, c+1));
4626 <                    (subtasks = new ForEachTransformedKeyTask<K,V,U>
4627 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
4628 <                }
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);
4606 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4607 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
4608 >            super(p, b, i, f, t);
4609 >            this.transformer = transformer; this.action = action;
4610 >        }
4611 >        public final void compute() {
4612 >            final Function<? super K, ? extends U> transformer;
4613 >            final Consumer<? super U> action;
4614 >            if ((transformer = this.transformer) != null &&
4615 >                (action = this.action) != null) {
4616 >                for (int i = baseIndex, f, h; batch > 0 &&
4617 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4618 >                    addToPendingCount(1);
4619 >                    new ForEachTransformedKeyTask<K,V,U>
4620 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4621 >                         transformer, action).fork();
4622 >                }
4623 >                for (Node<K,V> p; (p = advance()) != null; ) {
4624 >                    U u;
4625 >                    if ((u = transformer.apply((K)p.key)) != null)
4626 >                        action.accept(u);
4627 >                }
4628 >                propagateCompletion();
4629              }
5644            tryComplete(subtasks);
5645            return false;
4630          }
4631      }
4632  
4633 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
4634 <        extends BulkAction<K,V,Void> {
4635 <        final Fun<? super V, ? extends U> transformer;
4636 <        final Action<U> action;
4633 >    static final class ForEachTransformedValueTask<K,V,U>
4634 >        extends BulkTask<K,V,Void> {
4635 >        final Function<? super V, ? extends U> transformer;
4636 >        final Consumer<? super U> action;
4637          ForEachTransformedValueTask
4638 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4639 <             ForEachTransformedValueTask<K,V,U> nextTask,
4640 <             Fun<? super V, ? extends U> transformer,
4641 <             Action<U> action) {
4642 <            super(m, p, b, nextTask);
4643 <            this.transformer = transformer;
4644 <            this.action = action;
4645 <
4646 <        }
4647 <        @SuppressWarnings("unchecked") public final boolean exec() {
4648 <            final Fun<? super V, ? extends U> transformer =
4649 <                this.transformer;
4650 <            final Action<U> action = this.action;
4651 <            if (transformer == null || action == null)
4652 <                return abortOnNullFunction();
4653 <            ForEachTransformedValueTask<K,V,U> subtasks = null;
4654 <            try {
4655 <                int b = batch(), c;
4656 <                while (b > 1 && baseIndex != baseLimit) {
4657 <                    do {} while (!casPending(c = pending, c+1));
4658 <                    (subtasks = new ForEachTransformedValueTask<K,V,U>
4659 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
4660 <                }
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);
4638 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4639 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
4640 >            super(p, b, i, f, t);
4641 >            this.transformer = transformer; this.action = action;
4642 >        }
4643 >        public final void compute() {
4644 >            final Function<? super V, ? extends U> transformer;
4645 >            final Consumer<? super U> action;
4646 >            if ((transformer = this.transformer) != null &&
4647 >                (action = this.action) != null) {
4648 >                for (int i = baseIndex, f, h; batch > 0 &&
4649 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4650 >                    addToPendingCount(1);
4651 >                    new ForEachTransformedValueTask<K,V,U>
4652 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4653 >                         transformer, action).fork();
4654 >                }
4655 >                for (Node<K,V> p; (p = advance()) != null; ) {
4656 >                    U u;
4657 >                    if ((u = transformer.apply(p.val)) != null)
4658 >                        action.accept(u);
4659 >                }
4660 >                propagateCompletion();
4661              }
5685            tryComplete(subtasks);
5686            return false;
4662          }
4663      }
4664  
4665 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
4666 <        extends BulkAction<K,V,Void> {
4667 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
4668 <        final Action<U> action;
4665 >    static final class ForEachTransformedEntryTask<K,V,U>
4666 >        extends BulkTask<K,V,Void> {
4667 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
4668 >        final Consumer<? super U> action;
4669          ForEachTransformedEntryTask
4670 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4671 <             ForEachTransformedEntryTask<K,V,U> nextTask,
4672 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4673 <             Action<U> action) {
4674 <            super(m, p, b, nextTask);
4675 <            this.transformer = transformer;
4676 <            this.action = action;
4677 <
4678 <        }
4679 <        @SuppressWarnings("unchecked") public final boolean exec() {
4680 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
4681 <                this.transformer;
4682 <            final Action<U> action = this.action;
4683 <            if (transformer == null || action == null)
4684 <                return abortOnNullFunction();
4685 <            ForEachTransformedEntryTask<K,V,U> subtasks = null;
4686 <            try {
4687 <                int b = batch(), c;
4688 <                while (b > 1 && baseIndex != baseLimit) {
4689 <                    do {} while (!casPending(c = pending, c+1));
4690 <                    (subtasks = new ForEachTransformedEntryTask<K,V,U>
4691 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
4692 <                }
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);
4670 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4671 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
4672 >            super(p, b, i, f, t);
4673 >            this.transformer = transformer; this.action = action;
4674 >        }
4675 >        public final void compute() {
4676 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
4677 >            final Consumer<? super U> action;
4678 >            if ((transformer = this.transformer) != null &&
4679 >                (action = this.action) != null) {
4680 >                for (int i = baseIndex, f, h; batch > 0 &&
4681 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4682 >                    addToPendingCount(1);
4683 >                    new ForEachTransformedEntryTask<K,V,U>
4684 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4685 >                         transformer, action).fork();
4686 >                }
4687 >                for (Node<K,V> p; (p = advance()) != null; ) {
4688 >                    U u;
4689 >                    if ((u = transformer.apply(p)) != null)
4690 >                        action.accept(u);
4691 >                }
4692 >                propagateCompletion();
4693              }
5726            tryComplete(subtasks);
5727            return false;
4694          }
4695      }
4696  
4697 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
4698 <        extends BulkAction<K,V,Void> {
4699 <        final BiFun<? super K, ? super V, ? extends U> transformer;
4700 <        final Action<U> action;
4697 >    static final class ForEachTransformedMappingTask<K,V,U>
4698 >        extends BulkTask<K,V,Void> {
4699 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
4700 >        final Consumer<? super U> action;
4701          ForEachTransformedMappingTask
4702 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4703 <             ForEachTransformedMappingTask<K,V,U> nextTask,
4704 <             BiFun<? super K, ? super V, ? extends U> transformer,
4705 <             Action<U> action) {
4706 <            super(m, p, b, nextTask);
4707 <            this.transformer = transformer;
4708 <            this.action = action;
4709 <
4710 <        }
4711 <        @SuppressWarnings("unchecked") public final boolean exec() {
4712 <            final BiFun<? super K, ? super V, ? extends U> transformer =
4713 <                this.transformer;
4714 <            final Action<U> action = this.action;
4715 <            if (transformer == null || action == null)
4716 <                return abortOnNullFunction();
4717 <            ForEachTransformedMappingTask<K,V,U> subtasks = null;
4718 <            try {
4719 <                int b = batch(), c;
4720 <                while (b > 1 && baseIndex != baseLimit) {
4721 <                    do {} while (!casPending(c = pending, c+1));
4722 <                    (subtasks = new ForEachTransformedMappingTask<K,V,U>
4723 <                     (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);
4702 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4703 >             BiFunction<? super K, ? super V, ? extends U> transformer,
4704 >             Consumer<? super U> action) {
4705 >            super(p, b, i, f, t);
4706 >            this.transformer = transformer; this.action = action;
4707 >        }
4708 >        public final void compute() {
4709 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
4710 >            final Consumer<? super U> action;
4711 >            if ((transformer = this.transformer) != null &&
4712 >                (action = this.action) != null) {
4713 >                for (int i = baseIndex, f, h; batch > 0 &&
4714 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4715 >                    addToPendingCount(1);
4716 >                    new ForEachTransformedMappingTask<K,V,U>
4717 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4718 >                         transformer, action).fork();
4719 >                }
4720 >                for (Node<K,V> p; (p = advance()) != null; ) {
4721 >                    U u;
4722 >                    if ((u = transformer.apply((K)p.key, p.val)) != null)
4723 >                        action.accept(u);
4724                  }
4725 <            } catch (Throwable ex) {
5765 <                return tryCompleteComputation(ex);
4725 >                propagateCompletion();
4726              }
5767            tryComplete(subtasks);
5768            return false;
4727          }
4728      }
4729  
4730 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
4731 <        extends BulkAction<K,V,U> {
4732 <        final Fun<? super K, ? extends U> searchFunction;
4730 >    static final class SearchKeysTask<K,V,U>
4731 >        extends BulkTask<K,V,U> {
4732 >        final Function<? super K, ? extends U> searchFunction;
4733          final AtomicReference<U> result;
4734          SearchKeysTask
4735 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4736 <             SearchKeysTask<K,V,U> nextTask,
5779 <             Fun<? super K, ? extends U> searchFunction,
4735 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4736 >             Function<? super K, ? extends U> searchFunction,
4737               AtomicReference<U> result) {
4738 <            super(m, p, b, nextTask);
4738 >            super(p, b, i, f, t);
4739              this.searchFunction = searchFunction; this.result = result;
4740          }
4741 <        @SuppressWarnings("unchecked") public final boolean exec() {
4742 <            AtomicReference<U> result = this.result;
4743 <            final Fun<? super K, ? extends U> searchFunction =
4744 <                this.searchFunction;
4745 <            if (searchFunction == null || result == null)
4746 <                return abortOnNullFunction();
4747 <            SearchKeysTask<K,V,U> subtasks = null;
4748 <            try {
4749 <                int b = batch(), c;
4750 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4751 <                    do {} while (!casPending(c = pending, c+1));
4752 <                    (subtasks = new SearchKeysTask<K,V,U>
4753 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
4754 <                }
4755 <                U u;
4756 <                while (result.get() == null && advance() != null) {
4757 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
4741 >        public final U getRawResult() { return result.get(); }
4742 >        public final void compute() {
4743 >            final Function<? super K, ? extends U> searchFunction;
4744 >            final AtomicReference<U> result;
4745 >            if ((searchFunction = this.searchFunction) != null &&
4746 >                (result = this.result) != null) {
4747 >                for (int i = baseIndex, f, h; batch > 0 &&
4748 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4749 >                    if (result.get() != null)
4750 >                        return;
4751 >                    addToPendingCount(1);
4752 >                    new SearchKeysTask<K,V,U>
4753 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4754 >                         searchFunction, result).fork();
4755 >                }
4756 >                while (result.get() == null) {
4757 >                    U u;
4758 >                    Node<K,V> p;
4759 >                    if ((p = advance()) == null) {
4760 >                        propagateCompletion();
4761 >                        break;
4762 >                    }
4763 >                    if ((u = searchFunction.apply((K)p.key)) != null) {
4764                          if (result.compareAndSet(null, u))
4765 <                            tryCompleteComputation(null);
4765 >                            quietlyCompleteRoot();
4766                          break;
4767                      }
4768                  }
5806            } catch (Throwable ex) {
5807                return tryCompleteComputation(ex);
4769              }
5809            tryComplete(subtasks);
5810            return false;
4770          }
5812        public final U getRawResult() { return result.get(); }
4771      }
4772  
4773 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
4774 <        extends BulkAction<K,V,U> {
4775 <        final Fun<? super V, ? extends U> searchFunction;
4773 >    static final class SearchValuesTask<K,V,U>
4774 >        extends BulkTask<K,V,U> {
4775 >        final Function<? super V, ? extends U> searchFunction;
4776          final AtomicReference<U> result;
4777          SearchValuesTask
4778 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4779 <             SearchValuesTask<K,V,U> nextTask,
5822 <             Fun<? super V, ? extends U> searchFunction,
4778 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4779 >             Function<? super V, ? extends U> searchFunction,
4780               AtomicReference<U> result) {
4781 <            super(m, p, b, nextTask);
4781 >            super(p, b, i, f, t);
4782              this.searchFunction = searchFunction; this.result = result;
4783          }
4784 <        @SuppressWarnings("unchecked") public final boolean exec() {
4785 <            AtomicReference<U> result = this.result;
4786 <            final Fun<? super V, ? extends U> searchFunction =
4787 <                this.searchFunction;
4788 <            if (searchFunction == null || result == null)
4789 <                return abortOnNullFunction();
4790 <            SearchValuesTask<K,V,U> subtasks = null;
4791 <            try {
4792 <                int b = batch(), c;
4793 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4794 <                    do {} while (!casPending(c = pending, c+1));
4795 <                    (subtasks = new SearchValuesTask<K,V,U>
4796 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
4797 <                }
4798 <                Object v; U u;
4799 <                while (result.get() == null && (v = advance()) != null) {
4800 <                    if ((u = searchFunction.apply((V)v)) != null) {
4784 >        public final U getRawResult() { return result.get(); }
4785 >        public final void compute() {
4786 >            final Function<? super V, ? extends U> searchFunction;
4787 >            final AtomicReference<U> result;
4788 >            if ((searchFunction = this.searchFunction) != null &&
4789 >                (result = this.result) != null) {
4790 >                for (int i = baseIndex, f, h; batch > 0 &&
4791 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4792 >                    if (result.get() != null)
4793 >                        return;
4794 >                    addToPendingCount(1);
4795 >                    new SearchValuesTask<K,V,U>
4796 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4797 >                         searchFunction, result).fork();
4798 >                }
4799 >                while (result.get() == null) {
4800 >                    U u;
4801 >                    Node<K,V> p;
4802 >                    if ((p = advance()) == null) {
4803 >                        propagateCompletion();
4804 >                        break;
4805 >                    }
4806 >                    if ((u = searchFunction.apply(p.val)) != null) {
4807                          if (result.compareAndSet(null, u))
4808 <                            tryCompleteComputation(null);
4808 >                            quietlyCompleteRoot();
4809                          break;
4810                      }
4811                  }
5849            } catch (Throwable ex) {
5850                return tryCompleteComputation(ex);
4812              }
5852            tryComplete(subtasks);
5853            return false;
4813          }
5855        public final U getRawResult() { return result.get(); }
4814      }
4815  
4816 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
4817 <        extends BulkAction<K,V,U> {
4818 <        final Fun<Entry<K,V>, ? extends U> searchFunction;
4816 >    static final class SearchEntriesTask<K,V,U>
4817 >        extends BulkTask<K,V,U> {
4818 >        final Function<Entry<K,V>, ? extends U> searchFunction;
4819          final AtomicReference<U> result;
4820          SearchEntriesTask
4821 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4822 <             SearchEntriesTask<K,V,U> nextTask,
5865 <             Fun<Entry<K,V>, ? extends U> searchFunction,
4821 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4822 >             Function<Entry<K,V>, ? extends U> searchFunction,
4823               AtomicReference<U> result) {
4824 <            super(m, p, b, nextTask);
4824 >            super(p, b, i, f, t);
4825              this.searchFunction = searchFunction; this.result = result;
4826          }
4827 <        @SuppressWarnings("unchecked") public final boolean exec() {
4828 <            AtomicReference<U> result = this.result;
4829 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
4830 <                this.searchFunction;
4831 <            if (searchFunction == null || result == null)
4832 <                return abortOnNullFunction();
4833 <            SearchEntriesTask<K,V,U> subtasks = null;
4834 <            try {
4835 <                int b = batch(), c;
4836 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4837 <                    do {} while (!casPending(c = pending, c+1));
4838 <                    (subtasks = new SearchEntriesTask<K,V,U>
4839 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
4840 <                }
4841 <                Object v; U u;
4842 <                while (result.get() == null && (v = advance()) != null) {
4843 <                    if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
4844 <                        if (result.compareAndSet(null, u))
4845 <                            tryCompleteComputation(null);
4827 >        public final U getRawResult() { return result.get(); }
4828 >        public final void compute() {
4829 >            final Function<Entry<K,V>, ? extends U> searchFunction;
4830 >            final AtomicReference<U> result;
4831 >            if ((searchFunction = this.searchFunction) != null &&
4832 >                (result = this.result) != null) {
4833 >                for (int i = baseIndex, f, h; batch > 0 &&
4834 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4835 >                    if (result.get() != null)
4836 >                        return;
4837 >                    addToPendingCount(1);
4838 >                    new SearchEntriesTask<K,V,U>
4839 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4840 >                         searchFunction, result).fork();
4841 >                }
4842 >                while (result.get() == null) {
4843 >                    U u;
4844 >                    Node<K,V> p;
4845 >                    if ((p = advance()) == null) {
4846 >                        propagateCompletion();
4847                          break;
4848                      }
4849 +                    if ((u = searchFunction.apply(p)) != null) {
4850 +                        if (result.compareAndSet(null, u))
4851 +                            quietlyCompleteRoot();
4852 +                        return;
4853 +                    }
4854                  }
5892            } catch (Throwable ex) {
5893                return tryCompleteComputation(ex);
4855              }
5895            tryComplete(subtasks);
5896            return false;
4856          }
5898        public final U getRawResult() { return result.get(); }
4857      }
4858  
4859 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
4860 <        extends BulkAction<K,V,U> {
4861 <        final BiFun<? super K, ? super V, ? extends U> searchFunction;
4859 >    static final class SearchMappingsTask<K,V,U>
4860 >        extends BulkTask<K,V,U> {
4861 >        final BiFunction<? super K, ? super V, ? extends U> searchFunction;
4862          final AtomicReference<U> result;
4863          SearchMappingsTask
4864 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4865 <             SearchMappingsTask<K,V,U> nextTask,
5908 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
4864 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4865 >             BiFunction<? super K, ? super V, ? extends U> searchFunction,
4866               AtomicReference<U> result) {
4867 <            super(m, p, b, nextTask);
4867 >            super(p, b, i, f, t);
4868              this.searchFunction = searchFunction; this.result = result;
4869          }
4870 <        @SuppressWarnings("unchecked") public final boolean exec() {
4871 <            AtomicReference<U> result = this.result;
4872 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
4873 <                this.searchFunction;
4874 <            if (searchFunction == null || result == null)
4875 <                return abortOnNullFunction();
4876 <            SearchMappingsTask<K,V,U> subtasks = null;
4877 <            try {
4878 <                int b = batch(), c;
4879 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4880 <                    do {} while (!casPending(c = pending, c+1));
4881 <                    (subtasks = new SearchMappingsTask<K,V,U>
4882 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
4883 <                }
4884 <                Object v; U u;
4885 <                while (result.get() == null && (v = advance()) != null) {
4886 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
4870 >        public final U getRawResult() { return result.get(); }
4871 >        public final void compute() {
4872 >            final BiFunction<? super K, ? super V, ? extends U> searchFunction;
4873 >            final AtomicReference<U> result;
4874 >            if ((searchFunction = this.searchFunction) != null &&
4875 >                (result = this.result) != null) {
4876 >                for (int i = baseIndex, f, h; batch > 0 &&
4877 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4878 >                    if (result.get() != null)
4879 >                        return;
4880 >                    addToPendingCount(1);
4881 >                    new SearchMappingsTask<K,V,U>
4882 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4883 >                         searchFunction, result).fork();
4884 >                }
4885 >                while (result.get() == null) {
4886 >                    U u;
4887 >                    Node<K,V> p;
4888 >                    if ((p = advance()) == null) {
4889 >                        propagateCompletion();
4890 >                        break;
4891 >                    }
4892 >                    if ((u = searchFunction.apply((K)p.key, p.val)) != null) {
4893                          if (result.compareAndSet(null, u))
4894 <                            tryCompleteComputation(null);
4894 >                            quietlyCompleteRoot();
4895                          break;
4896                      }
4897                  }
5935            } catch (Throwable ex) {
5936                return tryCompleteComputation(ex);
4898              }
5938            tryComplete(subtasks);
5939            return false;
4899          }
5941        public final U getRawResult() { return result.get(); }
4900      }
4901  
4902 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
4902 >    static final class ReduceKeysTask<K,V>
4903          extends BulkTask<K,V,K> {
4904 <        final BiFun<? super K, ? super K, ? extends K> reducer;
4904 >        final BiFunction<? super K, ? super K, ? extends K> reducer;
4905          K result;
4906          ReduceKeysTask<K,V> rights, nextRight;
4907          ReduceKeysTask
4908 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4908 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4909               ReduceKeysTask<K,V> nextRight,
4910 <             BiFun<? super K, ? super K, ? extends K> reducer) {
4911 <            super(m, p, b); this.nextRight = nextRight;
4910 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
4911 >            super(p, b, i, f, t); this.nextRight = nextRight;
4912              this.reducer = reducer;
4913          }
4914 <        @SuppressWarnings("unchecked") public final boolean exec() {
4915 <            final BiFun<? super K, ? super K, ? extends K> reducer =
4916 <                this.reducer;
4917 <            if (reducer == null)
4918 <                return abortOnNullFunction();
4919 <            try {
4920 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5963 <                    do {} while (!casPending(c = pending, c+1));
4914 >        public final K getRawResult() { return result; }
4915 >        public final void compute() {
4916 >            final BiFunction<? super K, ? super K, ? extends K> reducer;
4917 >            if ((reducer = this.reducer) != null) {
4918 >                for (int i = baseIndex, f, h; batch > 0 &&
4919 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4920 >                    addToPendingCount(1);
4921                      (rights = new ReduceKeysTask<K,V>
4922 <                     (map, this, b >>>= 1, rights, reducer)).fork();
4922 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
4923 >                      rights, reducer)).fork();
4924                  }
4925                  K r = null;
4926 <                while (advance() != null) {
4927 <                    K u = (K)nextKey;
4928 <                    r = (r == null) ? u : reducer.apply(r, u);
4926 >                for (Node<K,V> p; (p = advance()) != null; ) {
4927 >                    K u = (K)p.key;
4928 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
4929                  }
4930                  result = r;
4931 <                for (ReduceKeysTask<K,V> t = this, s;;) {
4932 <                    int c; BulkTask<K,V,?> par; K tr, sr;
4933 <                    if ((c = t.pending) == 0) {
4934 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
4935 <                            if ((sr = s.result) != null)
4936 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
4937 <                        }
4938 <                        if ((par = t.parent) == null ||
4939 <                            !(par instanceof ReduceKeysTask)) {
4940 <                            t.quietlyComplete();
4941 <                            break;
5984 <                        }
5985 <                        t = (ReduceKeysTask<K,V>)par;
4931 >                CountedCompleter<?> c;
4932 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
4933 >                    ReduceKeysTask<K,V>
4934 >                        t = (ReduceKeysTask<K,V>)c,
4935 >                        s = t.rights;
4936 >                    while (s != null) {
4937 >                        K tr, sr;
4938 >                        if ((sr = s.result) != null)
4939 >                            t.result = (((tr = t.result) == null) ? sr :
4940 >                                        reducer.apply(tr, sr));
4941 >                        s = t.rights = s.nextRight;
4942                      }
5987                    else if (t.casPending(c, c - 1))
5988                        break;
4943                  }
5990            } catch (Throwable ex) {
5991                return tryCompleteComputation(ex);
4944              }
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;
4945          }
6002        public final K getRawResult() { return result; }
4946      }
4947  
4948 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
4948 >    static final class ReduceValuesTask<K,V>
4949          extends BulkTask<K,V,V> {
4950 <        final BiFun<? super V, ? super V, ? extends V> reducer;
4950 >        final BiFunction<? super V, ? super V, ? extends V> reducer;
4951          V result;
4952          ReduceValuesTask<K,V> rights, nextRight;
4953          ReduceValuesTask
4954 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4954 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4955               ReduceValuesTask<K,V> nextRight,
4956 <             BiFun<? super V, ? super V, ? extends V> reducer) {
4957 <            super(m, p, b); this.nextRight = nextRight;
4956 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
4957 >            super(p, b, i, f, t); this.nextRight = nextRight;
4958              this.reducer = reducer;
4959          }
4960 <        @SuppressWarnings("unchecked") public final boolean exec() {
4961 <            final BiFun<? super V, ? super V, ? extends V> reducer =
4962 <                this.reducer;
4963 <            if (reducer == null)
4964 <                return abortOnNullFunction();
4965 <            try {
4966 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6024 <                    do {} while (!casPending(c = pending, c+1));
4960 >        public final V getRawResult() { return result; }
4961 >        public final void compute() {
4962 >            final BiFunction<? super V, ? super V, ? extends V> reducer;
4963 >            if ((reducer = this.reducer) != null) {
4964 >                for (int i = baseIndex, f, h; batch > 0 &&
4965 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4966 >                    addToPendingCount(1);
4967                      (rights = new ReduceValuesTask<K,V>
4968 <                     (map, this, b >>>= 1, rights, reducer)).fork();
4968 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
4969 >                      rights, reducer)).fork();
4970                  }
4971                  V r = null;
4972 <                Object v;
4973 <                while ((v = advance()) != null) {
4974 <                    V u = (V)v;
6032 <                    r = (r == null) ? u : reducer.apply(r, u);
4972 >                for (Node<K,V> p; (p = advance()) != null; ) {
4973 >                    V v = p.val;
4974 >                    r = (r == null) ? v : reducer.apply(r, v);
4975                  }
4976                  result = r;
4977 <                for (ReduceValuesTask<K,V> t = this, s;;) {
4978 <                    int c; BulkTask<K,V,?> par; V tr, sr;
4979 <                    if ((c = t.pending) == 0) {
4980 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
4981 <                            if ((sr = s.result) != null)
4982 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
4983 <                        }
4984 <                        if ((par = t.parent) == null ||
4985 <                            !(par instanceof ReduceValuesTask)) {
4986 <                            t.quietlyComplete();
4987 <                            break;
6046 <                        }
6047 <                        t = (ReduceValuesTask<K,V>)par;
4977 >                CountedCompleter<?> c;
4978 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
4979 >                    ReduceValuesTask<K,V>
4980 >                        t = (ReduceValuesTask<K,V>)c,
4981 >                        s = t.rights;
4982 >                    while (s != null) {
4983 >                        V tr, sr;
4984 >                        if ((sr = s.result) != null)
4985 >                            t.result = (((tr = t.result) == null) ? sr :
4986 >                                        reducer.apply(tr, sr));
4987 >                        s = t.rights = s.nextRight;
4988                      }
6049                    else if (t.casPending(c, c - 1))
6050                        break;
4989                  }
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);
4990              }
6062            return false;
4991          }
6064        public final V getRawResult() { return result; }
4992      }
4993  
4994 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
4994 >    static final class ReduceEntriesTask<K,V>
4995          extends BulkTask<K,V,Map.Entry<K,V>> {
4996 <        final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
4996 >        final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
4997          Map.Entry<K,V> result;
4998          ReduceEntriesTask<K,V> rights, nextRight;
4999          ReduceEntriesTask
5000 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5000 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5001               ReduceEntriesTask<K,V> nextRight,
5002 <             BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5003 <            super(m, p, b); this.nextRight = nextRight;
5002 >             BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5003 >            super(p, b, i, f, t); this.nextRight = nextRight;
5004              this.reducer = reducer;
5005          }
5006 <        @SuppressWarnings("unchecked") public final boolean exec() {
5007 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
5008 <                this.reducer;
5009 <            if (reducer == null)
5010 <                return abortOnNullFunction();
5011 <            try {
5012 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6086 <                    do {} while (!casPending(c = pending, c+1));
5006 >        public final Map.Entry<K,V> getRawResult() { return result; }
5007 >        public final void compute() {
5008 >            final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5009 >            if ((reducer = this.reducer) != null) {
5010 >                for (int i = baseIndex, f, h; batch > 0 &&
5011 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5012 >                    addToPendingCount(1);
5013                      (rights = new ReduceEntriesTask<K,V>
5014 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5014 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5015 >                      rights, reducer)).fork();
5016                  }
5017                  Map.Entry<K,V> r = null;
5018 <                Object v;
5019 <                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 <                }
5018 >                for (Node<K,V> p; (p = advance()) != null; )
5019 >                    r = (r == null) ? p : reducer.apply(r, p);
5020                  result = r;
5021 <                for (ReduceEntriesTask<K,V> t = this, s;;) {
5022 <                    int c; BulkTask<K,V,?> par; Map.Entry<K,V> tr, sr;
5023 <                    if ((c = t.pending) == 0) {
5024 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5025 <                            if ((sr = s.result) != null)
5026 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5027 <                        }
5028 <                        if ((par = t.parent) == null ||
5029 <                            !(par instanceof ReduceEntriesTask)) {
5030 <                            t.quietlyComplete();
5031 <                            break;
6108 <                        }
6109 <                        t = (ReduceEntriesTask<K,V>)par;
5021 >                CountedCompleter<?> c;
5022 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5023 >                    ReduceEntriesTask<K,V>
5024 >                        t = (ReduceEntriesTask<K,V>)c,
5025 >                        s = t.rights;
5026 >                    while (s != null) {
5027 >                        Map.Entry<K,V> tr, sr;
5028 >                        if ((sr = s.result) != null)
5029 >                            t.result = (((tr = t.result) == null) ? sr :
5030 >                                        reducer.apply(tr, sr));
5031 >                        s = t.rights = s.nextRight;
5032                      }
6111                    else if (t.casPending(c, c - 1))
6112                        break;
5033                  }
6114            } catch (Throwable ex) {
6115                return tryCompleteComputation(ex);
5034              }
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;
5035          }
6126        public final Map.Entry<K,V> getRawResult() { return result; }
5036      }
5037  
5038 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5038 >    static final class MapReduceKeysTask<K,V,U>
5039          extends BulkTask<K,V,U> {
5040 <        final Fun<? super K, ? extends U> transformer;
5041 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5040 >        final Function<? super K, ? extends U> transformer;
5041 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5042          U result;
5043          MapReduceKeysTask<K,V,U> rights, nextRight;
5044          MapReduceKeysTask
5045 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5045 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5046               MapReduceKeysTask<K,V,U> nextRight,
5047 <             Fun<? super K, ? extends U> transformer,
5048 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5049 <            super(m, p, b); this.nextRight = nextRight;
5047 >             Function<? super K, ? extends U> transformer,
5048 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5049 >            super(p, b, i, f, t); this.nextRight = nextRight;
5050              this.transformer = transformer;
5051              this.reducer = reducer;
5052          }
5053 <        @SuppressWarnings("unchecked") public final boolean exec() {
5054 <            final Fun<? super K, ? extends U> transformer =
5055 <                this.transformer;
5056 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5057 <                this.reducer;
5058 <            if (transformer == null || reducer == null)
5059 <                return abortOnNullFunction();
5060 <            try {
5061 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6153 <                    do {} while (!casPending(c = pending, c+1));
5053 >        public final U getRawResult() { return result; }
5054 >        public final void compute() {
5055 >            final Function<? super K, ? extends U> transformer;
5056 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5057 >            if ((transformer = this.transformer) != null &&
5058 >                (reducer = this.reducer) != null) {
5059 >                for (int i = baseIndex, f, h; batch > 0 &&
5060 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5061 >                    addToPendingCount(1);
5062                      (rights = new MapReduceKeysTask<K,V,U>
5063 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5063 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5064 >                      rights, transformer, reducer)).fork();
5065                  }
5066 <                U r = null, u;
5067 <                while (advance() != null) {
5068 <                    if ((u = transformer.apply((K)nextKey)) != null)
5066 >                U r = null;
5067 >                for (Node<K,V> p; (p = advance()) != null; ) {
5068 >                    U u;
5069 >                    if ((u = transformer.apply((K)p.key)) != null)
5070                          r = (r == null) ? u : reducer.apply(r, u);
5071                  }
5072                  result = r;
5073 <                for (MapReduceKeysTask<K,V,U> t = this, s;;) {
5074 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5075 <                    if ((c = t.pending) == 0) {
5076 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5077 <                            if ((sr = s.result) != null)
5078 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5079 <                        }
5080 <                        if ((par = t.parent) == null ||
5081 <                            !(par instanceof MapReduceKeysTask)) {
5082 <                            t.quietlyComplete();
5083 <                            break;
6174 <                        }
6175 <                        t = (MapReduceKeysTask<K,V,U>)par;
5073 >                CountedCompleter<?> c;
5074 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5075 >                    MapReduceKeysTask<K,V,U>
5076 >                        t = (MapReduceKeysTask<K,V,U>)c,
5077 >                        s = t.rights;
5078 >                    while (s != null) {
5079 >                        U tr, sr;
5080 >                        if ((sr = s.result) != null)
5081 >                            t.result = (((tr = t.result) == null) ? sr :
5082 >                                        reducer.apply(tr, sr));
5083 >                        s = t.rights = s.nextRight;
5084                      }
6177                    else if (t.casPending(c, c - 1))
6178                        break;
5085                  }
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);
5086              }
6190            return false;
5087          }
6192        public final U getRawResult() { return result; }
5088      }
5089  
5090 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5090 >    static final class MapReduceValuesTask<K,V,U>
5091          extends BulkTask<K,V,U> {
5092 <        final Fun<? super V, ? extends U> transformer;
5093 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5092 >        final Function<? super V, ? extends U> transformer;
5093 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5094          U result;
5095          MapReduceValuesTask<K,V,U> rights, nextRight;
5096          MapReduceValuesTask
5097 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5097 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5098               MapReduceValuesTask<K,V,U> nextRight,
5099 <             Fun<? super V, ? extends U> transformer,
5100 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5101 <            super(m, p, b); this.nextRight = nextRight;
5099 >             Function<? super V, ? extends U> transformer,
5100 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5101 >            super(p, b, i, f, t); this.nextRight = nextRight;
5102              this.transformer = transformer;
5103              this.reducer = reducer;
5104          }
5105 <        @SuppressWarnings("unchecked") public final boolean exec() {
5106 <            final Fun<? super V, ? extends U> transformer =
5107 <                this.transformer;
5108 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5109 <                this.reducer;
5110 <            if (transformer == null || reducer == null)
5111 <                return abortOnNullFunction();
5112 <            try {
5113 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6219 <                    do {} while (!casPending(c = pending, c+1));
5105 >        public final U getRawResult() { return result; }
5106 >        public final void compute() {
5107 >            final Function<? super V, ? extends U> transformer;
5108 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5109 >            if ((transformer = this.transformer) != null &&
5110 >                (reducer = this.reducer) != null) {
5111 >                for (int i = baseIndex, f, h; batch > 0 &&
5112 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5113 >                    addToPendingCount(1);
5114                      (rights = new MapReduceValuesTask<K,V,U>
5115 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5115 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5116 >                      rights, transformer, reducer)).fork();
5117                  }
5118 <                U r = null, u;
5119 <                Object v;
5120 <                while ((v = advance()) != null) {
5121 <                    if ((u = transformer.apply((V)v)) != null)
5118 >                U r = null;
5119 >                for (Node<K,V> p; (p = advance()) != null; ) {
5120 >                    U u;
5121 >                    if ((u = transformer.apply(p.val)) != null)
5122                          r = (r == null) ? u : reducer.apply(r, u);
5123                  }
5124                  result = r;
5125 <                for (MapReduceValuesTask<K,V,U> t = this, s;;) {
5126 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5127 <                    if ((c = t.pending) == 0) {
5128 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5129 <                            if ((sr = s.result) != null)
5130 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5131 <                        }
5132 <                        if ((par = t.parent) == null ||
5133 <                            !(par instanceof MapReduceValuesTask)) {
5134 <                            t.quietlyComplete();
5135 <                            break;
6241 <                        }
6242 <                        t = (MapReduceValuesTask<K,V,U>)par;
5125 >                CountedCompleter<?> c;
5126 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5127 >                    MapReduceValuesTask<K,V,U>
5128 >                        t = (MapReduceValuesTask<K,V,U>)c,
5129 >                        s = t.rights;
5130 >                    while (s != null) {
5131 >                        U tr, sr;
5132 >                        if ((sr = s.result) != null)
5133 >                            t.result = (((tr = t.result) == null) ? sr :
5134 >                                        reducer.apply(tr, sr));
5135 >                        s = t.rights = s.nextRight;
5136                      }
6244                    else if (t.casPending(c, c - 1))
6245                        break;
5137                  }
6247            } catch (Throwable ex) {
6248                return tryCompleteComputation(ex);
5138              }
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;
5139          }
6259        public final U getRawResult() { return result; }
5140      }
5141  
5142 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5142 >    static final class MapReduceEntriesTask<K,V,U>
5143          extends BulkTask<K,V,U> {
5144 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5145 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5144 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5145 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5146          U result;
5147          MapReduceEntriesTask<K,V,U> rights, nextRight;
5148          MapReduceEntriesTask
5149 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5149 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5150               MapReduceEntriesTask<K,V,U> nextRight,
5151 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5152 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5153 <            super(m, p, b); this.nextRight = nextRight;
5151 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5152 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5153 >            super(p, b, i, f, t); this.nextRight = nextRight;
5154              this.transformer = transformer;
5155              this.reducer = reducer;
5156          }
5157 <        @SuppressWarnings("unchecked") public final boolean exec() {
5158 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5159 <                this.transformer;
5160 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5161 <                this.reducer;
5162 <            if (transformer == null || reducer == null)
5163 <                return abortOnNullFunction();
5164 <            try {
5165 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6286 <                    do {} while (!casPending(c = pending, c+1));
5157 >        public final U getRawResult() { return result; }
5158 >        public final void compute() {
5159 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5160 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5161 >            if ((transformer = this.transformer) != null &&
5162 >                (reducer = this.reducer) != null) {
5163 >                for (int i = baseIndex, f, h; batch > 0 &&
5164 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5165 >                    addToPendingCount(1);
5166                      (rights = new MapReduceEntriesTask<K,V,U>
5167 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5167 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5168 >                      rights, transformer, reducer)).fork();
5169                  }
5170 <                U r = null, u;
5171 <                Object v;
5172 <                while ((v = advance()) != null) {
5173 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5170 >                U r = null;
5171 >                for (Node<K,V> p; (p = advance()) != null; ) {
5172 >                    U u;
5173 >                    if ((u = transformer.apply(p)) != null)
5174                          r = (r == null) ? u : reducer.apply(r, u);
5175                  }
5176                  result = r;
5177 <                for (MapReduceEntriesTask<K,V,U> t = this, s;;) {
5178 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5179 <                    if ((c = t.pending) == 0) {
5180 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5181 <                            if ((sr = s.result) != null)
5182 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5183 <                        }
5184 <                        if ((par = t.parent) == null ||
5185 <                            !(par instanceof MapReduceEntriesTask)) {
5186 <                            t.quietlyComplete();
5187 <                            break;
6308 <                        }
6309 <                        t = (MapReduceEntriesTask<K,V,U>)par;
5177 >                CountedCompleter<?> c;
5178 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5179 >                    MapReduceEntriesTask<K,V,U>
5180 >                        t = (MapReduceEntriesTask<K,V,U>)c,
5181 >                        s = t.rights;
5182 >                    while (s != null) {
5183 >                        U tr, sr;
5184 >                        if ((sr = s.result) != null)
5185 >                            t.result = (((tr = t.result) == null) ? sr :
5186 >                                        reducer.apply(tr, sr));
5187 >                        s = t.rights = s.nextRight;
5188                      }
6311                    else if (t.casPending(c, c - 1))
6312                        break;
5189                  }
6314            } catch (Throwable ex) {
6315                return tryCompleteComputation(ex);
5190              }
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;
5191          }
6326        public final U getRawResult() { return result; }
5192      }
5193  
5194 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5194 >    static final class MapReduceMappingsTask<K,V,U>
5195          extends BulkTask<K,V,U> {
5196 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5197 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5196 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5197 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5198          U result;
5199          MapReduceMappingsTask<K,V,U> rights, nextRight;
5200          MapReduceMappingsTask
5201 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5201 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5202               MapReduceMappingsTask<K,V,U> nextRight,
5203 <             BiFun<? super K, ? super V, ? extends U> transformer,
5204 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5205 <            super(m, p, b); this.nextRight = nextRight;
5203 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5204 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5205 >            super(p, b, i, f, t); this.nextRight = nextRight;
5206              this.transformer = transformer;
5207              this.reducer = reducer;
5208          }
5209 <        @SuppressWarnings("unchecked") public final boolean exec() {
5210 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5211 <                this.transformer;
5212 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5213 <                this.reducer;
5214 <            if (transformer == null || reducer == null)
5215 <                return abortOnNullFunction();
5216 <            try {
5217 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6353 <                    do {} while (!casPending(c = pending, c+1));
5209 >        public final U getRawResult() { return result; }
5210 >        public final void compute() {
5211 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5212 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5213 >            if ((transformer = this.transformer) != null &&
5214 >                (reducer = this.reducer) != null) {
5215 >                for (int i = baseIndex, f, h; batch > 0 &&
5216 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5217 >                    addToPendingCount(1);
5218                      (rights = new MapReduceMappingsTask<K,V,U>
5219 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5219 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5220 >                      rights, transformer, reducer)).fork();
5221                  }
5222 <                U r = null, u;
5223 <                Object v;
5224 <                while ((v = advance()) != null) {
5225 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5222 >                U r = null;
5223 >                for (Node<K,V> p; (p = advance()) != null; ) {
5224 >                    U u;
5225 >                    if ((u = transformer.apply((K)p.key, p.val)) != null)
5226                          r = (r == null) ? u : reducer.apply(r, u);
5227                  }
5228                  result = r;
5229 <                for (MapReduceMappingsTask<K,V,U> t = this, s;;) {
5230 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5231 <                    if ((c = t.pending) == 0) {
5232 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5233 <                            if ((sr = s.result) != null)
5234 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5235 <                        }
5236 <                        if ((par = t.parent) == null ||
5237 <                            !(par instanceof MapReduceMappingsTask)) {
5238 <                            t.quietlyComplete();
5239 <                            break;
6375 <                        }
6376 <                        t = (MapReduceMappingsTask<K,V,U>)par;
5229 >                CountedCompleter<?> c;
5230 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5231 >                    MapReduceMappingsTask<K,V,U>
5232 >                        t = (MapReduceMappingsTask<K,V,U>)c,
5233 >                        s = t.rights;
5234 >                    while (s != null) {
5235 >                        U tr, sr;
5236 >                        if ((sr = s.result) != null)
5237 >                            t.result = (((tr = t.result) == null) ? sr :
5238 >                                        reducer.apply(tr, sr));
5239 >                        s = t.rights = s.nextRight;
5240                      }
6378                    else if (t.casPending(c, c - 1))
6379                        break;
5241                  }
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);
5242              }
6391            return false;
5243          }
6393        public final U getRawResult() { return result; }
5244      }
5245  
5246 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5246 >    static final class MapReduceKeysToDoubleTask<K,V>
5247          extends BulkTask<K,V,Double> {
5248 <        final ObjectToDouble<? super K> transformer;
5249 <        final DoubleByDoubleToDouble reducer;
5248 >        final ToDoubleFunction<? super K> transformer;
5249 >        final DoubleBinaryOperator reducer;
5250          final double basis;
5251          double result;
5252          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5253          MapReduceKeysToDoubleTask
5254 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5254 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5255               MapReduceKeysToDoubleTask<K,V> nextRight,
5256 <             ObjectToDouble<? super K> transformer,
5256 >             ToDoubleFunction<? super K> transformer,
5257               double basis,
5258 <             DoubleByDoubleToDouble reducer) {
5259 <            super(m, p, b); this.nextRight = nextRight;
5258 >             DoubleBinaryOperator reducer) {
5259 >            super(p, b, i, f, t); this.nextRight = nextRight;
5260              this.transformer = transformer;
5261              this.basis = basis; this.reducer = reducer;
5262          }
5263 <        @SuppressWarnings("unchecked") public final boolean exec() {
5264 <            final ObjectToDouble<? super K> transformer =
5265 <                this.transformer;
5266 <            final DoubleByDoubleToDouble reducer = this.reducer;
5267 <            if (transformer == null || reducer == null)
5268 <                return abortOnNullFunction();
5269 <            try {
5270 <                final double id = this.basis;
5271 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5272 <                    do {} while (!casPending(c = pending, c+1));
5263 >        public final Double getRawResult() { return result; }
5264 >        public final void compute() {
5265 >            final ToDoubleFunction<? super K> transformer;
5266 >            final DoubleBinaryOperator reducer;
5267 >            if ((transformer = this.transformer) != null &&
5268 >                (reducer = this.reducer) != null) {
5269 >                double r = this.basis;
5270 >                for (int i = baseIndex, f, h; batch > 0 &&
5271 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5272 >                    addToPendingCount(1);
5273                      (rights = new MapReduceKeysToDoubleTask<K,V>
5274 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5274 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5275 >                      rights, transformer, r, reducer)).fork();
5276                  }
5277 <                double r = id;
5278 <                while (advance() != null)
6428 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5277 >                for (Node<K,V> p; (p = advance()) != null; )
5278 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)p.key));
5279                  result = r;
5280 <                for (MapReduceKeysToDoubleTask<K,V> t = this, s;;) {
5281 <                    int c; BulkTask<K,V,?> par;
5282 <                    if ((c = t.pending) == 0) {
5283 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5284 <                            t.result = reducer.apply(t.result, s.result);
5285 <                        }
5286 <                        if ((par = t.parent) == null ||
5287 <                            !(par instanceof MapReduceKeysToDoubleTask)) {
6438 <                            t.quietlyComplete();
6439 <                            break;
6440 <                        }
6441 <                        t = (MapReduceKeysToDoubleTask<K,V>)par;
5280 >                CountedCompleter<?> c;
5281 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5282 >                    MapReduceKeysToDoubleTask<K,V>
5283 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
5284 >                        s = t.rights;
5285 >                    while (s != null) {
5286 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5287 >                        s = t.rights = s.nextRight;
5288                      }
6443                    else if (t.casPending(c, c - 1))
6444                        break;
5289                  }
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);
5290              }
6456            return false;
5291          }
6458        public final Double getRawResult() { return result; }
5292      }
5293  
5294 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5294 >    static final class MapReduceValuesToDoubleTask<K,V>
5295          extends BulkTask<K,V,Double> {
5296 <        final ObjectToDouble<? super V> transformer;
5297 <        final DoubleByDoubleToDouble reducer;
5296 >        final ToDoubleFunction<? super V> transformer;
5297 >        final DoubleBinaryOperator reducer;
5298          final double basis;
5299          double result;
5300          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5301          MapReduceValuesToDoubleTask
5302 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5302 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5303               MapReduceValuesToDoubleTask<K,V> nextRight,
5304 <             ObjectToDouble<? super V> transformer,
5304 >             ToDoubleFunction<? super V> transformer,
5305               double basis,
5306 <             DoubleByDoubleToDouble reducer) {
5307 <            super(m, p, b); this.nextRight = nextRight;
5306 >             DoubleBinaryOperator reducer) {
5307 >            super(p, b, i, f, t); this.nextRight = nextRight;
5308              this.transformer = transformer;
5309              this.basis = basis; this.reducer = reducer;
5310          }
5311 <        @SuppressWarnings("unchecked") public final boolean exec() {
5312 <            final ObjectToDouble<? super V> transformer =
5313 <                this.transformer;
5314 <            final DoubleByDoubleToDouble reducer = this.reducer;
5315 <            if (transformer == null || reducer == null)
5316 <                return abortOnNullFunction();
5317 <            try {
5318 <                final double id = this.basis;
5319 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5320 <                    do {} while (!casPending(c = pending, c+1));
5311 >        public final Double getRawResult() { return result; }
5312 >        public final void compute() {
5313 >            final ToDoubleFunction<? super V> transformer;
5314 >            final DoubleBinaryOperator reducer;
5315 >            if ((transformer = this.transformer) != null &&
5316 >                (reducer = this.reducer) != null) {
5317 >                double r = this.basis;
5318 >                for (int i = baseIndex, f, h; batch > 0 &&
5319 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5320 >                    addToPendingCount(1);
5321                      (rights = new MapReduceValuesToDoubleTask<K,V>
5322 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5322 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5323 >                      rights, transformer, r, reducer)).fork();
5324                  }
5325 <                double r = id;
5326 <                Object v;
6493 <                while ((v = advance()) != null)
6494 <                    r = reducer.apply(r, transformer.apply((V)v));
5325 >                for (Node<K,V> p; (p = advance()) != null; )
5326 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5327                  result = r;
5328 <                for (MapReduceValuesToDoubleTask<K,V> t = this, s;;) {
5329 <                    int c; BulkTask<K,V,?> par;
5330 <                    if ((c = t.pending) == 0) {
5331 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5332 <                            t.result = reducer.apply(t.result, s.result);
5333 <                        }
5334 <                        if ((par = t.parent) == null ||
5335 <                            !(par instanceof MapReduceValuesToDoubleTask)) {
6504 <                            t.quietlyComplete();
6505 <                            break;
6506 <                        }
6507 <                        t = (MapReduceValuesToDoubleTask<K,V>)par;
5328 >                CountedCompleter<?> c;
5329 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5330 >                    MapReduceValuesToDoubleTask<K,V>
5331 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
5332 >                        s = t.rights;
5333 >                    while (s != null) {
5334 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5335 >                        s = t.rights = s.nextRight;
5336                      }
6509                    else if (t.casPending(c, c - 1))
6510                        break;
5337                  }
6512            } catch (Throwable ex) {
6513                return tryCompleteComputation(ex);
5338              }
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;
5339          }
6524        public final Double getRawResult() { return result; }
5340      }
5341  
5342 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5342 >    static final class MapReduceEntriesToDoubleTask<K,V>
5343          extends BulkTask<K,V,Double> {
5344 <        final ObjectToDouble<Map.Entry<K,V>> transformer;
5345 <        final DoubleByDoubleToDouble reducer;
5344 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
5345 >        final DoubleBinaryOperator reducer;
5346          final double basis;
5347          double result;
5348          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5349          MapReduceEntriesToDoubleTask
5350 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5350 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5351               MapReduceEntriesToDoubleTask<K,V> nextRight,
5352 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5352 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5353               double basis,
5354 <             DoubleByDoubleToDouble reducer) {
5355 <            super(m, p, b); this.nextRight = nextRight;
5354 >             DoubleBinaryOperator reducer) {
5355 >            super(p, b, i, f, t); this.nextRight = nextRight;
5356              this.transformer = transformer;
5357              this.basis = basis; this.reducer = reducer;
5358          }
5359 <        @SuppressWarnings("unchecked") public final boolean exec() {
5360 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
5361 <                this.transformer;
5362 <            final DoubleByDoubleToDouble reducer = this.reducer;
5363 <            if (transformer == null || reducer == null)
5364 <                return abortOnNullFunction();
5365 <            try {
5366 <                final double id = this.basis;
5367 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5368 <                    do {} while (!casPending(c = pending, c+1));
5359 >        public final Double getRawResult() { return result; }
5360 >        public final void compute() {
5361 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
5362 >            final DoubleBinaryOperator reducer;
5363 >            if ((transformer = this.transformer) != null &&
5364 >                (reducer = this.reducer) != null) {
5365 >                double r = this.basis;
5366 >                for (int i = baseIndex, f, h; batch > 0 &&
5367 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5368 >                    addToPendingCount(1);
5369                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5370 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5370 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5371 >                      rights, transformer, r, reducer)).fork();
5372                  }
5373 <                double r = id;
5374 <                Object v;
6559 <                while ((v = advance()) != null)
6560 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5373 >                for (Node<K,V> p; (p = advance()) != null; )
5374 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5375                  result = r;
5376 <                for (MapReduceEntriesToDoubleTask<K,V> t = this, s;;) {
5377 <                    int c; BulkTask<K,V,?> par;
5378 <                    if ((c = t.pending) == 0) {
5379 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5380 <                            t.result = reducer.apply(t.result, s.result);
5381 <                        }
5382 <                        if ((par = t.parent) == null ||
5383 <                            !(par instanceof MapReduceEntriesToDoubleTask)) {
6570 <                            t.quietlyComplete();
6571 <                            break;
6572 <                        }
6573 <                        t = (MapReduceEntriesToDoubleTask<K,V>)par;
5376 >                CountedCompleter<?> c;
5377 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5378 >                    MapReduceEntriesToDoubleTask<K,V>
5379 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
5380 >                        s = t.rights;
5381 >                    while (s != null) {
5382 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5383 >                        s = t.rights = s.nextRight;
5384                      }
6575                    else if (t.casPending(c, c - 1))
6576                        break;
5385                  }
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);
5386              }
6588            return false;
5387          }
6590        public final Double getRawResult() { return result; }
5388      }
5389  
5390 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5390 >    static final class MapReduceMappingsToDoubleTask<K,V>
5391          extends BulkTask<K,V,Double> {
5392 <        final ObjectByObjectToDouble<? super K, ? super V> transformer;
5393 <        final DoubleByDoubleToDouble reducer;
5392 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
5393 >        final DoubleBinaryOperator reducer;
5394          final double basis;
5395          double result;
5396          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5397          MapReduceMappingsToDoubleTask
5398 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5398 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5399               MapReduceMappingsToDoubleTask<K,V> nextRight,
5400 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
5400 >             ToDoubleBiFunction<? super K, ? super V> transformer,
5401               double basis,
5402 <             DoubleByDoubleToDouble reducer) {
5403 <            super(m, p, b); this.nextRight = nextRight;
5402 >             DoubleBinaryOperator reducer) {
5403 >            super(p, b, i, f, t); this.nextRight = nextRight;
5404              this.transformer = transformer;
5405              this.basis = basis; this.reducer = reducer;
5406          }
5407 <        @SuppressWarnings("unchecked") public final boolean exec() {
5408 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
5409 <                this.transformer;
5410 <            final DoubleByDoubleToDouble reducer = this.reducer;
5411 <            if (transformer == null || reducer == null)
5412 <                return abortOnNullFunction();
5413 <            try {
5414 <                final double id = this.basis;
5415 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5416 <                    do {} while (!casPending(c = pending, c+1));
5407 >        public final Double getRawResult() { return result; }
5408 >        public final void compute() {
5409 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
5410 >            final DoubleBinaryOperator reducer;
5411 >            if ((transformer = this.transformer) != null &&
5412 >                (reducer = this.reducer) != null) {
5413 >                double r = this.basis;
5414 >                for (int i = baseIndex, f, h; batch > 0 &&
5415 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5416 >                    addToPendingCount(1);
5417                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5418 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5418 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5419 >                      rights, transformer, r, reducer)).fork();
5420                  }
5421 <                double r = id;
5422 <                Object v;
6625 <                while ((v = advance()) != null)
6626 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5421 >                for (Node<K,V> p; (p = advance()) != null; )
5422 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)p.key, p.val));
5423                  result = r;
5424 <                for (MapReduceMappingsToDoubleTask<K,V> t = this, s;;) {
5425 <                    int c; BulkTask<K,V,?> par;
5426 <                    if ((c = t.pending) == 0) {
5427 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5428 <                            t.result = reducer.apply(t.result, s.result);
5429 <                        }
5430 <                        if ((par = t.parent) == null ||
5431 <                            !(par instanceof MapReduceMappingsToDoubleTask)) {
6636 <                            t.quietlyComplete();
6637 <                            break;
6638 <                        }
6639 <                        t = (MapReduceMappingsToDoubleTask<K,V>)par;
5424 >                CountedCompleter<?> c;
5425 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5426 >                    MapReduceMappingsToDoubleTask<K,V>
5427 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
5428 >                        s = t.rights;
5429 >                    while (s != null) {
5430 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5431 >                        s = t.rights = s.nextRight;
5432                      }
6641                    else if (t.casPending(c, c - 1))
6642                        break;
5433                  }
6644            } catch (Throwable ex) {
6645                return tryCompleteComputation(ex);
5434              }
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;
5435          }
6656        public final Double getRawResult() { return result; }
5436      }
5437  
5438 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5438 >    static final class MapReduceKeysToLongTask<K,V>
5439          extends BulkTask<K,V,Long> {
5440 <        final ObjectToLong<? super K> transformer;
5441 <        final LongByLongToLong reducer;
5440 >        final ToLongFunction<? super K> transformer;
5441 >        final LongBinaryOperator reducer;
5442          final long basis;
5443          long result;
5444          MapReduceKeysToLongTask<K,V> rights, nextRight;
5445          MapReduceKeysToLongTask
5446 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5446 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5447               MapReduceKeysToLongTask<K,V> nextRight,
5448 <             ObjectToLong<? super K> transformer,
5448 >             ToLongFunction<? super K> transformer,
5449               long basis,
5450 <             LongByLongToLong reducer) {
5451 <            super(m, p, b); this.nextRight = nextRight;
5450 >             LongBinaryOperator reducer) {
5451 >            super(p, b, i, f, t); this.nextRight = nextRight;
5452              this.transformer = transformer;
5453              this.basis = basis; this.reducer = reducer;
5454          }
5455 <        @SuppressWarnings("unchecked") public final boolean exec() {
5456 <            final ObjectToLong<? super K> transformer =
5457 <                this.transformer;
5458 <            final LongByLongToLong reducer = this.reducer;
5459 <            if (transformer == null || reducer == null)
5460 <                return abortOnNullFunction();
5461 <            try {
5462 <                final long id = this.basis;
5463 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5464 <                    do {} while (!casPending(c = pending, c+1));
5455 >        public final Long getRawResult() { return result; }
5456 >        public final void compute() {
5457 >            final ToLongFunction<? super K> transformer;
5458 >            final LongBinaryOperator reducer;
5459 >            if ((transformer = this.transformer) != null &&
5460 >                (reducer = this.reducer) != null) {
5461 >                long r = this.basis;
5462 >                for (int i = baseIndex, f, h; batch > 0 &&
5463 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5464 >                    addToPendingCount(1);
5465                      (rights = new MapReduceKeysToLongTask<K,V>
5466 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5466 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5467 >                      rights, transformer, r, reducer)).fork();
5468                  }
5469 <                long r = id;
5470 <                while (advance() != null)
6691 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5469 >                for (Node<K,V> p; (p = advance()) != null; )
5470 >                    r = reducer.applyAsLong(r, transformer.applyAsLong((K)p.key));
5471                  result = r;
5472 <                for (MapReduceKeysToLongTask<K,V> t = this, s;;) {
5473 <                    int c; BulkTask<K,V,?> par;
5474 <                    if ((c = t.pending) == 0) {
5475 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5476 <                            t.result = reducer.apply(t.result, s.result);
5477 <                        }
5478 <                        if ((par = t.parent) == null ||
5479 <                            !(par instanceof MapReduceKeysToLongTask)) {
6701 <                            t.quietlyComplete();
6702 <                            break;
6703 <                        }
6704 <                        t = (MapReduceKeysToLongTask<K,V>)par;
5472 >                CountedCompleter<?> c;
5473 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5474 >                    MapReduceKeysToLongTask<K,V>
5475 >                        t = (MapReduceKeysToLongTask<K,V>)c,
5476 >                        s = t.rights;
5477 >                    while (s != null) {
5478 >                        t.result = reducer.applyAsLong(t.result, s.result);
5479 >                        s = t.rights = s.nextRight;
5480                      }
6706                    else if (t.casPending(c, c - 1))
6707                        break;
5481                  }
6709            } catch (Throwable ex) {
6710                return tryCompleteComputation(ex);
5482              }
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;
5483          }
6721        public final Long getRawResult() { return result; }
5484      }
5485  
5486 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5486 >    static final class MapReduceValuesToLongTask<K,V>
5487          extends BulkTask<K,V,Long> {
5488 <        final ObjectToLong<? super V> transformer;
5489 <        final LongByLongToLong reducer;
5488 >        final ToLongFunction<? super V> transformer;
5489 >        final LongBinaryOperator reducer;
5490          final long basis;
5491          long result;
5492          MapReduceValuesToLongTask<K,V> rights, nextRight;
5493          MapReduceValuesToLongTask
5494 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5494 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5495               MapReduceValuesToLongTask<K,V> nextRight,
5496 <             ObjectToLong<? super V> transformer,
5496 >             ToLongFunction<? super V> transformer,
5497               long basis,
5498 <             LongByLongToLong reducer) {
5499 <            super(m, p, b); this.nextRight = nextRight;
5498 >             LongBinaryOperator reducer) {
5499 >            super(p, b, i, f, t); this.nextRight = nextRight;
5500              this.transformer = transformer;
5501              this.basis = basis; this.reducer = reducer;
5502          }
5503 <        @SuppressWarnings("unchecked") public final boolean exec() {
5504 <            final ObjectToLong<? super V> transformer =
5505 <                this.transformer;
5506 <            final LongByLongToLong reducer = this.reducer;
5507 <            if (transformer == null || reducer == null)
5508 <                return abortOnNullFunction();
5509 <            try {
5510 <                final long id = this.basis;
5511 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5512 <                    do {} while (!casPending(c = pending, c+1));
5503 >        public final Long getRawResult() { return result; }
5504 >        public final void compute() {
5505 >            final ToLongFunction<? super V> transformer;
5506 >            final LongBinaryOperator reducer;
5507 >            if ((transformer = this.transformer) != null &&
5508 >                (reducer = this.reducer) != null) {
5509 >                long r = this.basis;
5510 >                for (int i = baseIndex, f, h; batch > 0 &&
5511 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5512 >                    addToPendingCount(1);
5513                      (rights = new MapReduceValuesToLongTask<K,V>
5514 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5514 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5515 >                      rights, transformer, r, reducer)).fork();
5516                  }
5517 <                long r = id;
5518 <                Object v;
6756 <                while ((v = advance()) != null)
6757 <                    r = reducer.apply(r, transformer.apply((V)v));
5517 >                for (Node<K,V> p; (p = advance()) != null; )
5518 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5519                  result = r;
5520 <                for (MapReduceValuesToLongTask<K,V> t = this, s;;) {
5521 <                    int c; BulkTask<K,V,?> par;
5522 <                    if ((c = t.pending) == 0) {
5523 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5524 <                            t.result = reducer.apply(t.result, s.result);
5525 <                        }
5526 <                        if ((par = t.parent) == null ||
5527 <                            !(par instanceof MapReduceValuesToLongTask)) {
6767 <                            t.quietlyComplete();
6768 <                            break;
6769 <                        }
6770 <                        t = (MapReduceValuesToLongTask<K,V>)par;
5520 >                CountedCompleter<?> c;
5521 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5522 >                    MapReduceValuesToLongTask<K,V>
5523 >                        t = (MapReduceValuesToLongTask<K,V>)c,
5524 >                        s = t.rights;
5525 >                    while (s != null) {
5526 >                        t.result = reducer.applyAsLong(t.result, s.result);
5527 >                        s = t.rights = s.nextRight;
5528                      }
6772                    else if (t.casPending(c, c - 1))
6773                        break;
5529                  }
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);
5530              }
6785            return false;
5531          }
6787        public final Long getRawResult() { return result; }
5532      }
5533  
5534 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5534 >    static final class MapReduceEntriesToLongTask<K,V>
5535          extends BulkTask<K,V,Long> {
5536 <        final ObjectToLong<Map.Entry<K,V>> transformer;
5537 <        final LongByLongToLong reducer;
5536 >        final ToLongFunction<Map.Entry<K,V>> transformer;
5537 >        final LongBinaryOperator reducer;
5538          final long basis;
5539          long result;
5540          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5541          MapReduceEntriesToLongTask
5542 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5542 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5543               MapReduceEntriesToLongTask<K,V> nextRight,
5544 <             ObjectToLong<Map.Entry<K,V>> transformer,
5544 >             ToLongFunction<Map.Entry<K,V>> transformer,
5545               long basis,
5546 <             LongByLongToLong reducer) {
5547 <            super(m, p, b); this.nextRight = nextRight;
5546 >             LongBinaryOperator reducer) {
5547 >            super(p, b, i, f, t); this.nextRight = nextRight;
5548              this.transformer = transformer;
5549              this.basis = basis; this.reducer = reducer;
5550          }
5551 <        @SuppressWarnings("unchecked") public final boolean exec() {
5552 <            final ObjectToLong<Map.Entry<K,V>> transformer =
5553 <                this.transformer;
5554 <            final LongByLongToLong reducer = this.reducer;
5555 <            if (transformer == null || reducer == null)
5556 <                return abortOnNullFunction();
5557 <            try {
5558 <                final long id = this.basis;
5559 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5560 <                    do {} while (!casPending(c = pending, c+1));
5551 >        public final Long getRawResult() { return result; }
5552 >        public final void compute() {
5553 >            final ToLongFunction<Map.Entry<K,V>> transformer;
5554 >            final LongBinaryOperator reducer;
5555 >            if ((transformer = this.transformer) != null &&
5556 >                (reducer = this.reducer) != null) {
5557 >                long r = this.basis;
5558 >                for (int i = baseIndex, f, h; batch > 0 &&
5559 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5560 >                    addToPendingCount(1);
5561                      (rights = new MapReduceEntriesToLongTask<K,V>
5562 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5562 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5563 >                      rights, transformer, r, reducer)).fork();
5564                  }
5565 <                long r = id;
5566 <                Object v;
6822 <                while ((v = advance()) != null)
6823 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5565 >                for (Node<K,V> p; (p = advance()) != null; )
5566 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
5567                  result = r;
5568 <                for (MapReduceEntriesToLongTask<K,V> t = this, s;;) {
5569 <                    int c; BulkTask<K,V,?> par;
5570 <                    if ((c = t.pending) == 0) {
5571 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5572 <                            t.result = reducer.apply(t.result, s.result);
5573 <                        }
5574 <                        if ((par = t.parent) == null ||
5575 <                            !(par instanceof MapReduceEntriesToLongTask)) {
6833 <                            t.quietlyComplete();
6834 <                            break;
6835 <                        }
6836 <                        t = (MapReduceEntriesToLongTask<K,V>)par;
5568 >                CountedCompleter<?> c;
5569 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5570 >                    MapReduceEntriesToLongTask<K,V>
5571 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
5572 >                        s = t.rights;
5573 >                    while (s != null) {
5574 >                        t.result = reducer.applyAsLong(t.result, s.result);
5575 >                        s = t.rights = s.nextRight;
5576                      }
6838                    else if (t.casPending(c, c - 1))
6839                        break;
5577                  }
6841            } catch (Throwable ex) {
6842                return tryCompleteComputation(ex);
5578              }
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;
5579          }
6853        public final Long getRawResult() { return result; }
5580      }
5581  
5582 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
5582 >    static final class MapReduceMappingsToLongTask<K,V>
5583          extends BulkTask<K,V,Long> {
5584 <        final ObjectByObjectToLong<? super K, ? super V> transformer;
5585 <        final LongByLongToLong reducer;
5584 >        final ToLongBiFunction<? super K, ? super V> transformer;
5585 >        final LongBinaryOperator reducer;
5586          final long basis;
5587          long result;
5588          MapReduceMappingsToLongTask<K,V> rights, nextRight;
5589          MapReduceMappingsToLongTask
5590 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5590 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5591               MapReduceMappingsToLongTask<K,V> nextRight,
5592 <             ObjectByObjectToLong<? super K, ? super V> transformer,
5592 >             ToLongBiFunction<? super K, ? super V> transformer,
5593               long basis,
5594 <             LongByLongToLong reducer) {
5595 <            super(m, p, b); this.nextRight = nextRight;
5594 >             LongBinaryOperator reducer) {
5595 >            super(p, b, i, f, t); this.nextRight = nextRight;
5596              this.transformer = transformer;
5597              this.basis = basis; this.reducer = reducer;
5598          }
5599 <        @SuppressWarnings("unchecked") public final boolean exec() {
5600 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
5601 <                this.transformer;
5602 <            final LongByLongToLong reducer = this.reducer;
5603 <            if (transformer == null || reducer == null)
5604 <                return abortOnNullFunction();
5605 <            try {
5606 <                final long id = this.basis;
5607 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5608 <                    do {} while (!casPending(c = pending, c+1));
5599 >        public final Long getRawResult() { return result; }
5600 >        public final void compute() {
5601 >            final ToLongBiFunction<? super K, ? super V> transformer;
5602 >            final LongBinaryOperator reducer;
5603 >            if ((transformer = this.transformer) != null &&
5604 >                (reducer = this.reducer) != null) {
5605 >                long r = this.basis;
5606 >                for (int i = baseIndex, f, h; batch > 0 &&
5607 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5608 >                    addToPendingCount(1);
5609                      (rights = new MapReduceMappingsToLongTask<K,V>
5610 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5610 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5611 >                      rights, transformer, r, reducer)).fork();
5612                  }
5613 <                long r = id;
5614 <                Object v;
6888 <                while ((v = advance()) != null)
6889 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5613 >                for (Node<K,V> p; (p = advance()) != null; )
5614 >                    r = reducer.applyAsLong(r, transformer.applyAsLong((K)p.key, p.val));
5615                  result = r;
5616 <                for (MapReduceMappingsToLongTask<K,V> t = this, s;;) {
5617 <                    int c; BulkTask<K,V,?> par;
5618 <                    if ((c = t.pending) == 0) {
5619 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5620 <                            t.result = reducer.apply(t.result, s.result);
5621 <                        }
5622 <                        if ((par = t.parent) == null ||
5623 <                            !(par instanceof MapReduceMappingsToLongTask)) {
6899 <                            t.quietlyComplete();
6900 <                            break;
6901 <                        }
6902 <                        t = (MapReduceMappingsToLongTask<K,V>)par;
5616 >                CountedCompleter<?> c;
5617 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5618 >                    MapReduceMappingsToLongTask<K,V>
5619 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
5620 >                        s = t.rights;
5621 >                    while (s != null) {
5622 >                        t.result = reducer.applyAsLong(t.result, s.result);
5623 >                        s = t.rights = s.nextRight;
5624                      }
6904                    else if (t.casPending(c, c - 1))
6905                        break;
5625                  }
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);
5626              }
6917            return false;
5627          }
6919        public final Long getRawResult() { return result; }
5628      }
5629  
5630 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
5630 >    static final class MapReduceKeysToIntTask<K,V>
5631          extends BulkTask<K,V,Integer> {
5632 <        final ObjectToInt<? super K> transformer;
5633 <        final IntByIntToInt reducer;
5632 >        final ToIntFunction<? super K> transformer;
5633 >        final IntBinaryOperator reducer;
5634          final int basis;
5635          int result;
5636          MapReduceKeysToIntTask<K,V> rights, nextRight;
5637          MapReduceKeysToIntTask
5638 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5638 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5639               MapReduceKeysToIntTask<K,V> nextRight,
5640 <             ObjectToInt<? super K> transformer,
5640 >             ToIntFunction<? super K> transformer,
5641               int basis,
5642 <             IntByIntToInt reducer) {
5643 <            super(m, p, b); this.nextRight = nextRight;
5642 >             IntBinaryOperator reducer) {
5643 >            super(p, b, i, f, t); this.nextRight = nextRight;
5644              this.transformer = transformer;
5645              this.basis = basis; this.reducer = reducer;
5646          }
5647 <        @SuppressWarnings("unchecked") public final boolean exec() {
5648 <            final ObjectToInt<? super K> transformer =
5649 <                this.transformer;
5650 <            final IntByIntToInt reducer = this.reducer;
5651 <            if (transformer == null || reducer == null)
5652 <                return abortOnNullFunction();
5653 <            try {
5654 <                final int id = this.basis;
5655 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5656 <                    do {} while (!casPending(c = pending, c+1));
5647 >        public final Integer getRawResult() { return result; }
5648 >        public final void compute() {
5649 >            final ToIntFunction<? super K> transformer;
5650 >            final IntBinaryOperator reducer;
5651 >            if ((transformer = this.transformer) != null &&
5652 >                (reducer = this.reducer) != null) {
5653 >                int r = this.basis;
5654 >                for (int i = baseIndex, f, h; batch > 0 &&
5655 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5656 >                    addToPendingCount(1);
5657                      (rights = new MapReduceKeysToIntTask<K,V>
5658 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5658 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5659 >                      rights, transformer, r, reducer)).fork();
5660                  }
5661 <                int r = id;
5662 <                while (advance() != null)
6954 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5661 >                for (Node<K,V> p; (p = advance()) != null; )
5662 >                    r = reducer.applyAsInt(r, transformer.applyAsInt((K)p.key));
5663                  result = r;
5664 <                for (MapReduceKeysToIntTask<K,V> t = this, s;;) {
5665 <                    int c; BulkTask<K,V,?> par;
5666 <                    if ((c = t.pending) == 0) {
5667 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5668 <                            t.result = reducer.apply(t.result, s.result);
5669 <                        }
5670 <                        if ((par = t.parent) == null ||
5671 <                            !(par instanceof MapReduceKeysToIntTask)) {
6964 <                            t.quietlyComplete();
6965 <                            break;
6966 <                        }
6967 <                        t = (MapReduceKeysToIntTask<K,V>)par;
5664 >                CountedCompleter<?> c;
5665 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5666 >                    MapReduceKeysToIntTask<K,V>
5667 >                        t = (MapReduceKeysToIntTask<K,V>)c,
5668 >                        s = t.rights;
5669 >                    while (s != null) {
5670 >                        t.result = reducer.applyAsInt(t.result, s.result);
5671 >                        s = t.rights = s.nextRight;
5672                      }
6969                    else if (t.casPending(c, c - 1))
6970                        break;
5673                  }
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);
5674              }
6982            return false;
5675          }
6984        public final Integer getRawResult() { return result; }
5676      }
5677  
5678 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
5678 >    static final class MapReduceValuesToIntTask<K,V>
5679          extends BulkTask<K,V,Integer> {
5680 <        final ObjectToInt<? super V> transformer;
5681 <        final IntByIntToInt reducer;
5680 >        final ToIntFunction<? super V> transformer;
5681 >        final IntBinaryOperator reducer;
5682          final int basis;
5683          int result;
5684          MapReduceValuesToIntTask<K,V> rights, nextRight;
5685          MapReduceValuesToIntTask
5686 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5686 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5687               MapReduceValuesToIntTask<K,V> nextRight,
5688 <             ObjectToInt<? super V> transformer,
5688 >             ToIntFunction<? super V> transformer,
5689               int basis,
5690 <             IntByIntToInt reducer) {
5691 <            super(m, p, b); this.nextRight = nextRight;
5690 >             IntBinaryOperator reducer) {
5691 >            super(p, b, i, f, t); this.nextRight = nextRight;
5692              this.transformer = transformer;
5693              this.basis = basis; this.reducer = reducer;
5694          }
5695 <        @SuppressWarnings("unchecked") public final boolean exec() {
5696 <            final ObjectToInt<? super V> transformer =
5697 <                this.transformer;
5698 <            final IntByIntToInt reducer = this.reducer;
5699 <            if (transformer == null || reducer == null)
5700 <                return abortOnNullFunction();
5701 <            try {
5702 <                final int id = this.basis;
5703 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5704 <                    do {} while (!casPending(c = pending, c+1));
5695 >        public final Integer getRawResult() { return result; }
5696 >        public final void compute() {
5697 >            final ToIntFunction<? super V> transformer;
5698 >            final IntBinaryOperator reducer;
5699 >            if ((transformer = this.transformer) != null &&
5700 >                (reducer = this.reducer) != null) {
5701 >                int r = this.basis;
5702 >                for (int i = baseIndex, f, h; batch > 0 &&
5703 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5704 >                    addToPendingCount(1);
5705                      (rights = new MapReduceValuesToIntTask<K,V>
5706 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5706 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5707 >                      rights, transformer, r, reducer)).fork();
5708                  }
5709 <                int r = id;
5710 <                Object v;
7019 <                while ((v = advance()) != null)
7020 <                    r = reducer.apply(r, transformer.apply((V)v));
5709 >                for (Node<K,V> p; (p = advance()) != null; )
5710 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
5711                  result = r;
5712 <                for (MapReduceValuesToIntTask<K,V> t = this, s;;) {
5713 <                    int c; BulkTask<K,V,?> par;
5714 <                    if ((c = t.pending) == 0) {
5715 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5716 <                            t.result = reducer.apply(t.result, s.result);
5717 <                        }
5718 <                        if ((par = t.parent) == null ||
5719 <                            !(par instanceof MapReduceValuesToIntTask)) {
7030 <                            t.quietlyComplete();
7031 <                            break;
7032 <                        }
7033 <                        t = (MapReduceValuesToIntTask<K,V>)par;
5712 >                CountedCompleter<?> c;
5713 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5714 >                    MapReduceValuesToIntTask<K,V>
5715 >                        t = (MapReduceValuesToIntTask<K,V>)c,
5716 >                        s = t.rights;
5717 >                    while (s != null) {
5718 >                        t.result = reducer.applyAsInt(t.result, s.result);
5719 >                        s = t.rights = s.nextRight;
5720                      }
7035                    else if (t.casPending(c, c - 1))
7036                        break;
5721                  }
7038            } catch (Throwable ex) {
7039                return tryCompleteComputation(ex);
5722              }
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;
5723          }
7050        public final Integer getRawResult() { return result; }
5724      }
5725  
5726 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
5726 >    static final class MapReduceEntriesToIntTask<K,V>
5727          extends BulkTask<K,V,Integer> {
5728 <        final ObjectToInt<Map.Entry<K,V>> transformer;
5729 <        final IntByIntToInt reducer;
5728 >        final ToIntFunction<Map.Entry<K,V>> transformer;
5729 >        final IntBinaryOperator reducer;
5730          final int basis;
5731          int result;
5732          MapReduceEntriesToIntTask<K,V> rights, nextRight;
5733          MapReduceEntriesToIntTask
5734 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5734 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5735               MapReduceEntriesToIntTask<K,V> nextRight,
5736 <             ObjectToInt<Map.Entry<K,V>> transformer,
5736 >             ToIntFunction<Map.Entry<K,V>> transformer,
5737               int basis,
5738 <             IntByIntToInt reducer) {
5739 <            super(m, p, b); this.nextRight = nextRight;
5738 >             IntBinaryOperator reducer) {
5739 >            super(p, b, i, f, t); this.nextRight = nextRight;
5740              this.transformer = transformer;
5741              this.basis = basis; this.reducer = reducer;
5742          }
5743 <        @SuppressWarnings("unchecked") public final boolean exec() {
5744 <            final ObjectToInt<Map.Entry<K,V>> transformer =
5745 <                this.transformer;
5746 <            final IntByIntToInt reducer = this.reducer;
5747 <            if (transformer == null || reducer == null)
5748 <                return abortOnNullFunction();
5749 <            try {
5750 <                final int id = this.basis;
5751 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5752 <                    do {} while (!casPending(c = pending, c+1));
5743 >        public final Integer getRawResult() { return result; }
5744 >        public final void compute() {
5745 >            final ToIntFunction<Map.Entry<K,V>> transformer;
5746 >            final IntBinaryOperator reducer;
5747 >            if ((transformer = this.transformer) != null &&
5748 >                (reducer = this.reducer) != null) {
5749 >                int r = this.basis;
5750 >                for (int i = baseIndex, f, h; batch > 0 &&
5751 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5752 >                    addToPendingCount(1);
5753                      (rights = new MapReduceEntriesToIntTask<K,V>
5754 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5754 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5755 >                      rights, transformer, r, reducer)).fork();
5756                  }
5757 <                int r = id;
5758 <                Object v;
7085 <                while ((v = advance()) != null)
7086 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5757 >                for (Node<K,V> p; (p = advance()) != null; )
5758 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
5759                  result = r;
5760 <                for (MapReduceEntriesToIntTask<K,V> t = this, s;;) {
5761 <                    int c; BulkTask<K,V,?> par;
5762 <                    if ((c = t.pending) == 0) {
5763 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5764 <                            t.result = reducer.apply(t.result, s.result);
5765 <                        }
5766 <                        if ((par = t.parent) == null ||
5767 <                            !(par instanceof MapReduceEntriesToIntTask)) {
7096 <                            t.quietlyComplete();
7097 <                            break;
7098 <                        }
7099 <                        t = (MapReduceEntriesToIntTask<K,V>)par;
5760 >                CountedCompleter<?> c;
5761 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5762 >                    MapReduceEntriesToIntTask<K,V>
5763 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
5764 >                        s = t.rights;
5765 >                    while (s != null) {
5766 >                        t.result = reducer.applyAsInt(t.result, s.result);
5767 >                        s = t.rights = s.nextRight;
5768                      }
7101                    else if (t.casPending(c, c - 1))
7102                        break;
5769                  }
7104            } catch (Throwable ex) {
7105                return tryCompleteComputation(ex);
5770              }
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;
5771          }
7116        public final Integer getRawResult() { return result; }
5772      }
5773  
5774 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
5774 >    static final class MapReduceMappingsToIntTask<K,V>
5775          extends BulkTask<K,V,Integer> {
5776 <        final ObjectByObjectToInt<? super K, ? super V> transformer;
5777 <        final IntByIntToInt reducer;
5776 >        final ToIntBiFunction<? super K, ? super V> transformer;
5777 >        final IntBinaryOperator reducer;
5778          final int basis;
5779          int result;
5780          MapReduceMappingsToIntTask<K,V> rights, nextRight;
5781          MapReduceMappingsToIntTask
5782 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5783 <             MapReduceMappingsToIntTask<K,V> rights,
5784 <             ObjectByObjectToInt<? super K, ? super V> transformer,
5782 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5783 >             MapReduceMappingsToIntTask<K,V> nextRight,
5784 >             ToIntBiFunction<? super K, ? super V> transformer,
5785               int basis,
5786 <             IntByIntToInt reducer) {
5787 <            super(m, p, b); this.nextRight = nextRight;
5786 >             IntBinaryOperator reducer) {
5787 >            super(p, b, i, f, t); this.nextRight = nextRight;
5788              this.transformer = transformer;
5789              this.basis = basis; this.reducer = reducer;
5790          }
5791 <        @SuppressWarnings("unchecked") public final boolean exec() {
5792 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
5793 <                this.transformer;
5794 <            final IntByIntToInt reducer = this.reducer;
5795 <            if (transformer == null || reducer == null)
5796 <                return abortOnNullFunction();
5797 <            try {
5798 <                final int id = this.basis;
5799 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5800 <                    do {} while (!casPending(c = pending, c+1));
5791 >        public final Integer getRawResult() { return result; }
5792 >        public final void compute() {
5793 >            final ToIntBiFunction<? super K, ? super V> transformer;
5794 >            final IntBinaryOperator reducer;
5795 >            if ((transformer = this.transformer) != null &&
5796 >                (reducer = this.reducer) != null) {
5797 >                int r = this.basis;
5798 >                for (int i = baseIndex, f, h; batch > 0 &&
5799 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5800 >                    addToPendingCount(1);
5801                      (rights = new MapReduceMappingsToIntTask<K,V>
5802 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5802 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5803 >                      rights, transformer, r, reducer)).fork();
5804                  }
5805 <                int r = id;
5806 <                Object v;
7151 <                while ((v = advance()) != null)
7152 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5805 >                for (Node<K,V> p; (p = advance()) != null; )
5806 >                    r = reducer.applyAsInt(r, transformer.applyAsInt((K)p.key, p.val));
5807                  result = r;
5808 <                for (MapReduceMappingsToIntTask<K,V> t = this, s;;) {
5809 <                    int c; BulkTask<K,V,?> par;
5810 <                    if ((c = t.pending) == 0) {
5811 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5812 <                            t.result = reducer.apply(t.result, s.result);
5813 <                        }
5814 <                        if ((par = t.parent) == null ||
5815 <                            !(par instanceof MapReduceMappingsToIntTask)) {
7162 <                            t.quietlyComplete();
7163 <                            break;
7164 <                        }
7165 <                        t = (MapReduceMappingsToIntTask<K,V>)par;
5808 >                CountedCompleter<?> c;
5809 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5810 >                    MapReduceMappingsToIntTask<K,V>
5811 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
5812 >                        s = t.rights;
5813 >                    while (s != null) {
5814 >                        t.result = reducer.applyAsInt(t.result, s.result);
5815 >                        s = t.rights = s.nextRight;
5816                      }
7167                    else if (t.casPending(c, c - 1))
7168                        break;
5817                  }
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);
5818              }
7180            return false;
5819          }
7182        public final Integer getRawResult() { return result; }
5820      }
5821  
5822      // Unsafe mechanics
5823 <    private static final sun.misc.Unsafe UNSAFE;
5824 <    private static final long counterOffset;
5825 <    private static final long sizeCtlOffset;
5823 >    private static final sun.misc.Unsafe U;
5824 >    private static final long SIZECTL;
5825 >    private static final long TRANSFERINDEX;
5826 >    private static final long TRANSFERORIGIN;
5827 >    private static final long BASECOUNT;
5828 >    private static final long CELLSBUSY;
5829 >    private static final long CELLVALUE;
5830      private static final long ABASE;
5831      private static final int ASHIFT;
5832  
5833      static {
7193        int ss;
5834          try {
5835 <            UNSAFE = sun.misc.Unsafe.getUnsafe();
5835 >            U = sun.misc.Unsafe.getUnsafe();
5836              Class<?> k = ConcurrentHashMap.class;
5837 <            counterOffset = UNSAFE.objectFieldOffset
7198 <                (k.getDeclaredField("counter"));
7199 <            sizeCtlOffset = UNSAFE.objectFieldOffset
5837 >            SIZECTL = U.objectFieldOffset
5838                  (k.getDeclaredField("sizeCtl"));
5839 +            TRANSFERINDEX = U.objectFieldOffset
5840 +                (k.getDeclaredField("transferIndex"));
5841 +            TRANSFERORIGIN = U.objectFieldOffset
5842 +                (k.getDeclaredField("transferOrigin"));
5843 +            BASECOUNT = U.objectFieldOffset
5844 +                (k.getDeclaredField("baseCount"));
5845 +            CELLSBUSY = U.objectFieldOffset
5846 +                (k.getDeclaredField("cellsBusy"));
5847 +            Class<?> ck = Cell.class;
5848 +            CELLVALUE = U.objectFieldOffset
5849 +                (ck.getDeclaredField("value"));
5850              Class<?> sc = Node[].class;
5851 <            ABASE = UNSAFE.arrayBaseOffset(sc);
5852 <            ss = UNSAFE.arrayIndexScale(sc);
5851 >            ABASE = U.arrayBaseOffset(sc);
5852 >            int scale = U.arrayIndexScale(sc);
5853 >            if ((scale & (scale - 1)) != 0)
5854 >                throw new Error("data type scale not a power of two");
5855 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
5856          } catch (Exception e) {
5857              throw new Error(e);
5858          }
7207        if ((ss & (ss-1)) != 0)
7208            throw new Error("data type scale not a power of two");
7209        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
5859      }
5860   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines