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.224 by dl, Tue Jun 18 17:11:45 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;
8  
9 < import java.util.Comparator;
9 > import java.io.ObjectStreamField;
10 > import java.io.Serializable;
11 > import java.lang.reflect.ParameterizedType;
12 > import java.lang.reflect.Type;
13   import java.util.Arrays;
14 import java.util.Map;
15 import java.util.Set;
14   import java.util.Collection;
15 < import java.util.AbstractMap;
16 < import java.util.AbstractSet;
17 < import java.util.AbstractCollection;
20 < import java.util.Hashtable;
15 > import java.util.Comparator;
16 > import java.util.ConcurrentModificationException;
17 > import java.util.Enumeration;
18   import java.util.HashMap;
19 + import java.util.Hashtable;
20   import java.util.Iterator;
21 < import java.util.Enumeration;
24 < import java.util.ConcurrentModificationException;
21 > import java.util.Map;
22   import java.util.NoSuchElementException;
23 + import java.util.Set;
24 + import java.util.Spliterator;
25   import java.util.concurrent.ConcurrentMap;
26 < import java.util.concurrent.ThreadLocalRandom;
28 < import java.util.concurrent.locks.LockSupport;
29 < import java.util.concurrent.locks.AbstractQueuedSynchronizer;
26 > import java.util.concurrent.ForkJoinPool;
27   import java.util.concurrent.atomic.AtomicReference;
28 <
29 < import java.io.Serializable;
28 > import java.util.concurrent.locks.LockSupport;
29 > import java.util.concurrent.locks.ReentrantLock;
30 > import java.util.function.BiConsumer;
31 > import java.util.function.BiFunction;
32 > import java.util.function.BinaryOperator;
33 > import java.util.function.Consumer;
34 > import java.util.function.DoubleBinaryOperator;
35 > import java.util.function.Function;
36 > import java.util.function.IntBinaryOperator;
37 > import java.util.function.LongBinaryOperator;
38 > import java.util.function.ToDoubleBiFunction;
39 > import java.util.function.ToDoubleFunction;
40 > import java.util.function.ToIntBiFunction;
41 > import java.util.function.ToIntFunction;
42 > import java.util.function.ToLongBiFunction;
43 > import java.util.function.ToLongFunction;
44 > import java.util.stream.Stream;
45  
46   /**
47   * A hash table supporting full concurrency of retrievals and
# Line 43 | Line 55 | import java.io.Serializable;
55   * interoperable with {@code Hashtable} in programs that rely on its
56   * thread safety but not on its synchronization details.
57   *
58 < * <p> Retrieval operations (including {@code get}) generally do not
58 > * <p>Retrieval operations (including {@code get}) generally do not
59   * block, so may overlap with update operations (including {@code put}
60   * and {@code remove}). Retrievals reflect the results of the most
61   * recently <em>completed</em> update operations holding upon their
# Line 64 | Line 76 | import java.io.Serializable;
76   * that may be adequate for monitoring or estimation purposes, but not
77   * for program control.
78   *
79 < * <p> The table is dynamically expanded when there are too many
79 > * <p>The table is dynamically expanded when there are too many
80   * collisions (i.e., keys that have distinct hash codes but fall into
81   * the same slot modulo the table size), with the expected average
82   * effect of maintaining roughly two bins per mapping (corresponding
# Line 83 | Line 95 | import java.io.Serializable;
95   * expected {@code concurrencyLevel} as an additional hint for
96   * internal sizing.  Note that using many keys with exactly the same
97   * {@code hashCode()} is a sure way to slow down performance of any
98 < * hash table.
98 > * hash table. To ameliorate impact, when keys are {@link Comparable},
99 > * this class may use comparison order among keys to help break ties.
100   *
101 < * <p> A {@link Set} projection of a ConcurrentHashMap may be created
101 > * <p>A {@link Set} projection of a ConcurrentHashMap may be created
102   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
103   * (using {@link #keySet(Object)} when only keys are of interest, and the
104   * mapped values are (perhaps transiently) not used or all take the
105   * same mapping value.
106   *
107 < * <p> A ConcurrentHashMap can be used as scalable frequency map (a
108 < * form of histogram or multiset) by using {@link LongAdder} values
109 < * and initializing via {@link #computeIfAbsent}. For example, to add
110 < * a count to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you
111 < * can use {@code freqs.computeIfAbsent(k -> new
112 < * LongAdder()).increment();}
107 > * <p>A ConcurrentHashMap can be used as scalable frequency map (a
108 > * form of histogram or multiset) by using {@link
109 > * java.util.concurrent.atomic.LongAdder} values and initializing via
110 > * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count
111 > * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
112 > * {@code freqs.computeIfAbsent(k -> new LongAdder()).increment();}
113   *
114   * <p>This class and its views and iterators implement all of the
115   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
116   * interfaces.
117   *
118 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
118 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
119   * does <em>not</em> allow {@code null} to be used as a key or value.
120   *
121 < * <p>ConcurrentHashMaps support parallel operations using the {@link
122 < * ForkJoinPool#commonPool}. (Tasks that may be used in other contexts
123 < * are available in class {@link ForkJoinTasks}). These operations are
124 < * designed to be safely, and often sensibly, applied even with maps
125 < * that are being concurrently updated by other threads; for example,
126 < * when computing a snapshot summary of the values in a shared
127 < * registry.  There are three kinds of operation, each with four
128 < * forms, accepting functions with Keys, Values, Entries, and (Key,
129 < * Value) arguments and/or return values. (The first three forms are
130 < * also available via the {@link #keySet()}, {@link #values()} and
131 < * {@link #entrySet()} views). Because the elements of a
132 < * ConcurrentHashMap are not ordered in any particular way, and may be
133 < * processed in different orders in different parallel executions, the
134 < * correctness of supplied functions should not depend on any
135 < * 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.
121 > * <p>ConcurrentHashMaps support a set of sequential and parallel bulk
122 > * operations that, unlike most {@link Stream} methods, are designed
123 > * to be safely, and often sensibly, applied even with maps that are
124 > * being concurrently updated by other threads; for example, when
125 > * computing a snapshot summary of the values in a shared registry.
126 > * There are three kinds of operation, each with four forms, accepting
127 > * functions with Keys, Values, Entries, and (Key, Value) arguments
128 > * and/or return values. Because the elements of a ConcurrentHashMap
129 > * are not ordered in any particular way, and may be processed in
130 > * different orders in different parallel executions, the correctness
131 > * of supplied functions should not depend on any ordering, or on any
132 > * other objects or values that may transiently change while
133 > * computation is in progress; and except for forEach actions, should
134 > * ideally be side-effect-free. Bulk operations on {@link Map.Entry}
135 > * objects do not support method {@code setValue}.
136   *
137   * <ul>
138   * <li> forEach: Perform a given action on each element.
# Line 148 | Line 159 | import java.io.Serializable;
159   * <li> Reductions to scalar doubles, longs, and ints, using a
160   * given basis value.</li>
161   *
151 * </li>
162   * </ul>
163 + * </li>
164   * </ul>
165   *
166 + * <p>These bulk operations accept a {@code parallelismThreshold}
167 + * argument. Methods proceed sequentially if the current map size is
168 + * estimated to be less than the given threshold. Using a value of
169 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
170 + * of {@code 1} results in maximal parallelism by partitioning into
171 + * enough subtasks to fully utilize the {@link
172 + * ForkJoinPool#commonPool()} that is used for all parallel
173 + * computations. Normally, you would initially choose one of these
174 + * extreme values, and then measure performance of using in-between
175 + * values that trade off overhead versus throughput.
176 + *
177   * <p>The concurrency properties of bulk operations follow
178   * from those of ConcurrentHashMap: Any non-null result returned
179   * from {@code get(key)} and related access methods bears a
# Line 187 | Line 209 | import java.io.Serializable;
209   * arguments can be supplied using {@code new
210   * AbstractMap.SimpleEntry(k,v)}.
211   *
212 < * <p> Bulk operations may complete abruptly, throwing an
212 > * <p>Bulk operations may complete abruptly, throwing an
213   * exception encountered in the application of a supplied
214   * function. Bear in mind when handling such exceptions that other
215   * concurrently executing functions could also have thrown
216   * exceptions, or would have done so if the first exception had
217   * not occurred.
218   *
219 < * <p>Parallel speedups for bulk operations compared to sequential
220 < * processing are common but not guaranteed.  Operations involving
221 < * brief functions on small maps may execute more slowly than
222 < * sequential loops if the underlying work to parallelize the
223 < * computation is more expensive than the computation itself.
224 < * Similarly, parallelization may not lead to much actual parallelism
225 < * if all processors are busy performing unrelated tasks.
219 > * <p>Speedups for parallel compared to sequential forms are common
220 > * but not guaranteed.  Parallel operations involving brief functions
221 > * on small maps may execute more slowly than sequential forms if the
222 > * underlying work to parallelize the computation is more expensive
223 > * than the computation itself.  Similarly, parallelization may not
224 > * lead to much actual parallelism if all processors are busy
225 > * performing unrelated tasks.
226   *
227 < * <p> All arguments to all task methods must be non-null.
206 < *
207 < * <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>
227 > * <p>All arguments to all task methods must be non-null.
228   *
229   * <p>This class is a member of the
230   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
# Line 217 | Line 235 | import java.io.Serializable;
235   * @param <K> the type of keys maintained by this map
236   * @param <V> the type of mapped values
237   */
238 < public class ConcurrentHashMap<K, V>
221 <    implements ConcurrentMap<K, V>, Serializable {
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
261 <     * approach explained below leads to a lot of code sprawl because
262 <     * retry-control precludes factoring into smaller methods.
251 >     * This map usually acts as a binned (bucketed) hash table.  Each
252 >     * key-value mapping is held in a Node.  Most nodes are instances
253 >     * of the basic Node class with hash, key, value, and next
254 >     * fields. However, various subclasses exist: TreeNodes are
255 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
256 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
257 >     * of bins during resizing. ReservationNodes are used as
258 >     * placeholders while establishing values in computeIfAbsent and
259 >     * related methods.  The types TreeBin, ForwardingNode, and
260 >     * ReservationNode do not hold normal user keys, values, or
261 >     * hashes, and are readily distinguishable during search etc
262 >     * because they have negative hash fields and null key and value
263 >     * fields. (These special nodes are either uncommon or transient,
264 >     * so the impact of carrying around some unused fields is
265 >     * insignficant.)
266       *
267       * The table is lazily initialized to a power-of-two size upon the
268       * first insertion.  Each bin in the table normally contains a
# Line 320 | Line 270 | public class ConcurrentHashMap<K, V>
270       * Table accesses require volatile/atomic reads, writes, and
271       * CASes.  Because there is no other way to arrange this without
272       * adding further indirections, we use intrinsics
273 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
274 <     * are always accurately traversable under volatile reads, so long
275 <     * as lookups check hash code and non-nullness of value before
276 <     * checking key equality.
277 <     *
278 <     * We use the top two bits of Node hash fields for control
329 <     * purposes -- they are available anyway because of addressing
330 <     * 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).
273 >     * (sun.misc.Unsafe) operations.
274 >     *
275 >     * We use the top (sign) bit of Node hash fields for control
276 >     * purposes -- it is available anyway because of addressing
277 >     * constraints.  Nodes with negative hash fields are specially
278 >     * handled or ignored in map methods.
279       *
280       * Insertion (via put or its variants) of the first node in an
281       * empty bin is performed by just CASing it to the bin.  This is
# Line 346 | Line 284 | public class ConcurrentHashMap<K, V>
284       * delete, and replace) require locks.  We do not want to waste
285       * the space required to associate a distinct lock object with
286       * each bin, so instead use the first node of a bin list itself as
287 <     * a lock. Blocking support for these locks relies on the builtin
288 <     * "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.
287 >     * a lock. Locking support for these locks relies on builtin
288 >     * "synchronized" monitors.
289       *
290       * Using the first node of a list as a lock does not by itself
291       * suffice though: When a node is locked, any update must first
292       * validate that it is still the first node after locking it, and
293       * retry if not. Because new nodes are always appended to lists,
294       * once a node is first in a bin, it remains first until deleted
295 <     * 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.
295 >     * or the bin becomes invalidated (upon resizing).
296       *
297       * The main disadvantage of per-bin locks is that other update
298       * operations on other nodes in a bin list protected by the same
# Line 394 | Line 325 | public class ConcurrentHashMap<K, V>
325       * sometimes deviate significantly from uniform randomness.  This
326       * includes the case when N > (1<<30), so some keys MUST collide.
327       * Similarly for dumb or hostile usages in which multiple keys are
328 <     * designed to have identical hash codes. Also, although we guard
329 <     * against the worst effects of this (see method spread), sets of
330 <     * hashes may differ only in bits that do not impact their bin
331 <     * index for a given power-of-two mask.  So we use a secondary
332 <     * strategy that applies when the number of nodes in a bin exceeds
333 <     * a threshold, and at least one of the keys implements
403 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
404 <     * (a specialized form of red-black trees), bounding search time
405 <     * to O(log N).  Each search step in a TreeBin is around twice as
328 >     * designed to have identical hash codes or ones that differs only
329 >     * in masked-out high bits. So we use a secondary strategy that
330 >     * applies when the number of nodes in a bin exceeds a
331 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
332 >     * specialized form of red-black trees), bounding search time to
333 >     * 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 >     * CounterCells.  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).
407 >     *
408 >     * TreeBins use a special form of comparison for search and
409 >     * related operations (which is the main reason we cannot use
410 >     * existing collections such as TreeMaps). TreeBins contain
411 >     * Comparable elements, but may contain others, as well as
412 >     * elements that are Comparable but not necessarily Comparable
413 >     * for the same T, so we cannot invoke compareTo among them. To
414 >     * handle this, the tree is ordered primarily by hash value, then
415 >     * by Comparable.compareTo order if applicable.  On lookup at a
416 >     * node, if elements are not comparable or compare as 0 then both
417 >     * left and right children may need to be searched in the case of
418 >     * tied hash values. (This corresponds to the full list search
419 >     * that would be necessary if all elements were non-Comparable and
420 >     * had tied hashes.)  The red-black balancing code is updated from
421 >     * pre-jdk-collections
422 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
423 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
424 >     * Algorithms" (CLR).
425 >     *
426 >     * TreeBins also require an additional locking mechanism.  While
427 >     * list traversal is always possible by readers even during
428 >     * updates, tree traversal is not, mainly beause of tree-rotations
429 >     * that may change the root node and/or its linkages.  TreeBins
430 >     * include a simple read-write lock mechanism parasitic on the
431 >     * main bin-synchronization strategy: Structural adjustments
432 >     * associated with an insertion or removal are already bin-locked
433 >     * (and so cannot conflict with other writers) but must wait for
434 >     * ongoing readers to finish. Since there can be only one such
435 >     * waiter, we use a simple scheme using a single "waiter" field to
436 >     * block writers.  However, readers need never block.  If the root
437 >     * lock is held, they proceed along the slow traversal path (via
438 >     * next-pointers) until the lock becomes available or the list is
439 >     * exhausted, whichever comes first. These cases are not fast, but
440 >     * maximize aggregate expected throughput.
441       *
442       * Maintaining API and serialization compatibility with previous
443       * versions of this class introduces several oddities. Mainly: We
# Line 487 | Line 447 | public class ConcurrentHashMap<K, V>
447       * time that we can guarantee to honor it.) We also declare an
448       * unused "Segment" class that is instantiated in minimal form
449       * only when serializing.
450 +     *
451 +     * This file is organized to make things a little easier to follow
452 +     * while reading than they might otherwise: First the main static
453 +     * declarations and utilities, then fields, then main public
454 +     * methods (with a few factorings of multiple public methods into
455 +     * internal ones), then sizing methods, trees, traversers, and
456 +     * bulk operations.
457       */
458  
459      /* ---------------- Constants -------------- */
# Line 528 | Line 495 | public class ConcurrentHashMap<K, V>
495      private static final float LOAD_FACTOR = 0.75f;
496  
497      /**
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    /**
498       * The bin count threshold for using a tree rather than list for a
499 <     * bin.  The value reflects the approximate break-even point for
500 <     * using tree-based operations.
499 >     * bin.  Bins are converted to trees when adding an element to a
500 >     * bin with at least this many nodes. The value must be greater
501 >     * than 2, and should be at least 8 to mesh with assumptions in
502 >     * tree removal about conversion back to plain bins upon
503 >     * shrinkage.
504       */
505 <    private static final int TREE_THRESHOLD = 8;
543 <
544 <    /*
545 <     * Encodings for special uses of Node hash fields. See above for
546 <     * explanation.
547 <     */
548 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
549 <    static final int LOCKED    = 0x40000000; // set/tested only as a bit
550 <    static final int WAITING   = 0xc0000000; // both bits set/tested together
551 <    static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
552 <
553 <    /* ---------------- Fields -------------- */
505 >    static final int TREEIFY_THRESHOLD = 8;
506  
507      /**
508 <     * The array of bins. Lazily initialized upon first insertion.
509 <     * Size is always a power of two. Accessed directly by iterators.
508 >     * The bin count threshold for untreeifying a (split) bin during a
509 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
510 >     * most 6 to mesh with shrinkage detection under removal.
511       */
512 <    transient volatile Node[] table;
512 >    static final int UNTREEIFY_THRESHOLD = 6;
513  
514      /**
515 <     * The counter maintaining number of elements.
515 >     * The smallest table capacity for which bins may be treeified.
516 >     * (Otherwise the table is resized if too many nodes in a bin.)
517 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
518 >     * conflicts between resizing and treeification thresholds.
519       */
520 <    private transient final LongAdder counter;
520 >    static final int MIN_TREEIFY_CAPACITY = 64;
521  
522      /**
523 <     * Table initialization and resizing control.  When negative, the
524 <     * table is being initialized or resized. Otherwise, when table is
525 <     * null, holds the initial table size to use upon creation, or 0
526 <     * for default. After initialization, holds the next element count
527 <     * value upon which to resize the table.
523 >     * Minimum number of rebinnings per transfer step. Ranges are
524 >     * subdivided to allow multiple resizer threads.  This value
525 >     * serves as a lower bound to avoid resizers encountering
526 >     * excessive memory contention.  The value should be at least
527 >     * DEFAULT_CAPACITY.
528       */
529 <    private transient volatile int sizeCtl;
574 <
575 <    // views
576 <    private transient KeySetView<K,V> keySet;
577 <    private transient ValuesView<K,V> values;
578 <    private transient EntrySetView<K,V> entrySet;
579 <
580 <    /** For serialization compatibility. Null unless serialized; see below */
581 <    private Segment<K,V>[] segments;
582 <
583 <    /* ---------------- Table element access -------------- */
529 >    private static final int MIN_TRANSFER_STRIDE = 16;
530  
531      /*
532 <     * Volatile access methods are used for table elements as well as
587 <     * elements of in-progress next table while resizing.  Uses are
588 <     * null checked by callers, and implicitly bounds-checked, relying
589 <     * on the invariants that tab arrays have non-zero size, and all
590 <     * indices are masked with (tab.length - 1) which is never
591 <     * negative and always less than length. Note that, to be correct
592 <     * wrt arbitrary concurrency errors by users, bounds checks must
593 <     * operate on local variables, which accounts for some odd-looking
594 <     * inline assignments below.
532 >     * Encodings for Node hash fields. See above for explanation.
533       */
534 <
535 <    static final Node tabAt(Node[] tab, int i) { // used by Iter
536 <        return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
537 <    }
538 <
539 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
540 <        return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
541 <    }
542 <
543 <    private static final void setTabAt(Node[] tab, int i, Node v) {
544 <        UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
545 <    }
534 >    static final int MOVED     = 0x8fffffff; // (-1) hash for forwarding nodes
535 >    static final int TREEBIN   = 0x80000000; // hash for heads of treea
536 >    static final int RESERVED  = 0x80000001; // hash for transient reservations
537 >    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
538 >
539 >    /** Number of CPUS, to place bounds on some sizings */
540 >    static final int NCPU = Runtime.getRuntime().availableProcessors();
541 >
542 >    /** For serialization compatibility. */
543 >    private static final ObjectStreamField[] serialPersistentFields = {
544 >        new ObjectStreamField("segments", Segment[].class),
545 >        new ObjectStreamField("segmentMask", Integer.TYPE),
546 >        new ObjectStreamField("segmentShift", Integer.TYPE)
547 >    };
548  
549      /* ---------------- Nodes -------------- */
550  
551      /**
552 <     * Key-value entry. Note that this is never exported out as a
553 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
554 <     * field of MOVED are special, and do not contain user keys or
555 <     * values.  Otherwise, keys are never null, and null val fields
556 <     * indicate that a node is in the process of being deleted or
557 <     * created. For purposes of read-only access, a key may be read
558 <     * before a val, but can only be used after checking val to be
559 <     * non-null.
560 <     */
561 <    static class Node {
562 <        volatile int hash;
563 <        final Object key;
624 <        volatile Object val;
625 <        volatile Node next;
552 >     * Key-value entry.  This class is never exported out as a
553 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
554 >     * MapEntry below), but can be used for read-only traversals used
555 >     * in bulk tasks.  Subclasses of Node with a negativehash field
556 >     * are special, and contain null keys and values (but are never
557 >     * exported).  Otherwise, keys and vals are never null.
558 >     */
559 >    static class Node<K,V> implements Map.Entry<K,V> {
560 >        final int hash;
561 >        final K key;
562 >        volatile V val;
563 >        Node<K,V> next;
564  
565 <        Node(int hash, Object key, Object val, Node next) {
565 >        Node(int hash, K key, V val, Node<K,V> next) {
566              this.hash = hash;
567              this.key = key;
568              this.val = val;
569              this.next = next;
570          }
571  
572 <        /** CompareAndSet the hash field */
573 <        final boolean casHash(int cmp, int val) {
574 <            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
575 <        }
576 <
577 <        /** The number of spins before blocking for a lock */
640 <        static final int MAX_SPINS =
641 <            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
642 <
643 <        /**
644 <         * Spins a while if LOCKED bit set and this node is the first
645 <         * of its bin, and then sets WAITING bits on hash field and
646 <         * blocks (once) if they are still set.  It is OK for this
647 <         * method to return even if lock is not available upon exit,
648 <         * which enables these simple single-wait mechanics.
649 <         *
650 <         * The corresponding signalling operation is performed within
651 <         * callers: Upon detecting that WAITING has been set when
652 <         * unlocking lock (via a failed CAS from non-waiting LOCKED
653 <         * 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 <            }
690 <        }
691 <
692 <        // Unsafe mechanics for casHash
693 <        private static final sun.misc.Unsafe UNSAFE;
694 <        private static final long hashOffset;
695 <
696 <        static {
697 <            try {
698 <                UNSAFE = sun.misc.Unsafe.getUnsafe();
699 <                Class<?> k = Node.class;
700 <                hashOffset = UNSAFE.objectFieldOffset
701 <                    (k.getDeclaredField("hash"));
702 <            } catch (Exception e) {
703 <                throw new Error(e);
704 <            }
705 <        }
706 <    }
707 <
708 <    /* ---------------- TreeBins -------------- */
709 <
710 <    /**
711 <     * Nodes for use in TreeBins
712 <     */
713 <    static final class TreeNode extends Node {
714 <        TreeNode parent;  // red-black tree links
715 <        TreeNode left;
716 <        TreeNode right;
717 <        TreeNode prev;    // needed to unlink next upon deletion
718 <        boolean red;
719 <
720 <        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
721 <            super(hash, key, val, next);
722 <            this.parent = parent;
723 <        }
724 <    }
725 <
726 <    /**
727 <     * A specialized form of red-black tree for use in bins
728 <     * whose size exceeds a threshold.
729 <     *
730 <     * TreeBins use a special form of comparison for search and
731 <     * related operations (which is the main reason we cannot use
732 <     * existing collections such as TreeMaps). TreeBins contain
733 <     * Comparable elements, but may contain others, as well as
734 <     * elements that are Comparable but not necessarily Comparable<T>
735 <     * for the same T, so we cannot invoke compareTo among them. To
736 <     * handle this, the tree is ordered primarily by hash value, then
737 <     * by getClass().getName() order, and then by Comparator order
738 <     * among elements of the same class.  On lookup at a node, if
739 <     * elements are not comparable or compare as 0, both left and
740 <     * right children may need to be searched in the case of tied hash
741 <     * values. (This corresponds to the full list search that would be
742 <     * necessary if all elements were non-Comparable and had tied
743 <     * hashes.)  The red-black balancing code is updated from
744 <     * pre-jdk-collections
745 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
746 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
747 <     * Algorithms" (CLR).
748 <     *
749 <     * TreeBins also maintain a separate locking discipline than
750 <     * regular bins. Because they are forwarded via special MOVED
751 <     * nodes at bin heads (which can never change once established),
752 <     * we cannot use those nodes as locks. Instead, TreeBin
753 <     * extends AbstractQueuedSynchronizer to support a simple form of
754 <     * read-write lock. For update operations and table validation,
755 <     * the exclusive form of lock behaves in the same way as bin-head
756 <     * locks. However, lookups use shared read-lock mechanics to allow
757 <     * multiple readers in the absence of writers.  Additionally,
758 <     * these lookups do not ever block: While the lock is not
759 <     * available, they proceed along the slow traversal path (via
760 <     * next-pointers) until the lock becomes available or the list is
761 <     * exhausted, whichever comes first. (These cases are not fast,
762 <     * 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.
768 <     */
769 <    static final class TreeBin extends AbstractQueuedSynchronizer {
770 <        private static final long serialVersionUID = 2249069246763182397L;
771 <        transient TreeNode root;  // root of tree
772 <        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 <        }
801 <
802 <        /** From CLR */
803 <        private void rotateLeft(TreeNode p) {
804 <            if (p != null) {
805 <                TreeNode r = p.right, pp, rl;
806 <                if ((rl = p.right = r.left) != null)
807 <                    rl.parent = p;
808 <                if ((pp = r.parent = p.parent) == null)
809 <                    root = r;
810 <                else if (pp.left == p)
811 <                    pp.left = r;
812 <                else
813 <                    pp.right = r;
814 <                r.left = p;
815 <                p.parent = r;
816 <            }
817 <        }
818 <
819 <        /** From CLR */
820 <        private void rotateRight(TreeNode p) {
821 <            if (p != null) {
822 <                TreeNode l = p.left, pp, lr;
823 <                if ((lr = p.left = l.right) != null)
824 <                    lr.parent = p;
825 <                if ((pp = l.parent = p.parent) == null)
826 <                    root = l;
827 <                else if (pp.right == p)
828 <                    pp.right = l;
829 <                else
830 <                    pp.left = l;
831 <                l.right = p;
832 <                p.parent = l;
833 <            }
834 <        }
835 <
836 <        /**
837 <         * Returns the TreeNode (or null if not found) for the given key
838 <         * starting at given root.
839 <         */
840 <        @SuppressWarnings("unchecked") final TreeNode getTreeNode
841 <            (int h, Object k, TreeNode p) {
842 <            Class<?> c = k.getClass();
843 <            while (p != null) {
844 <                int dir, ph;  Object pk; Class<?> pc;
845 <                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
864 <                    dir = (h < ph) ? -1 : 1;
865 <                p = (dir > 0) ? p.right : p.left;
866 <            }
867 <            return null;
572 >        public final K getKey()       { return key; }
573 >        public final V getValue()     { return val; }
574 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
575 >        public final String toString(){ return key + "=" + val; }
576 >        public final V setValue(V value) {
577 >            throw new UnsupportedOperationException();
578          }
579  
580 <        /**
581 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
582 <         * read-lock to call getTreeNode, but during failure to get
583 <         * lock, searches along next links.
584 <         */
585 <        final Object getValue(int h, Object k) {
586 <            Node r = null;
877 <            int c = getState(); // Must read lock state first
878 <            for (Node e = first; e != null; e = e.next) {
879 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
880 <                    try {
881 <                        r = getTreeNode(h, k, root);
882 <                    } finally {
883 <                        releaseShared(0);
884 <                    }
885 <                    break;
886 <                }
887 <                else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
888 <                    r = e;
889 <                    break;
890 <                }
891 <                else
892 <                    c = getState();
893 <            }
894 <            return r == null ? null : r.val;
580 >        public final boolean equals(Object o) {
581 >            Object k, v, u; Map.Entry<?,?> e;
582 >            return ((o instanceof Map.Entry) &&
583 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
584 >                    (v = e.getValue()) != null &&
585 >                    (k == key || k.equals(key)) &&
586 >                    (v == (u = val) || v.equals(u)));
587          }
588  
589          /**
590 <         * Finds or adds a node.
899 <         * @return null if added
590 >         * Virtualized support for map.get(); overridden in subclasses.
591           */
592 <        @SuppressWarnings("unchecked") final TreeNode putTreeNode
593 <            (int h, Object k, Object v) {
594 <            Class<?> c = k.getClass();
595 <            TreeNode pp = root, p = null;
596 <            int dir = 0;
597 <            while (pp != null) { // find existing node or leaf to insert at
598 <                int ph;  Object pk; Class<?> pc;
599 <                p = pp;
600 <                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
928 <                    dir = (h < ph) ? -1 : 1;
929 <                pp = (dir > 0) ? p.right : p.left;
930 <            }
931 <
932 <            TreeNode f = first;
933 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
934 <            if (p == null)
935 <                root = x;
936 <            else { // attach and rebalance; adapted from CLR
937 <                TreeNode xp, xpp;
938 <                if (f != null)
939 <                    f.prev = x;
940 <                if (dir <= 0)
941 <                    p.left = x;
942 <                else
943 <                    p.right = x;
944 <                x.red = true;
945 <                while (x != null && (xp = x.parent) != null && xp.red &&
946 <                       (xpp = xp.parent) != null) {
947 <                    TreeNode xppl = xpp.left;
948 <                    if (xp == xppl) {
949 <                        TreeNode y = xpp.right;
950 <                        if (y != null && y.red) {
951 <                            y.red = false;
952 <                            xp.red = false;
953 <                            xpp.red = true;
954 <                            x = xpp;
955 <                        }
956 <                        else {
957 <                            if (x == xp.right) {
958 <                                rotateLeft(x = xp);
959 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
960 <                            }
961 <                            if (xp != null) {
962 <                                xp.red = false;
963 <                                if (xpp != null) {
964 <                                    xpp.red = true;
965 <                                    rotateRight(xpp);
966 <                                }
967 <                            }
968 <                        }
969 <                    }
970 <                    else {
971 <                        TreeNode y = xppl;
972 <                        if (y != null && y.red) {
973 <                            y.red = false;
974 <                            xp.red = false;
975 <                            xpp.red = true;
976 <                            x = xpp;
977 <                        }
978 <                        else {
979 <                            if (x == xp.left) {
980 <                                rotateRight(x = xp);
981 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
982 <                            }
983 <                            if (xp != null) {
984 <                                xp.red = false;
985 <                                if (xpp != null) {
986 <                                    xpp.red = true;
987 <                                    rotateLeft(xpp);
988 <                                }
989 <                            }
990 <                        }
991 <                    }
992 <                }
993 <                TreeNode r = root;
994 <                if (r != null && r.red)
995 <                    r.red = false;
592 >        Node<K,V> find(int h, Object k) {
593 >            Node<K,V> e = this;
594 >            if (k != null) {
595 >                do {
596 >                    K ek;
597 >                    if (e.hash == h &&
598 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
599 >                        return e;
600 >                } while ((e = e.next) != null);
601              }
602              return null;
603          }
999
1000        /**
1001         * Removes the given node, that must be present before this
1002         * call.  This is messier than typical red-black deletion code
1003         * because we cannot swap the contents of an interior node
1004         * with a leaf successor that is pinned by "next" pointers
1005         * that are accessible independently of lock. So instead we
1006         * swap the tree linkages.
1007         */
1008        final void deleteTreeNode(TreeNode p) {
1009            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
1010            TreeNode pred = p.prev;
1011            if (pred == null)
1012                first = next;
1013            else
1014                pred.next = next;
1015            if (next != null)
1016                next.prev = pred;
1017            TreeNode replacement;
1018            TreeNode pl = p.left;
1019            TreeNode pr = p.right;
1020            if (pl != null && pr != null) {
1021                TreeNode s = pr, sl;
1022                while ((sl = s.left) != null) // find successor
1023                    s = sl;
1024                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
1025                TreeNode sr = s.right;
1026                TreeNode pp = p.parent;
1027                if (s == pr) { // p was s's direct parent
1028                    p.parent = s;
1029                    s.right = p;
1030                }
1031                else {
1032                    TreeNode sp = s.parent;
1033                    if ((p.parent = sp) != null) {
1034                        if (s == sp.left)
1035                            sp.left = p;
1036                        else
1037                            sp.right = p;
1038                    }
1039                    if ((s.right = pr) != null)
1040                        pr.parent = s;
1041                }
1042                p.left = null;
1043                if ((p.right = sr) != null)
1044                    sr.parent = p;
1045                if ((s.left = pl) != null)
1046                    pl.parent = s;
1047                if ((s.parent = pp) == null)
1048                    root = s;
1049                else if (p == pp.left)
1050                    pp.left = s;
1051                else
1052                    pp.right = s;
1053                replacement = sr;
1054            }
1055            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                }
1063                replacement = p;
1064            }
1065            else {
1066                replacement.parent = pp;
1067                if (pp == null)
1068                    root = replacement;
1069                else if (p == pp.left)
1070                    pp.left = replacement;
1071                else
1072                    pp.right = replacement;
1073                p.left = p.right = p.parent = null;
1074            }
1075            if (!p.red) { // rebalance, from CLR
1076                TreeNode x = replacement;
1077                while (x != null) {
1078                    TreeNode xp, xpl;
1079                    if (x.red || (xp = x.parent) == null) {
1080                        x.red = false;
1081                        break;
1082                    }
1083                    if (x == (xpl = xp.left)) {
1084                        TreeNode sib = xp.right;
1085                        if (sib != null && sib.red) {
1086                            sib.red = false;
1087                            xp.red = true;
1088                            rotateLeft(xp);
1089                            sib = (xp = x.parent) == null ? null : xp.right;
1090                        }
1091                        if (sib == null)
1092                            x = xp;
1093                        else {
1094                            TreeNode sl = sib.left, sr = sib.right;
1095                            if ((sr == null || !sr.red) &&
1096                                (sl == null || !sl.red)) {
1097                                sib.red = true;
1098                                x = xp;
1099                            }
1100                            else {
1101                                if (sr == null || !sr.red) {
1102                                    if (sl != null)
1103                                        sl.red = false;
1104                                    sib.red = true;
1105                                    rotateRight(sib);
1106                                    sib = (xp = x.parent) == null ? null : xp.right;
1107                                }
1108                                if (sib != null) {
1109                                    sib.red = (xp == null) ? false : xp.red;
1110                                    if ((sr = sib.right) != null)
1111                                        sr.red = false;
1112                                }
1113                                if (xp != null) {
1114                                    xp.red = false;
1115                                    rotateLeft(xp);
1116                                }
1117                                x = root;
1118                            }
1119                        }
1120                    }
1121                    else { // symmetric
1122                        TreeNode sib = xpl;
1123                        if (sib != null && sib.red) {
1124                            sib.red = false;
1125                            xp.red = true;
1126                            rotateRight(xp);
1127                            sib = (xp = x.parent) == null ? null : xp.left;
1128                        }
1129                        if (sib == null)
1130                            x = xp;
1131                        else {
1132                            TreeNode sl = sib.left, sr = sib.right;
1133                            if ((sl == null || !sl.red) &&
1134                                (sr == null || !sr.red)) {
1135                                sib.red = true;
1136                                x = xp;
1137                            }
1138                            else {
1139                                if (sl == null || !sl.red) {
1140                                    if (sr != null)
1141                                        sr.red = false;
1142                                    sib.red = true;
1143                                    rotateLeft(sib);
1144                                    sib = (xp = x.parent) == null ? null : xp.left;
1145                                }
1146                                if (sib != null) {
1147                                    sib.red = (xp == null) ? false : xp.red;
1148                                    if ((sl = sib.left) != null)
1149                                        sl.red = false;
1150                                }
1151                                if (xp != null) {
1152                                    xp.red = false;
1153                                    rotateRight(xp);
1154                                }
1155                                x = root;
1156                            }
1157                        }
1158                    }
1159                }
1160            }
1161            if (p == replacement && (pp = p.parent) != null) {
1162                if (p == pp.left) // detach pointers
1163                    pp.left = null;
1164                else if (p == pp.right)
1165                    pp.right = null;
1166                p.parent = null;
1167            }
1168        }
604      }
605  
606 <    /* ---------------- Collision reduction methods -------------- */
606 >    /* ---------------- Static utilities -------------- */
607  
608      /**
609 <     * Spreads higher bits to lower, and also forces top 2 bits to 0.
610 <     * Because the table uses power-of-two masking, sets of hashes
611 <     * that vary only in bits above the current mask will always
612 <     * collide. (Among known examples are sets of Float keys holding
613 <     * consecutive whole numbers in small tables.)  To counter this,
614 <     * we apply a transform that spreads the impact of higher bits
609 >     * Spreads (XORs) higher bits of hash to lower and also forces top
610 >     * bit to 0. Because the table uses power-of-two masking, sets of
611 >     * hashes that vary only in bits above the current mask will
612 >     * always collide. (Among known examples are sets of Float keys
613 >     * holding consecutive whole numbers in small tables.)  So we
614 >     * apply a transform that spreads the impact of higher bits
615       * downward. There is a tradeoff between speed, utility, and
616       * quality of bit-spreading. Because many common sets of hashes
617 <     * are already reasonably distributed across bits (so don't benefit
618 <     * from spreading), and because we use trees to handle large sets
619 <     * of collisions in bins, we don't need excessively high quality.
620 <     */
621 <    private static final int spread(int h) {
622 <        h ^= (h >>> 18) ^ (h >>> 12);
1188 <        return (h ^ (h >>> 10)) & HASH_BITS;
1189 <    }
1190 <
1191 <    /**
1192 <     * Replaces a list bin with a tree bin. Call only when locked.
1193 <     * Fails to replace if the given key is non-comparable or table
1194 <     * is, or needs, resizing.
1195 <     */
1196 <    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1197 <        if ((key instanceof Comparable) &&
1198 <            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
1199 <            TreeBin t = new TreeBin();
1200 <            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));
1203 <        }
1204 <    }
1205 <
1206 <    /* ---------------- Internal access and update methods -------------- */
1207 <
1208 <    /** Implementation for get and containsKey */
1209 <    private final Object internalGet(Object k) {
1210 <        int h = spread(k.hashCode());
1211 <        retry: for (Node[] tab = table; tab != null;) {
1212 <            Node e, p; Object ek, ev; int eh;      // locals to read fields once
1213 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1214 <                if ((eh = e.hash) == MOVED) {
1215 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1216 <                        return ((TreeBin)ek).getValue(h, k);
1217 <                    else {                        // restart with new table
1218 <                        tab = (Node[])ek;
1219 <                        continue retry;
1220 <                    }
1221 <                }
1222 <                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1223 <                         ((ek = e.key) == k || k.equals(ek)))
1224 <                    return ev;
1225 <            }
1226 <            break;
1227 <        }
1228 <        return null;
1229 <    }
1230 <
1231 <    /**
1232 <     * Implementation for the four public remove/replace methods:
1233 <     * Replaces node value with v, conditional upon match of cv if
1234 <     * non-null.  If resulting value is null, delete.
617 >     * are already reasonably distributed (so don't benefit from
618 >     * spreading), and because we use trees to handle large sets of
619 >     * collisions in bins, we just XOR some shifted bits in the
620 >     * cheapest possible way to reduce systematic lossage, as well as
621 >     * to incorporate impact of the highest bits that would otherwise
622 >     * never be used in index calculations because of table bounds.
623       */
624 <    private final Object internalReplace(Object k, Object v, Object cv) {
625 <        int h = spread(k.hashCode());
1238 <        Object oldVal = null;
1239 <        for (Node[] tab = table;;) {
1240 <            Node f; int i, fh; Object fk;
1241 <            if (tab == null ||
1242 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1243 <                break;
1244 <            else if ((fh = f.hash) == MOVED) {
1245 <                if ((fk = f.key) instanceof TreeBin) {
1246 <                    TreeBin t = (TreeBin)fk;
1247 <                    boolean validated = false;
1248 <                    boolean deleted = false;
1249 <                    t.acquire(0);
1250 <                    try {
1251 <                        if (tabAt(tab, i) == f) {
1252 <                            validated = true;
1253 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1254 <                            if (p != null) {
1255 <                                Object pv = p.val;
1256 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1257 <                                    oldVal = pv;
1258 <                                    if ((p.val = v) == null) {
1259 <                                        deleted = true;
1260 <                                        t.deleteTreeNode(p);
1261 <                                    }
1262 <                                }
1263 <                            }
1264 <                        }
1265 <                    } finally {
1266 <                        t.release(0);
1267 <                    }
1268 <                    if (validated) {
1269 <                        if (deleted)
1270 <                            counter.add(-1L);
1271 <                        break;
1272 <                    }
1273 <                }
1274 <                else
1275 <                    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);
1282 <            }
1283 <            else if (f.casHash(fh, fh | LOCKED)) {
1284 <                boolean validated = false;
1285 <                boolean deleted = false;
1286 <                try {
1287 <                    if (tabAt(tab, i) == f) {
1288 <                        validated = true;
1289 <                        for (Node e = f, pred = null;;) {
1290 <                            Object ek, ev;
1291 <                            if ((e.hash & HASH_BITS) == h &&
1292 <                                ((ev = e.val) != null) &&
1293 <                                ((ek = e.key) == k || k.equals(ek))) {
1294 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1295 <                                    oldVal = ev;
1296 <                                    if ((e.val = v) == null) {
1297 <                                        deleted = true;
1298 <                                        Node en = e.next;
1299 <                                        if (pred != null)
1300 <                                            pred.next = en;
1301 <                                        else
1302 <                                            setTabAt(tab, i, en);
1303 <                                    }
1304 <                                }
1305 <                                break;
1306 <                            }
1307 <                            pred = e;
1308 <                            if ((e = e.next) == null)
1309 <                                break;
1310 <                        }
1311 <                    }
1312 <                } finally {
1313 <                    if (!f.casHash(fh | LOCKED, fh)) {
1314 <                        f.hash = fh;
1315 <                        synchronized (f) { f.notifyAll(); };
1316 <                    }
1317 <                }
1318 <                if (validated) {
1319 <                    if (deleted)
1320 <                        counter.add(-1L);
1321 <                    break;
1322 <                }
1323 <            }
1324 <        }
1325 <        return oldVal;
1326 <    }
1327 <
1328 <    /*
1329 <     * Internal versions of the six insertion methods, each a
1330 <     * little more complicated than the last. All have
1331 <     * the same basic structure as the first (internalPut):
1332 <     *  1. If table uninitialized, create
1333 <     *  2. If bin empty, try to CAS new node
1334 <     *  3. If bin stale, use new table
1335 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1336 <     *  5. Lock and validate; if valid, scan and add or update
1337 <     *
1338 <     * The others interweave other checks and/or alternative actions:
1339 <     *  * Plain put checks for and performs resize after insertion.
1340 <     *  * putIfAbsent prescans for mapping without lock (and fails to add
1341 <     *    if present), which also makes pre-emptive resize checks worthwhile.
1342 <     *  * computeIfAbsent extends form used in putIfAbsent with additional
1343 <     *    mechanics to deal with, calls, potential exceptions and null
1344 <     *    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.
1354 <     */
1355 <
1356 <    /** Implementation for put */
1357 <    private final Object internalPut(Object k, Object v) {
1358 <        int h = spread(k.hashCode());
1359 <        int count = 0;
1360 <        for (Node[] tab = table;;) {
1361 <            int i; Node f; int fh; Object fk;
1362 <            if (tab == null)
1363 <                tab = initTable();
1364 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1365 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1366 <                    break;                   // no lock when adding to empty bin
1367 <            }
1368 <            else if ((fh = f.hash) == MOVED) {
1369 <                if ((fk = f.key) instanceof TreeBin) {
1370 <                    TreeBin t = (TreeBin)fk;
1371 <                    Object oldVal = null;
1372 <                    t.acquire(0);
1373 <                    try {
1374 <                        if (tabAt(tab, i) == f) {
1375 <                            count = 2;
1376 <                            TreeNode p = t.putTreeNode(h, k, v);
1377 <                            if (p != null) {
1378 <                                oldVal = p.val;
1379 <                                p.val = v;
1380 <                            }
1381 <                        }
1382 <                    } finally {
1383 <                        t.release(0);
1384 <                    }
1385 <                    if (count != 0) {
1386 <                        if (oldVal != null)
1387 <                            return oldVal;
1388 <                        break;
1389 <                    }
1390 <                }
1391 <                else
1392 <                    tab = (Node[])fk;
1393 <            }
1394 <            else if ((fh & LOCKED) != 0) {
1395 <                checkForResize();
1396 <                f.tryAwaitLock(tab, i);
1397 <            }
1398 <            else if (f.casHash(fh, fh | LOCKED)) {
1399 <                Object oldVal = null;
1400 <                try {                        // needed in case equals() throws
1401 <                    if (tabAt(tab, i) == f) {
1402 <                        count = 1;
1403 <                        for (Node e = f;; ++count) {
1404 <                            Object ek, ev;
1405 <                            if ((e.hash & HASH_BITS) == h &&
1406 <                                (ev = e.val) != null &&
1407 <                                ((ek = e.key) == k || k.equals(ek))) {
1408 <                                oldVal = ev;
1409 <                                e.val = v;
1410 <                                break;
1411 <                            }
1412 <                            Node last = e;
1413 <                            if ((e = e.next) == null) {
1414 <                                last.next = new Node(h, k, v, null);
1415 <                                if (count >= TREE_THRESHOLD)
1416 <                                    replaceWithTreeBin(tab, i, k);
1417 <                                break;
1418 <                            }
1419 <                        }
1420 <                    }
1421 <                } finally {                  // unlock and signal if needed
1422 <                    if (!f.casHash(fh | LOCKED, fh)) {
1423 <                        f.hash = fh;
1424 <                        synchronized (f) { f.notifyAll(); };
1425 <                    }
1426 <                }
1427 <                if (count != 0) {
1428 <                    if (oldVal != null)
1429 <                        return oldVal;
1430 <                    if (tab.length <= 64)
1431 <                        count = 2;
1432 <                    break;
1433 <                }
1434 <            }
1435 <        }
1436 <        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();
1540 <        return null;
1541 <    }
1542 <
1543 <    /** Implementation for computeIfAbsent */
1544 <    private final Object internalComputeIfAbsent(K k,
1545 <                                                 Fun<? super K, ?> mf) {
1546 <        int h = spread(k.hashCode());
1547 <        Object val = null;
1548 <        int count = 0;
1549 <        for (Node[] tab = table;;) {
1550 <            Node f; int i, fh; Object fk, fv;
1551 <            if (tab == null)
1552 <                tab = initTable();
1553 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1554 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1555 <                if (casTabAt(tab, i, null, node)) {
1556 <                    count = 1;
1557 <                    try {
1558 <                        if ((val = mf.apply(k)) != null)
1559 <                            node.val = val;
1560 <                    } finally {
1561 <                        if (val == null)
1562 <                            setTabAt(tab, i, null);
1563 <                        if (!node.casHash(fh, h)) {
1564 <                            node.hash = h;
1565 <                            synchronized (node) { node.notifyAll(); };
1566 <                        }
1567 <                    }
1568 <                }
1569 <                if (count != 0)
1570 <                    break;
1571 <            }
1572 <            else if ((fh = f.hash) == MOVED) {
1573 <                if ((fk = f.key) instanceof TreeBin) {
1574 <                    TreeBin t = (TreeBin)fk;
1575 <                    boolean added = false;
1576 <                    t.acquire(0);
1577 <                    try {
1578 <                        if (tabAt(tab, i) == f) {
1579 <                            count = 1;
1580 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1581 <                            if (p != null)
1582 <                                val = p.val;
1583 <                            else if ((val = mf.apply(k)) != null) {
1584 <                                added = true;
1585 <                                count = 2;
1586 <                                t.putTreeNode(h, k, val);
1587 <                            }
1588 <                        }
1589 <                    } finally {
1590 <                        t.release(0);
1591 <                    }
1592 <                    if (count != 0) {
1593 <                        if (!added)
1594 <                            return val;
1595 <                        break;
1596 <                    }
1597 <                }
1598 <                else
1599 <                    tab = (Node[])fk;
1600 <            }
1601 <            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1602 <                     ((fk = f.key) == k || k.equals(fk)))
1603 <                return fv;
1604 <            else {
1605 <                Node g = f.next;
1606 <                if (g != null) {
1607 <                    for (Node e = g;;) {
1608 <                        Object ek, ev;
1609 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1610 <                            ((ek = e.key) == k || k.equals(ek)))
1611 <                            return ev;
1612 <                        if ((e = e.next) == null) {
1613 <                            checkForResize();
1614 <                            break;
1615 <                        }
1616 <                    }
1617 <                }
1618 <                if (((fh = f.hash) & LOCKED) != 0) {
1619 <                    checkForResize();
1620 <                    f.tryAwaitLock(tab, i);
1621 <                }
1622 <                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;
1644 <                                }
1645 <                            }
1646 <                        }
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;
1659 <                    }
1660 <                }
1661 <            }
1662 <        }
1663 <        if (val != null) {
1664 <            counter.add(1L);
1665 <            if (count > 1)
1666 <                checkForResize();
1667 <        }
1668 <        return val;
624 >    static final int spread(int h) {
625 >        return (h ^ (h >>> 16)) & HASH_BITS;
626      }
627  
1671    /** Implementation for compute */
1672    @SuppressWarnings("unchecked") private final Object internalCompute
1673        (K k, boolean onlyIfPresent, BiFun<? super K, ? super V, ? extends V> mf) {
1674        int h = spread(k.hashCode());
1675        Object val = null;
1676        int delta = 0;
1677        int count = 0;
1678        for (Node[] tab = table;;) {
1679            Node f; int i, fh; Object fk;
1680            if (tab == null)
1681                tab = initTable();
1682            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1683                if (onlyIfPresent)
1684                    break;
1685                Node node = new Node(fh = h | LOCKED, k, null, null);
1686                if (casTabAt(tab, i, null, node)) {
1687                    try {
1688                        count = 1;
1689                        if ((val = mf.apply(k, null)) != null) {
1690                            node.val = val;
1691                            delta = 1;
1692                        }
1693                    } finally {
1694                        if (delta == 0)
1695                            setTabAt(tab, i, null);
1696                        if (!node.casHash(fh, h)) {
1697                            node.hash = h;
1698                            synchronized (node) { node.notifyAll(); };
1699                        }
1700                    }
1701                }
1702                if (count != 0)
1703                    break;
1704            }
1705            else if ((fh = f.hash) == MOVED) {
1706                if ((fk = f.key) instanceof TreeBin) {
1707                    TreeBin t = (TreeBin)fk;
1708                    t.acquire(0);
1709                    try {
1710                        if (tabAt(tab, i) == f) {
1711                            count = 1;
1712                            TreeNode p = t.getTreeNode(h, k, t.root);
1713                            Object pv = (p == null) ? null : p.val;
1714                            if ((val = mf.apply(k, (V)pv)) != null) {
1715                                if (p != null)
1716                                    p.val = val;
1717                                else {
1718                                    count = 2;
1719                                    delta = 1;
1720                                    t.putTreeNode(h, k, val);
1721                                }
1722                            }
1723                            else if (p != null) {
1724                                delta = -1;
1725                                t.deleteTreeNode(p);
1726                            }
1727                        }
1728                    } finally {
1729                        t.release(0);
1730                    }
1731                    if (count != 0)
1732                        break;
1733                }
1734                else
1735                    tab = (Node[])fk;
1736            }
1737            else if ((fh & LOCKED) != 0) {
1738                checkForResize();
1739                f.tryAwaitLock(tab, i);
1740            }
1741            else if (f.casHash(fh, fh | LOCKED)) {
1742                try {
1743                    if (tabAt(tab, i) == f) {
1744                        count = 1;
1745                        for (Node e = f, pred = null;; ++count) {
1746                            Object ek, ev;
1747                            if ((e.hash & HASH_BITS) == h &&
1748                                (ev = e.val) != null &&
1749                                ((ek = e.key) == k || k.equals(ek))) {
1750                                val = mf.apply(k, (V)ev);
1751                                if (val != null)
1752                                    e.val = val;
1753                                else {
1754                                    delta = -1;
1755                                    Node en = e.next;
1756                                    if (pred != null)
1757                                        pred.next = en;
1758                                    else
1759                                        setTabAt(tab, i, en);
1760                                }
1761                                break;
1762                            }
1763                            pred = e;
1764                            if ((e = e.next) == null) {
1765                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1766                                    pred.next = new Node(h, k, val, null);
1767                                    delta = 1;
1768                                    if (count >= TREE_THRESHOLD)
1769                                        replaceWithTreeBin(tab, i, k);
1770                                }
1771                                break;
1772                            }
1773                        }
1774                    }
1775                } finally {
1776                    if (!f.casHash(fh | LOCKED, fh)) {
1777                        f.hash = fh;
1778                        synchronized (f) { f.notifyAll(); };
1779                    }
1780                }
1781                if (count != 0) {
1782                    if (tab.length <= 64)
1783                        count = 2;
1784                    break;
1785                }
1786            }
1787        }
1788        if (delta != 0) {
1789            counter.add((long)delta);
1790            if (count > 1)
1791                checkForResize();
1792        }
1793        return val;
1794    }
1795
1796    /** Implementation for merge */
1797    @SuppressWarnings("unchecked") private final Object internalMerge
1798        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1799        int h = spread(k.hashCode());
1800        Object val = null;
1801        int delta = 0;
1802        int count = 0;
1803        for (Node[] tab = table;;) {
1804            int i; Node f; int fh; Object fk, fv;
1805            if (tab == null)
1806                tab = initTable();
1807            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1808                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1809                    delta = 1;
1810                    val = v;
1811                    break;
1812                }
1813            }
1814            else if ((fh = f.hash) == MOVED) {
1815                if ((fk = f.key) instanceof TreeBin) {
1816                    TreeBin t = (TreeBin)fk;
1817                    t.acquire(0);
1818                    try {
1819                        if (tabAt(tab, i) == f) {
1820                            count = 1;
1821                            TreeNode p = t.getTreeNode(h, k, t.root);
1822                            val = (p == null) ? v : mf.apply((V)p.val, v);
1823                            if (val != null) {
1824                                if (p != null)
1825                                    p.val = val;
1826                                else {
1827                                    count = 2;
1828                                    delta = 1;
1829                                    t.putTreeNode(h, k, val);
1830                                }
1831                            }
1832                            else if (p != null) {
1833                                delta = -1;
1834                                t.deleteTreeNode(p);
1835                            }
1836                        }
1837                    } finally {
1838                        t.release(0);
1839                    }
1840                    if (count != 0)
1841                        break;
1842                }
1843                else
1844                    tab = (Node[])fk;
1845            }
1846            else if ((fh & LOCKED) != 0) {
1847                checkForResize();
1848                f.tryAwaitLock(tab, i);
1849            }
1850            else if (f.casHash(fh, fh | LOCKED)) {
1851                try {
1852                    if (tabAt(tab, i) == f) {
1853                        count = 1;
1854                        for (Node e = f, pred = null;; ++count) {
1855                            Object ek, ev;
1856                            if ((e.hash & HASH_BITS) == h &&
1857                                (ev = e.val) != null &&
1858                                ((ek = e.key) == k || k.equals(ek))) {
1859                                val = mf.apply(v, (V)ev);
1860                                if (val != null)
1861                                    e.val = val;
1862                                else {
1863                                    delta = -1;
1864                                    Node en = e.next;
1865                                    if (pred != null)
1866                                        pred.next = en;
1867                                    else
1868                                        setTabAt(tab, i, en);
1869                                }
1870                                break;
1871                            }
1872                            pred = e;
1873                            if ((e = e.next) == null) {
1874                                val = v;
1875                                pred.next = new Node(h, k, val, null);
1876                                delta = 1;
1877                                if (count >= TREE_THRESHOLD)
1878                                    replaceWithTreeBin(tab, i, k);
1879                                break;
1880                            }
1881                        }
1882                    }
1883                } finally {
1884                    if (!f.casHash(fh | LOCKED, fh)) {
1885                        f.hash = fh;
1886                        synchronized (f) { f.notifyAll(); };
1887                    }
1888                }
1889                if (count != 0) {
1890                    if (tab.length <= 64)
1891                        count = 2;
1892                    break;
1893                }
1894            }
1895        }
1896        if (delta != 0) {
1897            counter.add((long)delta);
1898            if (count > 1)
1899                checkForResize();
1900        }
1901        return val;
1902    }
1903
1904    /** Implementation for putAll */
1905    private final void internalPutAll(Map<?, ?> m) {
1906        tryPresize(m.size());
1907        long delta = 0L;     // number of uncommitted additions
1908        boolean npe = false; // to throw exception on exit for nulls
1909        try {                // to clean up counts on other exceptions
1910            for (Map.Entry<?, ?> entry : m.entrySet()) {
1911                Object k, v;
1912                if (entry == null || (k = entry.getKey()) == null ||
1913                    (v = entry.getValue()) == null) {
1914                    npe = true;
1915                    break;
1916                }
1917                int h = spread(k.hashCode());
1918                for (Node[] tab = table;;) {
1919                    int i; Node f; int fh; Object fk;
1920                    if (tab == null)
1921                        tab = initTable();
1922                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1923                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1924                            ++delta;
1925                            break;
1926                        }
1927                    }
1928                    else if ((fh = f.hash) == MOVED) {
1929                        if ((fk = f.key) instanceof TreeBin) {
1930                            TreeBin t = (TreeBin)fk;
1931                            boolean validated = false;
1932                            t.acquire(0);
1933                            try {
1934                                if (tabAt(tab, i) == f) {
1935                                    validated = true;
1936                                    TreeNode p = t.getTreeNode(h, k, t.root);
1937                                    if (p != null)
1938                                        p.val = v;
1939                                    else {
1940                                        t.putTreeNode(h, k, v);
1941                                        ++delta;
1942                                    }
1943                                }
1944                            } finally {
1945                                t.release(0);
1946                            }
1947                            if (validated)
1948                                break;
1949                        }
1950                        else
1951                            tab = (Node[])fk;
1952                    }
1953                    else if ((fh & LOCKED) != 0) {
1954                        counter.add(delta);
1955                        delta = 0L;
1956                        checkForResize();
1957                        f.tryAwaitLock(tab, i);
1958                    }
1959                    else if (f.casHash(fh, fh | LOCKED)) {
1960                        int count = 0;
1961                        try {
1962                            if (tabAt(tab, i) == f) {
1963                                count = 1;
1964                                for (Node e = f;; ++count) {
1965                                    Object ek, ev;
1966                                    if ((e.hash & HASH_BITS) == h &&
1967                                        (ev = e.val) != null &&
1968                                        ((ek = e.key) == k || k.equals(ek))) {
1969                                        e.val = v;
1970                                        break;
1971                                    }
1972                                    Node last = e;
1973                                    if ((e = e.next) == null) {
1974                                        ++delta;
1975                                        last.next = new Node(h, k, v, null);
1976                                        if (count >= TREE_THRESHOLD)
1977                                            replaceWithTreeBin(tab, i, k);
1978                                        break;
1979                                    }
1980                                }
1981                            }
1982                        } finally {
1983                            if (!f.casHash(fh | LOCKED, fh)) {
1984                                f.hash = fh;
1985                                synchronized (f) { f.notifyAll(); };
1986                            }
1987                        }
1988                        if (count != 0) {
1989                            if (count > 1) {
1990                                counter.add(delta);
1991                                delta = 0L;
1992                                checkForResize();
1993                            }
1994                            break;
1995                        }
1996                    }
1997                }
1998            }
1999        } finally {
2000            if (delta != 0)
2001                counter.add(delta);
2002        }
2003        if (npe)
2004            throw new NullPointerException();
2005    }
2006
2007    /* ---------------- Table Initialization and Resizing -------------- */
2008
628      /**
629       * Returns a power of two table size for the given desired capacity.
630       * See Hackers Delight, sec 3.2
# Line 2021 | Line 640 | public class ConcurrentHashMap<K, V>
640      }
641  
642      /**
643 <     * Initializes table, using the size recorded in sizeCtl.
643 >     * Returns x's Class if it is of the form "class C implements
644 >     * Comparable<C>", else null.
645       */
646 <    private final Node[] initTable() {
647 <        Node[] tab; int sc;
648 <        while ((tab = table) == null) {
649 <            if ((sc = sizeCtl) < 0)
650 <                Thread.yield(); // lost initialization race; just spin
651 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
652 <                try {
653 <                    if ((tab = table) == null) {
654 <                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
655 <                        tab = table = new Node[n];
656 <                        sc = n - (n >>> 2);
657 <                    }
658 <                } finally {
2039 <                    sizeCtl = sc;
2040 <                }
2041 <                break;
2042 <            }
2043 <        }
2044 <        return tab;
2045 <    }
2046 <
2047 <    /**
2048 <     * If table is too small and not already resizing, creates next
2049 <     * table and transfers bins.  Rechecks occupancy after a transfer
2050 <     * to see if another resize is already needed because resizings
2051 <     * are lagging additions.
2052 <     */
2053 <    private final void checkForResize() {
2054 <        Node[] tab; int n, sc;
2055 <        while ((tab = table) != null &&
2056 <               (n = tab.length) < MAXIMUM_CAPACITY &&
2057 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
2058 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
2059 <            try {
2060 <                if (tab == table) {
2061 <                    table = rebuild(tab);
2062 <                    sc = (n << 1) - (n >>> 1);
646 >    static Class<?> comparableClassFor(Object x) {
647 >        if (x instanceof Comparable) {
648 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
649 >            if ((c = x.getClass()) == String.class) // bypass checks
650 >                return c;
651 >            if ((ts = c.getGenericInterfaces()) != null) {
652 >                for (int i = 0; i < ts.length; ++i) {
653 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
654 >                        ((p = (ParameterizedType)t).getRawType() ==
655 >                         Comparable.class) &&
656 >                        (as = p.getActualTypeArguments()) != null &&
657 >                        as.length == 1 && as[0] == c) // type arg is c
658 >                        return c;
659                  }
2064            } finally {
2065                sizeCtl = sc;
660              }
661          }
662 +        return null;
663      }
664  
665      /**
666 <     * Tries to presize table to accommodate the given number of elements.
667 <     *
2073 <     * @param size number of elements (doesn't need to be perfectly accurate)
666 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
667 >     * class), else 0.
668       */
669 <    private final void tryPresize(int size) {
670 <        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
671 <            tableSizeFor(size + (size >>> 1) + 1);
672 <        int sc;
2079 <        while ((sc = sizeCtl) >= 0) {
2080 <            Node[] tab = table; int n;
2081 <            if (tab == null || (n = tab.length) == 0) {
2082 <                n = (sc > c) ? sc : c;
2083 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
2084 <                    try {
2085 <                        if (table == tab) {
2086 <                            table = new Node[n];
2087 <                            sc = n - (n >>> 2);
2088 <                        }
2089 <                    } finally {
2090 <                        sizeCtl = sc;
2091 <                    }
2092 <                }
2093 <            }
2094 <            else if (c <= sc || n >= MAXIMUM_CAPACITY)
2095 <                break;
2096 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
2097 <                try {
2098 <                    if (table == tab) {
2099 <                        table = rebuild(tab);
2100 <                        sc = (n << 1) - (n >>> 1);
2101 <                    }
2102 <                } finally {
2103 <                    sizeCtl = sc;
2104 <                }
2105 <            }
2106 <        }
669 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
670 >    static int compareComparables(Class<?> kc, Object k, Object x) {
671 >        return (x == null || x.getClass() != kc ? 0 :
672 >                ((Comparable)k).compareTo(x));
673      }
674  
675 +    /* ---------------- Table element access -------------- */
676 +
677      /*
678 <     * Moves and/or copies the nodes in each bin to new table. See
679 <     * above for explanation.
680 <     *
681 <     * @return the new table
682 <     */
683 <    private static final Node[] rebuild(Node[] tab) {
684 <        int n = tab.length;
685 <        Node[] nextTab = new Node[n << 1];
686 <        Node fwd = new Node(MOVED, nextTab, null, null);
687 <        int[] buffer = null;       // holds bins to revisit; null until needed
688 <        Node rev = null;           // reverse forwarder; null until needed
689 <        int nbuffered = 0;         // the number of bins in buffer list
690 <        int bufferIndex = 0;       // buffer index of current buffered bin
691 <        int bin = n - 1;           // current non-buffered bin or -1 if none
692 <
693 <        for (int i = bin;;) {      // start upwards sweep
694 <            int fh; Node f;
695 <            if ((f = tabAt(tab, i)) == null) {
696 <                if (bin >= 0) {    // Unbuffered; no lock needed (or available)
697 <                    if (!casTabAt(tab, i, f, fwd))
698 <                        continue;
699 <                }
2132 <                else {             // transiently use a locked forwarding node
2133 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2134 <                    if (!casTabAt(tab, i, f, g))
2135 <                        continue;
2136 <                    setTabAt(nextTab, i, null);
2137 <                    setTabAt(nextTab, i + n, null);
2138 <                    setTabAt(tab, i, fwd);
2139 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2140 <                        g.hash = MOVED;
2141 <                        synchronized (g) { g.notifyAll(); }
2142 <                    }
2143 <                }
2144 <            }
2145 <            else if ((fh = f.hash) == MOVED) {
2146 <                Object fk = f.key;
2147 <                if (fk instanceof TreeBin) {
2148 <                    TreeBin t = (TreeBin)fk;
2149 <                    boolean validated = false;
2150 <                    t.acquire(0);
2151 <                    try {
2152 <                        if (tabAt(tab, i) == f) {
2153 <                            validated = true;
2154 <                            splitTreeBin(nextTab, i, t);
2155 <                            setTabAt(tab, i, fwd);
2156 <                        }
2157 <                    } finally {
2158 <                        t.release(0);
2159 <                    }
2160 <                    if (!validated)
2161 <                        continue;
2162 <                }
2163 <            }
2164 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2165 <                boolean validated = false;
2166 <                try {              // split to lo and hi lists; copying as needed
2167 <                    if (tabAt(tab, i) == f) {
2168 <                        validated = true;
2169 <                        splitBin(nextTab, i, f);
2170 <                        setTabAt(tab, i, fwd);
2171 <                    }
2172 <                } finally {
2173 <                    if (!f.casHash(fh | LOCKED, fh)) {
2174 <                        f.hash = fh;
2175 <                        synchronized (f) { f.notifyAll(); };
2176 <                    }
2177 <                }
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];
2208 <            }
2209 <            else
2210 <                return nextTab;
2211 <        }
678 >     * Volatile access methods are used for table elements as well as
679 >     * elements of in-progress next table while resizing.  All uses of
680 >     * the tab arguments must be null checked by callers.  All callers
681 >     * also paranoically precheck that tab's length is not zero (or an
682 >     * equivalent check), thus ensuring that any index argument taking
683 >     * the form of a hash value anded with (length - 1) is a valid
684 >     * index.  Note that, to be correct wrt arbitrary concurrency
685 >     * errors by users, these checks must operate on local variables,
686 >     * which accounts for some odd-looking inline assignments below.
687 >     * Note that calls to setTabAt always occur within locked regions,
688 >     * and so do not need full volatile semantics, but still require
689 >     * ordering to maintain concurrent readability.
690 >     */
691 >
692 >    @SuppressWarnings("unchecked")
693 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
694 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
695 >    }
696 >
697 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
698 >                                        Node<K,V> c, Node<K,V> v) {
699 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
700      }
701  
702 <    /**
703 <     * 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);
702 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
703 >        U.putOrderedObject(tab, ((long)i << ASHIFT) + ABASE, v);
704      }
705  
706 +    /* ---------------- Fields -------------- */
707 +
708      /**
709 <     * Splits a tree bin into lo and hi parts; installs in given table.
709 >     * The array of bins. Lazily initialized upon first insertion.
710 >     * Size is always a power of two. Accessed directly by iterators.
711       */
712 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2249 <        int bit = nextTab.length >>> 1;
2250 <        TreeBin lt = new TreeBin();
2251 <        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);
2263 <            }
2264 <        }
2265 <        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);
2282 <    }
712 >    transient volatile Node<K,V>[] table;
713  
714      /**
715 <     * Implementation for clear. Steps through each bin, removing all
2286 <     * nodes.
715 >     * The next table to use; non-null only while resizing.
716       */
717 <    private final void internalClear() {
2289 <        long delta = 0L; // negative number of deletions
2290 <        int i = 0;
2291 <        Node[] tab = table;
2292 <        while (tab != null && i < tab.length) {
2293 <            int fh; Object fk;
2294 <            Node f = tabAt(tab, i);
2295 <            if (f == null)
2296 <                ++i;
2297 <            else if ((fh = f.hash) == MOVED) {
2298 <                if ((fk = f.key) instanceof TreeBin) {
2299 <                    TreeBin t = (TreeBin)fk;
2300 <                    t.acquire(0);
2301 <                    try {
2302 <                        if (tabAt(tab, i) == f) {
2303 <                            for (Node p = t.first; p != null; p = p.next) {
2304 <                                if (p.val != null) { // (currently always true)
2305 <                                    p.val = null;
2306 <                                    --delta;
2307 <                                }
2308 <                            }
2309 <                            t.first = null;
2310 <                            t.root = null;
2311 <                            ++i;
2312 <                        }
2313 <                    } finally {
2314 <                        t.release(0);
2315 <                    }
2316 <                }
2317 <                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);
2324 <            }
2325 <            else if (f.casHash(fh, fh | LOCKED)) {
2326 <                try {
2327 <                    if (tabAt(tab, i) == f) {
2328 <                        for (Node e = f; e != null; e = e.next) {
2329 <                            if (e.val != null) {  // (currently always true)
2330 <                                e.val = null;
2331 <                                --delta;
2332 <                            }
2333 <                        }
2334 <                        setTabAt(tab, i, null);
2335 <                        ++i;
2336 <                    }
2337 <                } finally {
2338 <                    if (!f.casHash(fh | LOCKED, fh)) {
2339 <                        f.hash = fh;
2340 <                        synchronized (f) { f.notifyAll(); };
2341 <                    }
2342 <                }
2343 <            }
2344 <        }
2345 <        if (delta != 0)
2346 <            counter.add(delta);
2347 <    }
717 >    private transient volatile Node<K,V>[] nextTable;
718  
719 <    /* ----------------Table Traversal -------------- */
719 >    /**
720 >     * Base counter value, used mainly when there is no contention,
721 >     * but also as a fallback during table initialization
722 >     * races. Updated via CAS.
723 >     */
724 >    private transient volatile long baseCount;
725  
726      /**
727 <     * Encapsulates traversal for methods such as containsValue; also
728 <     * serves as a base class for other iterators and bulk tasks.
729 <     *
730 <     * At each step, the iterator snapshots the key ("nextKey") and
731 <     * value ("nextVal") of a valid node (i.e., one that, at point of
732 <     * snapshot, has a non-null user value). Because val fields can
733 <     * change (including to null, indicating deletion), field nextVal
734 <     * 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
2373 <     * reachable upon iterator construction. It might miss some that
2374 <     * were added to a bin after the bin was visited, which is OK wrt
2375 <     * consistency guarantees. Maintaining this property in the face
2376 <     * of possible ongoing resizes requires a fair amount of
2377 <     * bookkeeping state that is difficult to optimize away amidst
2378 <     * volatile accesses.  Even so, traversal maintains reasonable
2379 <     * throughput.
2380 <     *
2381 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2382 <     * However, if the table has been resized, then all future steps
2383 <     * must traverse both the bin at the current index as well as at
2384 <     * (index + baseSize); and so on for further resizings. To
2385 <     * paranoically cope with potential sharing by users of iterators
2386 <     * across threads, iteration terminates if a bounds checks fails
2387 <     * for a table read.
2388 <     *
2389 <     * This class extends ForkJoinTask to streamline parallel
2390 <     * iteration in bulk operations (see BulkTask). This adds only an
2391 <     * int of space overhead, which is close enough to negligible in
2392 <     * cases where it is not needed to not worry about it.  Because
2393 <     * ForkJoinTask is Serializable, but iterators need not be, we
2394 <     * need to add warning suppressions.
2395 <     */
2396 <    @SuppressWarnings("serial") static class Traverser<K,V,R> extends ForkJoinTask<R> {
2397 <        final ConcurrentHashMap<K, V> map;
2398 <        Node next;           // the next entry to use
2399 <        Object nextKey;      // cached key field of next
2400 <        Object nextVal;      // cached val field of next
2401 <        Node[] tab;          // current table; updated if resized
2402 <        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
727 >     * Table initialization and resizing control.  When negative, the
728 >     * table is being initialized or resized: -1 for initialization,
729 >     * else -(1 + the number of active resizing threads).  Otherwise,
730 >     * when table is null, holds the initial table size to use upon
731 >     * creation, or 0 for default. After initialization, holds the
732 >     * next element count value upon which to resize the table.
733 >     */
734 >    private transient volatile int sizeCtl;
735  
736 <        /** Creates iterator for all entries in the table. */
737 <        Traverser(ConcurrentHashMap<K, V> map) {
738 <            this.map = map;
739 <        }
736 >    /**
737 >     * The next table index (plus one) to split while resizing.
738 >     */
739 >    private transient volatile int transferIndex;
740  
741 <        /** Creates iterator for split() methods */
742 <        Traverser(Traverser<K,V,?> it) {
743 <            ConcurrentHashMap<K, V> m; Node[] t;
744 <            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;
2424 <        }
741 >    /**
742 >     * The least available table index to split while resizing.
743 >     */
744 >    private transient volatile int transferOrigin;
745  
746 <        /**
747 <         * Advances next; returns nextVal or null if terminated.
748 <         * See above for explanation.
749 <         */
2430 <        final Object advance() {
2431 <            Node e = next;
2432 <            Object ev = null;
2433 <            outer: do {
2434 <                if (e != null)                  // advance past used/skipped node
2435 <                    e = e.next;
2436 <                while (e == null) {             // get to next non-null bin
2437 <                    ConcurrentHashMap<K, V> m;
2438 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2439 <                    if ((t = tab) != null)
2440 <                        n = t.length;
2441 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2442 <                        n = baseLimit = baseSize = t.length;
2443 <                    else
2444 <                        break outer;
2445 <                    if ((b = baseIndex) >= baseLimit ||
2446 <                        (i = index) < 0 || i >= n)
2447 <                        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);
2457 <                }
2458 <                nextKey = e.key;
2459 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2460 <            next = e;
2461 <            return nextVal = ev;
2462 <        }
746 >    /**
747 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
748 >     */
749 >    private transient volatile int cellsBusy;
750  
751 <        public final void remove() {
752 <            Object k = nextKey;
753 <            if (k == null && (advance() == null || (k = nextKey) == null))
754 <                throw new IllegalStateException();
2468 <            map.internalReplace(k, null, null);
2469 <        }
751 >    /**
752 >     * Table of counter cells. When non-null, size is a power of 2.
753 >     */
754 >    private transient volatile CounterCell[] counterCells;
755  
756 <        public final boolean hasNext() {
757 <            return nextVal != null || advance() != null;
758 <        }
756 >    // views
757 >    private transient KeySetView<K,V> keySet;
758 >    private transient ValuesView<K,V> values;
759 >    private transient EntrySetView<K,V> entrySet;
760  
2475        public final boolean hasMoreElements() { return hasNext(); }
2476        public final void setRawResult(Object x) { }
2477        public R getRawResult() { return null; }
2478        public boolean exec() { return true; }
2479    }
761  
762      /* ---------------- Public operations -------------- */
763  
# Line 2484 | Line 765 | public class ConcurrentHashMap<K, V>
765       * Creates a new, empty map with the default initial table size (16).
766       */
767      public ConcurrentHashMap() {
2487        this.counter = new LongAdder();
768      }
769  
770      /**
# Line 2503 | Line 783 | public class ConcurrentHashMap<K, V>
783          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
784                     MAXIMUM_CAPACITY :
785                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2506        this.counter = new LongAdder();
786          this.sizeCtl = cap;
787      }
788  
# Line 2513 | Line 792 | public class ConcurrentHashMap<K, V>
792       * @param m the map
793       */
794      public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2516        this.counter = new LongAdder();
795          this.sizeCtl = DEFAULT_CAPACITY;
796 <        internalPutAll(m);
796 >        putAll(m);
797      }
798  
799      /**
# Line 2556 | Line 834 | public class ConcurrentHashMap<K, V>
834       * nonpositive
835       */
836      public ConcurrentHashMap(int initialCapacity,
837 <                               float loadFactor, int concurrencyLevel) {
837 >                             float loadFactor, int concurrencyLevel) {
838          if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
839              throw new IllegalArgumentException();
840          if (initialCapacity < concurrencyLevel)   // Use at least as many bins
# Line 2564 | Line 842 | public class ConcurrentHashMap<K, V>
842          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
843          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
844              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2567        this.counter = new LongAdder();
845          this.sizeCtl = cap;
846      }
847  
848 <    /**
2572 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2573 <     * from the given type to {@code Boolean.TRUE}.
2574 <     *
2575 <     * @return the new set
2576 <     */
2577 <    public static <K> KeySetView<K,Boolean> newKeySet() {
2578 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(),
2579 <                                      Boolean.TRUE);
2580 <    }
2581 <
2582 <    /**
2583 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2584 <     * from the given type to {@code Boolean.TRUE}.
2585 <     *
2586 <     * @param initialCapacity The implementation performs internal
2587 <     * sizing to accommodate this many elements.
2588 <     * @throws IllegalArgumentException if the initial capacity of
2589 <     * elements is negative
2590 <     * @return the new set
2591 <     */
2592 <    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2593 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(initialCapacity),
2594 <                                      Boolean.TRUE);
2595 <    }
2596 <
2597 <    /**
2598 <     * {@inheritDoc}
2599 <     */
2600 <    public boolean isEmpty() {
2601 <        return counter.sum() <= 0L; // ignore transient negative values
2602 <    }
848 >    // Original (since JDK1.2) Map methods
849  
850      /**
851       * {@inheritDoc}
852       */
853      public int size() {
854 <        long n = counter.sum();
854 >        long n = sumCount();
855          return ((n < 0L) ? 0 :
856                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
857                  (int)n);
858      }
859  
860      /**
861 <     * Returns the number of mappings. This method should be used
2616 <     * instead of {@link #size} because a ConcurrentHashMap may
2617 <     * contain more mappings than can be represented as an int. The
2618 <     * value returned is a snapshot; the actual count may differ if
2619 <     * there are ongoing concurrent insertions or removals.
2620 <     *
2621 <     * @return the number of mappings
861 >     * {@inheritDoc}
862       */
863 <    public long mappingCount() {
864 <        long n = counter.sum();
2625 <        return (n < 0L) ? 0L : n; // ignore transient negative values
863 >    public boolean isEmpty() {
864 >        return sumCount() <= 0L; // ignore transient negative values
865      }
866  
867      /**
# Line 2636 | Line 875 | public class ConcurrentHashMap<K, V>
875       *
876       * @throws NullPointerException if the specified key is null
877       */
878 <    @SuppressWarnings("unchecked") public V get(Object key) {
879 <        if (key == null)
880 <            throw new NullPointerException();
881 <        return (V)internalGet(key);
882 <    }
883 <
884 <    /**
885 <     * Returns the value to which the specified key is mapped,
886 <     * or the given defaultValue if this map contains no mapping for the key.
887 <     *
888 <     * @param key the key
889 <     * @param defaultValue the value to return if this map contains
890 <     * no mapping for the given key
891 <     * @return the mapping for the key, if present; else the defaultValue
892 <     * @throws NullPointerException if the specified key is null
893 <     */
894 <    @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) {
895 <        if (key == null)
2657 <            throw new NullPointerException();
2658 <        V v = (V) internalGet(key);
2659 <        return v == null ? defaultValue : v;
878 >    public V get(Object key) {
879 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
880 >        int h = spread(key.hashCode());
881 >        if ((tab = table) != null && (n = tab.length) > 0 &&
882 >            (e = tabAt(tab, (n - 1) & h)) != null) {
883 >            if ((eh = e.hash) == h) {
884 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
885 >                    return e.val;
886 >            }
887 >            else if (eh < 0)
888 >                return (p = e.find(h, key)) != null ? p.val : null;
889 >            while ((e = e.next) != null) {
890 >                if (e.hash == h &&
891 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
892 >                    return e.val;
893 >            }
894 >        }
895 >        return null;
896      }
897  
898      /**
899       * Tests if the specified object is a key in this table.
900       *
901 <     * @param  key   possible key
901 >     * @param  key possible key
902       * @return {@code true} if and only if the specified object
903       *         is a key in this table, as determined by the
904       *         {@code equals} method; {@code false} otherwise
905       * @throws NullPointerException if the specified key is null
906       */
907      public boolean containsKey(Object key) {
908 <        if (key == null)
2673 <            throw new NullPointerException();
2674 <        return internalGet(key) != null;
908 >        return get(key) != null;
909      }
910  
911      /**
# Line 2687 | Line 921 | public class ConcurrentHashMap<K, V>
921      public boolean containsValue(Object value) {
922          if (value == null)
923              throw new NullPointerException();
924 <        Object v;
925 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
926 <        while ((v = it.advance()) != null) {
927 <            if (v == value || value.equals(v))
928 <                return true;
924 >        Node<K,V>[] t;
925 >        if ((t = table) != null) {
926 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
927 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
928 >                V v;
929 >                if ((v = p.val) == value || (v != null && value.equals(v)))
930 >                    return true;
931 >            }
932          }
933          return false;
934      }
935  
936      /**
2700     * Legacy method testing if some key maps into the specified value
2701     * in this table.  This method is identical in functionality to
2702     * {@link #containsValue}, and exists solely to ensure
2703     * full compatibility with class {@link java.util.Hashtable},
2704     * which supported this method prior to introduction of the
2705     * Java Collections framework.
2706     *
2707     * @param  value a value to search for
2708     * @return {@code true} if and only if some key maps to the
2709     *         {@code value} argument in this table as
2710     *         determined by the {@code equals} method;
2711     *         {@code false} otherwise
2712     * @throws NullPointerException if the specified value is null
2713     */
2714    public boolean contains(Object value) {
2715        return containsValue(value);
2716    }
2717
2718    /**
937       * Maps the specified key to the specified value in this table.
938       * Neither the key nor the value can be null.
939       *
940 <     * <p> The value can be retrieved by calling the {@code get} method
940 >     * <p>The value can be retrieved by calling the {@code get} method
941       * with a key that is equal to the original key.
942       *
943       * @param key key with which the specified value is to be associated
# Line 2728 | Line 946 | public class ConcurrentHashMap<K, V>
946       *         {@code null} if there was no mapping for {@code key}
947       * @throws NullPointerException if the specified key or value is null
948       */
949 <    @SuppressWarnings("unchecked") public V put(K key, V value) {
950 <        if (key == null || value == null)
949 >    public V put(K key, V value) {
950 >        return putVal(key, value, false);
951 >    }
952 >
953 >    /** Implementation for put and putIfAbsent */
954 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
955 >        if (key == null || value == null) throw new NullPointerException();
956 >        int hash = spread(key.hashCode());
957 >        int binCount = 0;
958 >        for (Node<K,V>[] tab = table;;) {
959 >            Node<K,V> f; int n, i, fh;
960 >            if (tab == null || (n = tab.length) == 0)
961 >                tab = initTable();
962 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
963 >                if (casTabAt(tab, i, null,
964 >                             new Node<K,V>(hash, key, value, null)))
965 >                    break;                   // no lock when adding to empty bin
966 >            }
967 >            else if ((fh = f.hash) == MOVED)
968 >                tab = helpTransfer(tab, f);
969 >            else {
970 >                V oldVal = null;
971 >                synchronized (f) {
972 >                    if (tabAt(tab, i) == f) {
973 >                        if (fh >= 0) {
974 >                            binCount = 1;
975 >                            for (Node<K,V> e = f;; ++binCount) {
976 >                                K ek;
977 >                                if (e.hash == hash &&
978 >                                    ((ek = e.key) == key ||
979 >                                     (ek != null && key.equals(ek)))) {
980 >                                    oldVal = e.val;
981 >                                    if (!onlyIfAbsent)
982 >                                        e.val = value;
983 >                                    break;
984 >                                }
985 >                                Node<K,V> pred = e;
986 >                                if ((e = e.next) == null) {
987 >                                    pred.next = new Node<K,V>(hash, key,
988 >                                                              value, null);
989 >                                    break;
990 >                                }
991 >                            }
992 >                        }
993 >                        else if (f instanceof TreeBin) {
994 >                            Node<K,V> p;
995 >                            binCount = 2;
996 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
997 >                                                           value)) != null) {
998 >                                oldVal = p.val;
999 >                                if (!onlyIfAbsent)
1000 >                                    p.val = value;
1001 >                            }
1002 >                        }
1003 >                    }
1004 >                }
1005 >                if (binCount != 0) {
1006 >                    if (binCount >= TREEIFY_THRESHOLD)
1007 >                        treeifyBin(tab, i);
1008 >                    if (oldVal != null)
1009 >                        return oldVal;
1010 >                    break;
1011 >                }
1012 >            }
1013 >        }
1014 >        addCount(1L, binCount);
1015 >        return null;
1016 >    }
1017 >
1018 >    /**
1019 >     * Copies all of the mappings from the specified map to this one.
1020 >     * These mappings replace any mappings that this map had for any of the
1021 >     * keys currently in the specified map.
1022 >     *
1023 >     * @param m mappings to be stored in this map
1024 >     */
1025 >    public void putAll(Map<? extends K, ? extends V> m) {
1026 >        tryPresize(m.size());
1027 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1028 >            putVal(e.getKey(), e.getValue(), false);
1029 >    }
1030 >
1031 >    /**
1032 >     * Removes the key (and its corresponding value) from this map.
1033 >     * This method does nothing if the key is not in the map.
1034 >     *
1035 >     * @param  key the key that needs to be removed
1036 >     * @return the previous value associated with {@code key}, or
1037 >     *         {@code null} if there was no mapping for {@code key}
1038 >     * @throws NullPointerException if the specified key is null
1039 >     */
1040 >    public V remove(Object key) {
1041 >        return replaceNode(key, null, null);
1042 >    }
1043 >
1044 >    /**
1045 >     * Implementation for the four public remove/replace methods:
1046 >     * Replaces node value with v, conditional upon match of cv if
1047 >     * non-null.  If resulting value is null, delete.
1048 >     */
1049 >    final V replaceNode(Object key, V value, Object cv) {
1050 >        int hash = spread(key.hashCode());
1051 >        for (Node<K,V>[] tab = table;;) {
1052 >            Node<K,V> f; int n, i, fh;
1053 >            if (tab == null || (n = tab.length) == 0 ||
1054 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1055 >                break;
1056 >            else if ((fh = f.hash) == MOVED)
1057 >                tab = helpTransfer(tab, f);
1058 >            else {
1059 >                V oldVal = null;
1060 >                boolean validated = false;
1061 >                synchronized (f) {
1062 >                    if (tabAt(tab, i) == f) {
1063 >                        if (fh >= 0) {
1064 >                            validated = true;
1065 >                            for (Node<K,V> e = f, pred = null;;) {
1066 >                                K ek;
1067 >                                if (e.hash == hash &&
1068 >                                    ((ek = e.key) == key ||
1069 >                                     (ek != null && key.equals(ek)))) {
1070 >                                    V ev = e.val;
1071 >                                    if (cv == null || cv == ev ||
1072 >                                        (ev != null && cv.equals(ev))) {
1073 >                                        oldVal = ev;
1074 >                                        if (value != null)
1075 >                                            e.val = value;
1076 >                                        else if (pred != null)
1077 >                                            pred.next = e.next;
1078 >                                        else
1079 >                                            setTabAt(tab, i, e.next);
1080 >                                    }
1081 >                                    break;
1082 >                                }
1083 >                                pred = e;
1084 >                                if ((e = e.next) == null)
1085 >                                    break;
1086 >                            }
1087 >                        }
1088 >                        else if (f instanceof TreeBin) {
1089 >                            validated = true;
1090 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1091 >                            TreeNode<K,V> r, p;
1092 >                            if ((r = t.root) != null &&
1093 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1094 >                                V pv = p.val;
1095 >                                if (cv == null || cv == pv ||
1096 >                                    (pv != null && cv.equals(pv))) {
1097 >                                    oldVal = pv;
1098 >                                    if (value != null)
1099 >                                        p.val = value;
1100 >                                    else if (t.removeTreeNode(p))
1101 >                                        setTabAt(tab, i, untreeify(t.first));
1102 >                                }
1103 >                            }
1104 >                        }
1105 >                    }
1106 >                }
1107 >                if (validated) {
1108 >                    if (oldVal != null) {
1109 >                        if (value == null)
1110 >                            addCount(-1L, -1);
1111 >                        return oldVal;
1112 >                    }
1113 >                    break;
1114 >                }
1115 >            }
1116 >        }
1117 >        return null;
1118 >    }
1119 >
1120 >    /**
1121 >     * Removes all of the mappings from this map.
1122 >     */
1123 >    public void clear() {
1124 >        long delta = 0L; // negative number of deletions
1125 >        int i = 0;
1126 >        Node<K,V>[] tab = table;
1127 >        while (tab != null && i < tab.length) {
1128 >            int fh;
1129 >            Node<K,V> f = tabAt(tab, i);
1130 >            if (f == null)
1131 >                ++i;
1132 >            else if ((fh = f.hash) == MOVED) {
1133 >                tab = helpTransfer(tab, f);
1134 >                i = 0; // restart
1135 >            }
1136 >            else {
1137 >                synchronized (f) {
1138 >                    if (tabAt(tab, i) == f) {
1139 >                        Node<K,V> p = (fh >= 0 ? f :
1140 >                                       (f instanceof TreeBin) ?
1141 >                                       ((TreeBin<K,V>)f).first : null);
1142 >                        while (p != null) {
1143 >                            --delta;
1144 >                            p = p.next;
1145 >                        }
1146 >                        setTabAt(tab, i++, null);
1147 >                    }
1148 >                }
1149 >            }
1150 >        }
1151 >        if (delta != 0L)
1152 >            addCount(delta, -1);
1153 >    }
1154 >
1155 >    /**
1156 >     * Returns a {@link Set} view of the keys contained in this map.
1157 >     * The set is backed by the map, so changes to the map are
1158 >     * reflected in the set, and vice-versa. The set supports element
1159 >     * removal, which removes the corresponding mapping from this map,
1160 >     * via the {@code Iterator.remove}, {@code Set.remove},
1161 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1162 >     * operations.  It does not support the {@code add} or
1163 >     * {@code addAll} operations.
1164 >     *
1165 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1166 >     * that will never throw {@link ConcurrentModificationException},
1167 >     * and guarantees to traverse elements as they existed upon
1168 >     * construction of the iterator, and may (but is not guaranteed to)
1169 >     * reflect any modifications subsequent to construction.
1170 >     *
1171 >     * @return the set view
1172 >     */
1173 >    public KeySetView<K,V> keySet() {
1174 >        KeySetView<K,V> ks;
1175 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1176 >    }
1177 >
1178 >    /**
1179 >     * Returns a {@link Collection} view of the values contained in this map.
1180 >     * The collection is backed by the map, so changes to the map are
1181 >     * reflected in the collection, and vice-versa.  The collection
1182 >     * supports element removal, which removes the corresponding
1183 >     * mapping from this map, via the {@code Iterator.remove},
1184 >     * {@code Collection.remove}, {@code removeAll},
1185 >     * {@code retainAll}, and {@code clear} operations.  It does not
1186 >     * support the {@code add} or {@code addAll} operations.
1187 >     *
1188 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1189 >     * that will never throw {@link ConcurrentModificationException},
1190 >     * and guarantees to traverse elements as they existed upon
1191 >     * construction of the iterator, and may (but is not guaranteed to)
1192 >     * reflect any modifications subsequent to construction.
1193 >     *
1194 >     * @return the collection view
1195 >     */
1196 >    public Collection<V> values() {
1197 >        ValuesView<K,V> vs;
1198 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1199 >    }
1200 >
1201 >    /**
1202 >     * Returns a {@link Set} view of the mappings contained in this map.
1203 >     * The set is backed by the map, so changes to the map are
1204 >     * reflected in the set, and vice-versa.  The set supports element
1205 >     * removal, which removes the corresponding mapping from the map,
1206 >     * via the {@code Iterator.remove}, {@code Set.remove},
1207 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1208 >     * operations.
1209 >     *
1210 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1211 >     * that will never throw {@link ConcurrentModificationException},
1212 >     * and guarantees to traverse elements as they existed upon
1213 >     * construction of the iterator, and may (but is not guaranteed to)
1214 >     * reflect any modifications subsequent to construction.
1215 >     *
1216 >     * @return the set view
1217 >     */
1218 >    public Set<Map.Entry<K,V>> entrySet() {
1219 >        EntrySetView<K,V> es;
1220 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1221 >    }
1222 >
1223 >    /**
1224 >     * Returns the hash code value for this {@link Map}, i.e.,
1225 >     * the sum of, for each key-value pair in the map,
1226 >     * {@code key.hashCode() ^ value.hashCode()}.
1227 >     *
1228 >     * @return the hash code value for this map
1229 >     */
1230 >    public int hashCode() {
1231 >        int h = 0;
1232 >        Node<K,V>[] t;
1233 >        if ((t = table) != null) {
1234 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1235 >            for (Node<K,V> p; (p = it.advance()) != null; )
1236 >                h += p.key.hashCode() ^ p.val.hashCode();
1237 >        }
1238 >        return h;
1239 >    }
1240 >
1241 >    /**
1242 >     * Returns a string representation of this map.  The string
1243 >     * representation consists of a list of key-value mappings (in no
1244 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1245 >     * mappings are separated by the characters {@code ", "} (comma
1246 >     * and space).  Each key-value mapping is rendered as the key
1247 >     * followed by an equals sign ("{@code =}") followed by the
1248 >     * associated value.
1249 >     *
1250 >     * @return a string representation of this map
1251 >     */
1252 >    public String toString() {
1253 >        Node<K,V>[] t;
1254 >        int f = (t = table) == null ? 0 : t.length;
1255 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1256 >        StringBuilder sb = new StringBuilder();
1257 >        sb.append('{');
1258 >        Node<K,V> p;
1259 >        if ((p = it.advance()) != null) {
1260 >            for (;;) {
1261 >                K k = p.key;
1262 >                V v = p.val;
1263 >                sb.append(k == this ? "(this Map)" : k);
1264 >                sb.append('=');
1265 >                sb.append(v == this ? "(this Map)" : v);
1266 >                if ((p = it.advance()) == null)
1267 >                    break;
1268 >                sb.append(',').append(' ');
1269 >            }
1270 >        }
1271 >        return sb.append('}').toString();
1272 >    }
1273 >
1274 >    /**
1275 >     * Compares the specified object with this map for equality.
1276 >     * Returns {@code true} if the given object is a map with the same
1277 >     * mappings as this map.  This operation may return misleading
1278 >     * results if either map is concurrently modified during execution
1279 >     * of this method.
1280 >     *
1281 >     * @param o object to be compared for equality with this map
1282 >     * @return {@code true} if the specified object is equal to this map
1283 >     */
1284 >    public boolean equals(Object o) {
1285 >        if (o != this) {
1286 >            if (!(o instanceof Map))
1287 >                return false;
1288 >            Map<?,?> m = (Map<?,?>) o;
1289 >            Node<K,V>[] t;
1290 >            int f = (t = table) == null ? 0 : t.length;
1291 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1292 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1293 >                V val = p.val;
1294 >                Object v = m.get(p.key);
1295 >                if (v == null || (v != val && !v.equals(val)))
1296 >                    return false;
1297 >            }
1298 >            for (Map.Entry<?,?> e : m.entrySet()) {
1299 >                Object mk, mv, v;
1300 >                if ((mk = e.getKey()) == null ||
1301 >                    (mv = e.getValue()) == null ||
1302 >                    (v = get(mk)) == null ||
1303 >                    (mv != v && !mv.equals(v)))
1304 >                    return false;
1305 >            }
1306 >        }
1307 >        return true;
1308 >    }
1309 >
1310 >    /**
1311 >     * Stripped-down version of helper class used in previous version,
1312 >     * declared for the sake of serialization compatibility
1313 >     */
1314 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1315 >        private static final long serialVersionUID = 2249069246763182397L;
1316 >        final float loadFactor;
1317 >        Segment(float lf) { this.loadFactor = lf; }
1318 >    }
1319 >
1320 >    /**
1321 >     * Saves the state of the {@code ConcurrentHashMap} instance to a
1322 >     * stream (i.e., serializes it).
1323 >     * @param s the stream
1324 >     * @serialData
1325 >     * the key (Object) and value (Object)
1326 >     * for each key-value mapping, followed by a null pair.
1327 >     * The key-value mappings are emitted in no particular order.
1328 >     */
1329 >    private void writeObject(java.io.ObjectOutputStream s)
1330 >        throws java.io.IOException {
1331 >        // For serialization compatibility
1332 >        // Emulate segment calculation from previous version of this class
1333 >        int sshift = 0;
1334 >        int ssize = 1;
1335 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1336 >            ++sshift;
1337 >            ssize <<= 1;
1338 >        }
1339 >        int segmentShift = 32 - sshift;
1340 >        int segmentMask = ssize - 1;
1341 >        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1342 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1343 >        for (int i = 0; i < segments.length; ++i)
1344 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1345 >        s.putFields().put("segments", segments);
1346 >        s.putFields().put("segmentShift", segmentShift);
1347 >        s.putFields().put("segmentMask", segmentMask);
1348 >        s.writeFields();
1349 >
1350 >        Node<K,V>[] t;
1351 >        if ((t = table) != null) {
1352 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1353 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1354 >                s.writeObject(p.key);
1355 >                s.writeObject(p.val);
1356 >            }
1357 >        }
1358 >        s.writeObject(null);
1359 >        s.writeObject(null);
1360 >        segments = null; // throw away
1361 >    }
1362 >
1363 >    /**
1364 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1365 >     * @param s the stream
1366 >     */
1367 >    private void readObject(java.io.ObjectInputStream s)
1368 >        throws java.io.IOException, ClassNotFoundException {
1369 >        /*
1370 >         * To improve performance in typical cases, we create nodes
1371 >         * while reading, then place in table once size is known.
1372 >         * However, we must also validate uniqueness and deal with
1373 >         * overpopulated bins while doing so, which requires
1374 >         * specialized versions of putVal mechanics.
1375 >         */
1376 >        sizeCtl = -1; // force exclusion for table construction
1377 >        s.defaultReadObject();
1378 >        long size = 0L;
1379 >        Node<K,V> p = null;
1380 >        for (;;) {
1381 >            @SuppressWarnings("unchecked") K k = (K) s.readObject();
1382 >            @SuppressWarnings("unchecked") V v = (V) s.readObject();
1383 >            if (k != null && v != null) {
1384 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1385 >                ++size;
1386 >            }
1387 >            else
1388 >                break;
1389 >        }
1390 >        if (size == 0L)
1391 >            sizeCtl = 0;
1392 >        else {
1393 >            int n;
1394 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1395 >                n = MAXIMUM_CAPACITY;
1396 >            else {
1397 >                int sz = (int)size;
1398 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1399 >            }
1400 >            @SuppressWarnings({"rawtypes","unchecked"})
1401 >                Node<K,V>[] tab = (Node<K,V>[])new Node[n];
1402 >            int mask = n - 1;
1403 >            long added = 0L;
1404 >            while (p != null) {
1405 >                boolean insertAtFront;
1406 >                Node<K,V> next = p.next, first;
1407 >                int h = p.hash, j = h & mask;
1408 >                if ((first = tabAt(tab, j)) == null)
1409 >                    insertAtFront = true;
1410 >                else {
1411 >                    K k = p.key;
1412 >                    if (first.hash < 0) {
1413 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1414 >                        if (t.putTreeVal(h, k, p.val) == null)
1415 >                            ++added;
1416 >                        insertAtFront = false;
1417 >                    }
1418 >                    else {
1419 >                        int binCount = 0;
1420 >                        insertAtFront = true;
1421 >                        Node<K,V> q; K qk;
1422 >                        for (q = first; q != null; q = q.next) {
1423 >                            if (q.hash == h &&
1424 >                                ((qk = q.key) == k ||
1425 >                                 (qk != null && k.equals(qk)))) {
1426 >                                insertAtFront = false;
1427 >                                break;
1428 >                            }
1429 >                            ++binCount;
1430 >                        }
1431 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1432 >                            insertAtFront = false;
1433 >                            ++added;
1434 >                            p.next = first;
1435 >                            TreeNode<K,V> hd = null, tl = null;
1436 >                            for (q = p; q != null; q = q.next) {
1437 >                                TreeNode<K,V> t = new TreeNode<K,V>
1438 >                                    (q.hash, q.key, q.val, null, null);
1439 >                                if ((t.prev = tl) == null)
1440 >                                    hd = t;
1441 >                                else
1442 >                                    tl.next = t;
1443 >                                tl = t;
1444 >                            }
1445 >                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1446 >                        }
1447 >                    }
1448 >                }
1449 >                if (insertAtFront) {
1450 >                    ++added;
1451 >                    p.next = first;
1452 >                    setTabAt(tab, j, p);
1453 >                }
1454 >                p = next;
1455 >            }
1456 >            table = tab;
1457 >            sizeCtl = n - (n >>> 2);
1458 >            baseCount = added;
1459 >        }
1460 >    }
1461 >
1462 >    // ConcurrentMap methods
1463 >
1464 >    /**
1465 >     * {@inheritDoc}
1466 >     *
1467 >     * @return the previous value associated with the specified key,
1468 >     *         or {@code null} if there was no mapping for the key
1469 >     * @throws NullPointerException if the specified key or value is null
1470 >     */
1471 >    public V putIfAbsent(K key, V value) {
1472 >        return putVal(key, value, true);
1473 >    }
1474 >
1475 >    /**
1476 >     * {@inheritDoc}
1477 >     *
1478 >     * @throws NullPointerException if the specified key is null
1479 >     */
1480 >    public boolean remove(Object key, Object value) {
1481 >        if (key == null)
1482 >            throw new NullPointerException();
1483 >        return value != null && replaceNode(key, null, value) != null;
1484 >    }
1485 >
1486 >    /**
1487 >     * {@inheritDoc}
1488 >     *
1489 >     * @throws NullPointerException if any of the arguments are null
1490 >     */
1491 >    public boolean replace(K key, V oldValue, V newValue) {
1492 >        if (key == null || oldValue == null || newValue == null)
1493              throw new NullPointerException();
1494 <        return (V)internalPut(key, value);
1494 >        return replaceNode(key, newValue, oldValue) != null;
1495      }
1496  
1497      /**
# Line 2741 | Line 1501 | public class ConcurrentHashMap<K, V>
1501       *         or {@code null} if there was no mapping for the key
1502       * @throws NullPointerException if the specified key or value is null
1503       */
1504 <    @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) {
1504 >    public V replace(K key, V value) {
1505          if (key == null || value == null)
1506              throw new NullPointerException();
1507 <        return (V)internalPutIfAbsent(key, value);
1507 >        return replaceNode(key, value, null);
1508      }
1509  
1510 +    // Overrides of JDK8+ Map extension method defaults
1511 +
1512      /**
1513 <     * Copies all of the mappings from the specified map to this one.
1514 <     * These mappings replace any mappings that this map had for any of the
1515 <     * keys currently in the specified map.
1513 >     * Returns the value to which the specified key is mapped, or the
1514 >     * given default value if this map contains no mapping for the
1515 >     * key.
1516       *
1517 <     * @param m mappings to be stored in this map
1517 >     * @param key the key whose associated value is to be returned
1518 >     * @param defaultValue the value to return if this map contains
1519 >     * no mapping for the given key
1520 >     * @return the mapping for the key, if present; else the default value
1521 >     * @throws NullPointerException if the specified key is null
1522       */
1523 <    public void putAll(Map<? extends K, ? extends V> m) {
1524 <        internalPutAll(m);
1523 >    public V getOrDefault(Object key, V defaultValue) {
1524 >        V v;
1525 >        return (v = get(key)) == null ? defaultValue : v;
1526 >    }
1527 >
1528 >    public void forEach(BiConsumer<? super K, ? super V> action) {
1529 >        if (action == null) throw new NullPointerException();
1530 >        Node<K,V>[] t;
1531 >        if ((t = table) != null) {
1532 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1533 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1534 >                action.accept(p.key, p.val);
1535 >            }
1536 >        }
1537 >    }
1538 >
1539 >    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1540 >        if (function == null) throw new NullPointerException();
1541 >        Node<K,V>[] t;
1542 >        if ((t = table) != null) {
1543 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1544 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1545 >                V oldValue = p.val;
1546 >                for (K key = p.key;;) {
1547 >                    V newValue = function.apply(key, oldValue);
1548 >                    if (newValue == null)
1549 >                        throw new NullPointerException();
1550 >                    if (replaceNode(key, newValue, oldValue) != null ||
1551 >                        (oldValue = get(key)) == null)
1552 >                        break;
1553 >                }
1554 >            }
1555 >        }
1556      }
1557  
1558      /**
1559       * If the specified key is not already associated with a value,
1560 <     * computes its value using the given mappingFunction and enters
1561 <     * it into the map unless null.  This is equivalent to
1562 <     * <pre> {@code
1563 <     * if (map.containsKey(key))
1564 <     *   return map.get(key);
1565 <     * value = mappingFunction.apply(key);
1566 <     * 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>
1560 >     * attempts to compute its value using the given mapping function
1561 >     * and enters it into this map unless {@code null}.  The entire
1562 >     * method invocation is performed atomically, so the function is
1563 >     * applied at most once per key.  Some attempted update operations
1564 >     * on this map by other threads may be blocked while computation
1565 >     * is in progress, so the computation should be short and simple,
1566 >     * and must not attempt to update any other mappings of this map.
1567       *
1568       * @param key key with which the specified value is to be associated
1569       * @param mappingFunction the function to compute a value
# Line 2797 | Line 1577 | public class ConcurrentHashMap<K, V>
1577       * @throws RuntimeException or Error if the mappingFunction does so,
1578       *         in which case the mapping is left unestablished
1579       */
1580 <    @SuppressWarnings("unchecked") public V computeIfAbsent
2801 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
1580 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1581          if (key == null || mappingFunction == null)
1582              throw new NullPointerException();
1583 <        return (V)internalComputeIfAbsent(key, mappingFunction);
1583 >        int h = spread(key.hashCode());
1584 >        V val = null;
1585 >        int binCount = 0;
1586 >        for (Node<K,V>[] tab = table;;) {
1587 >            Node<K,V> f; int n, i, fh;
1588 >            if (tab == null || (n = tab.length) == 0)
1589 >                tab = initTable();
1590 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1591 >                Node<K,V> r = new ReservationNode<K,V>();
1592 >                synchronized (r) {
1593 >                    if (casTabAt(tab, i, null, r)) {
1594 >                        binCount = 1;
1595 >                        Node<K,V> node = null;
1596 >                        try {
1597 >                            if ((val = mappingFunction.apply(key)) != null)
1598 >                                node = new Node<K,V>(h, key, val, null);
1599 >                        } finally {
1600 >                            setTabAt(tab, i, node);
1601 >                        }
1602 >                    }
1603 >                }
1604 >                if (binCount != 0)
1605 >                    break;
1606 >            }
1607 >            else if ((fh = f.hash) == MOVED)
1608 >                tab = helpTransfer(tab, f);
1609 >            else {
1610 >                boolean added = false;
1611 >                synchronized (f) {
1612 >                    if (tabAt(tab, i) == f) {
1613 >                        if (fh >= 0) {
1614 >                            binCount = 1;
1615 >                            for (Node<K,V> e = f;; ++binCount) {
1616 >                                K ek; V ev;
1617 >                                if (e.hash == h &&
1618 >                                    ((ek = e.key) == key ||
1619 >                                     (ek != null && key.equals(ek)))) {
1620 >                                    val = e.val;
1621 >                                    break;
1622 >                                }
1623 >                                Node<K,V> pred = e;
1624 >                                if ((e = e.next) == null) {
1625 >                                    if ((val = mappingFunction.apply(key)) != null) {
1626 >                                        added = true;
1627 >                                        pred.next = new Node<K,V>(h, key, val, null);
1628 >                                    }
1629 >                                    break;
1630 >                                }
1631 >                            }
1632 >                        }
1633 >                        else if (f instanceof TreeBin) {
1634 >                            binCount = 2;
1635 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1636 >                            TreeNode<K,V> r, p;
1637 >                            if ((r = t.root) != null &&
1638 >                                (p = r.findTreeNode(h, key, null)) != null)
1639 >                                val = p.val;
1640 >                            else if ((val = mappingFunction.apply(key)) != null) {
1641 >                                added = true;
1642 >                                t.putTreeVal(h, key, val);
1643 >                            }
1644 >                        }
1645 >                    }
1646 >                }
1647 >                if (binCount != 0) {
1648 >                    if (binCount >= TREEIFY_THRESHOLD)
1649 >                        treeifyBin(tab, i);
1650 >                    if (!added)
1651 >                        return val;
1652 >                    break;
1653 >                }
1654 >            }
1655 >        }
1656 >        if (val != null)
1657 >            addCount(1L, binCount);
1658 >        return val;
1659      }
1660  
1661      /**
1662 <     * If the given key is present, computes a new mapping value given a key and
1663 <     * its current mapped value. This is equivalent to
1664 <     *  <pre> {@code
1665 <     *   if (map.containsKey(key)) {
1666 <     *     value = remappingFunction.apply(key, map.get(key));
1667 <     *     if (value != null)
1668 <     *       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:
1662 >     * If the value for the specified key is present, attempts to
1663 >     * compute a new mapping given the key and its current mapped
1664 >     * value.  The entire method invocation is performed atomically.
1665 >     * Some attempted update operations on this map by other threads
1666 >     * may be blocked while computation is in progress, so the
1667 >     * computation should be short and simple, and must not attempt to
1668 >     * update any other mappings of this map.
1669       *
1670 <     * @param key key with which the specified value is to be associated
1670 >     * @param key key with which a value may be associated
1671       * @param remappingFunction the function to compute a value
1672       * @return the new value associated with the specified key, or null if none
1673       * @throws NullPointerException if the specified key or remappingFunction
# Line 2838 | Line 1678 | public class ConcurrentHashMap<K, V>
1678       * @throws RuntimeException or Error if the remappingFunction does so,
1679       *         in which case the mapping is unchanged
1680       */
1681 <    @SuppressWarnings("unchecked") public V computeIfPresent
2842 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1681 >    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1682          if (key == null || remappingFunction == null)
1683              throw new NullPointerException();
1684 <        return (V)internalCompute(key, true, remappingFunction);
1684 >        int h = spread(key.hashCode());
1685 >        V val = null;
1686 >        int delta = 0;
1687 >        int binCount = 0;
1688 >        for (Node<K,V>[] tab = table;;) {
1689 >            Node<K,V> f; int n, i, fh;
1690 >            if (tab == null || (n = tab.length) == 0)
1691 >                tab = initTable();
1692 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1693 >                break;
1694 >            else if ((fh = f.hash) == MOVED)
1695 >                tab = helpTransfer(tab, f);
1696 >            else {
1697 >                synchronized (f) {
1698 >                    if (tabAt(tab, i) == f) {
1699 >                        if (fh >= 0) {
1700 >                            binCount = 1;
1701 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1702 >                                K ek;
1703 >                                if (e.hash == h &&
1704 >                                    ((ek = e.key) == key ||
1705 >                                     (ek != null && key.equals(ek)))) {
1706 >                                    val = remappingFunction.apply(key, e.val);
1707 >                                    if (val != null)
1708 >                                        e.val = val;
1709 >                                    else {
1710 >                                        delta = -1;
1711 >                                        Node<K,V> en = e.next;
1712 >                                        if (pred != null)
1713 >                                            pred.next = en;
1714 >                                        else
1715 >                                            setTabAt(tab, i, en);
1716 >                                    }
1717 >                                    break;
1718 >                                }
1719 >                                pred = e;
1720 >                                if ((e = e.next) == null)
1721 >                                    break;
1722 >                            }
1723 >                        }
1724 >                        else if (f instanceof TreeBin) {
1725 >                            binCount = 2;
1726 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1727 >                            TreeNode<K,V> r, p;
1728 >                            if ((r = t.root) != null &&
1729 >                                (p = r.findTreeNode(h, key, null)) != null) {
1730 >                                val = remappingFunction.apply(key, p.val);
1731 >                                if (val != null)
1732 >                                    p.val = val;
1733 >                                else {
1734 >                                    delta = -1;
1735 >                                    if (t.removeTreeNode(p))
1736 >                                        setTabAt(tab, i, untreeify(t.first));
1737 >                                }
1738 >                            }
1739 >                        }
1740 >                    }
1741 >                }
1742 >                if (binCount != 0)
1743 >                    break;
1744 >            }
1745 >        }
1746 >        if (delta != 0)
1747 >            addCount((long)delta, binCount);
1748 >        return val;
1749      }
1750  
1751      /**
1752 <     * Computes a new mapping value given a key and
1753 <     * its current mapped value (or {@code null} if there is no current
1754 <     * mapping). This is equivalent to
1755 <     *  <pre> {@code
1756 <     *   value = remappingFunction.apply(key, map.get(key));
1757 <     *   if (value != null)
1758 <     *     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>
1752 >     * Attempts to compute a mapping for the specified key and its
1753 >     * current mapped value (or {@code null} if there is no current
1754 >     * mapping). The entire method invocation is performed atomically.
1755 >     * Some attempted update operations on this map by other threads
1756 >     * may be blocked while computation is in progress, so the
1757 >     * computation should be short and simple, and must not attempt to
1758 >     * update any other mappings of this Map.
1759       *
1760       * @param key key with which the specified value is to be associated
1761       * @param remappingFunction the function to compute a value
# Line 2885 | Line 1768 | public class ConcurrentHashMap<K, V>
1768       * @throws RuntimeException or Error if the remappingFunction does so,
1769       *         in which case the mapping is unchanged
1770       */
1771 <    @SuppressWarnings("unchecked") public V compute
1772 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1771 >    public V compute(K key,
1772 >                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1773          if (key == null || remappingFunction == null)
1774              throw new NullPointerException();
1775 <        return (V)internalCompute(key, false, remappingFunction);
1775 >        int h = spread(key.hashCode());
1776 >        V val = null;
1777 >        int delta = 0;
1778 >        int binCount = 0;
1779 >        for (Node<K,V>[] tab = table;;) {
1780 >            Node<K,V> f; int n, i, fh;
1781 >            if (tab == null || (n = tab.length) == 0)
1782 >                tab = initTable();
1783 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1784 >                Node<K,V> r = new ReservationNode<K,V>();
1785 >                synchronized (r) {
1786 >                    if (casTabAt(tab, i, null, r)) {
1787 >                        binCount = 1;
1788 >                        Node<K,V> node = null;
1789 >                        try {
1790 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1791 >                                delta = 1;
1792 >                                node = new Node<K,V>(h, key, val, null);
1793 >                            }
1794 >                        } finally {
1795 >                            setTabAt(tab, i, node);
1796 >                        }
1797 >                    }
1798 >                }
1799 >                if (binCount != 0)
1800 >                    break;
1801 >            }
1802 >            else if ((fh = f.hash) == MOVED)
1803 >                tab = helpTransfer(tab, f);
1804 >            else {
1805 >                synchronized (f) {
1806 >                    if (tabAt(tab, i) == f) {
1807 >                        if (fh >= 0) {
1808 >                            binCount = 1;
1809 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1810 >                                K ek;
1811 >                                if (e.hash == h &&
1812 >                                    ((ek = e.key) == key ||
1813 >                                     (ek != null && key.equals(ek)))) {
1814 >                                    val = remappingFunction.apply(key, e.val);
1815 >                                    if (val != null)
1816 >                                        e.val = val;
1817 >                                    else {
1818 >                                        delta = -1;
1819 >                                        Node<K,V> en = e.next;
1820 >                                        if (pred != null)
1821 >                                            pred.next = en;
1822 >                                        else
1823 >                                            setTabAt(tab, i, en);
1824 >                                    }
1825 >                                    break;
1826 >                                }
1827 >                                pred = e;
1828 >                                if ((e = e.next) == null) {
1829 >                                    val = remappingFunction.apply(key, null);
1830 >                                    if (val != null) {
1831 >                                        delta = 1;
1832 >                                        pred.next =
1833 >                                            new Node<K,V>(h, key, val, null);
1834 >                                    }
1835 >                                    break;
1836 >                                }
1837 >                            }
1838 >                        }
1839 >                        else if (f instanceof TreeBin) {
1840 >                            binCount = 1;
1841 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1842 >                            TreeNode<K,V> r, p;
1843 >                            if ((r = t.root) != null)
1844 >                                p = r.findTreeNode(h, key, null);
1845 >                            else
1846 >                                p = null;
1847 >                            V pv = (p == null) ? null : p.val;
1848 >                            val = remappingFunction.apply(key, pv);
1849 >                            if (val != null) {
1850 >                                if (p != null)
1851 >                                    p.val = val;
1852 >                                else {
1853 >                                    delta = 1;
1854 >                                    t.putTreeVal(h, key, val);
1855 >                                }
1856 >                            }
1857 >                            else if (p != null) {
1858 >                                delta = -1;
1859 >                                if (t.removeTreeNode(p))
1860 >                                    setTabAt(tab, i, untreeify(t.first));
1861 >                            }
1862 >                        }
1863 >                    }
1864 >                }
1865 >                if (binCount != 0) {
1866 >                    if (binCount >= TREEIFY_THRESHOLD)
1867 >                        treeifyBin(tab, i);
1868 >                    break;
1869 >                }
1870 >            }
1871 >        }
1872 >        if (delta != 0)
1873 >            addCount((long)delta, binCount);
1874 >        return val;
1875      }
1876  
1877      /**
1878 <     * If the specified key is not already associated
1879 <     * with a value, associate it with the given value.
1880 <     * Otherwise, replace the value with the results of
1881 <     * the given remapping function. This is equivalent to:
1882 <     *  <pre> {@code
1883 <     *   if (!map.containsKey(key))
1884 <     *     map.put(value);
1885 <     *   else {
1886 <     *     newValue = remappingFunction.apply(map.get(key), value);
1887 <     *     if (value != null)
1888 <     *       map.put(key, value);
1889 <     *     else
1890 <     *       map.remove(key);
1891 <     *   }
1892 <     * }</pre>
1893 <     * except that the action is performed atomically.  If the
1894 <     * function returns {@code null}, the mapping is removed.  If the
1895 <     * function itself throws an (unchecked) exception, the exception
2914 <     * is rethrown to its caller, and the current mapping is left
2915 <     * unchanged.  Some attempted update operations on this map by
2916 <     * 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.
1878 >     * If the specified key is not already associated with a
1879 >     * (non-null) value, associates it with the given value.
1880 >     * Otherwise, replaces the value with the results of the given
1881 >     * remapping function, or removes if {@code null}. The entire
1882 >     * method invocation is performed atomically.  Some attempted
1883 >     * update operations on this map by other threads may be blocked
1884 >     * while computation is in progress, so the computation should be
1885 >     * short and simple, and must not attempt to update any other
1886 >     * mappings of this Map.
1887 >     *
1888 >     * @param key key with which the specified value is to be associated
1889 >     * @param value the value to use if absent
1890 >     * @param remappingFunction the function to recompute a value if present
1891 >     * @return the new value associated with the specified key, or null if none
1892 >     * @throws NullPointerException if the specified key or the
1893 >     *         remappingFunction is null
1894 >     * @throws RuntimeException or Error if the remappingFunction does so,
1895 >     *         in which case the mapping is unchanged
1896       */
1897 <    @SuppressWarnings("unchecked") public V merge
2921 <        (K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1897 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1898          if (key == null || value == null || remappingFunction == null)
1899              throw new NullPointerException();
1900 <        return (V)internalMerge(key, value, remappingFunction);
1900 >        int h = spread(key.hashCode());
1901 >        V val = null;
1902 >        int delta = 0;
1903 >        int binCount = 0;
1904 >        for (Node<K,V>[] tab = table;;) {
1905 >            Node<K,V> f; int n, i, fh;
1906 >            if (tab == null || (n = tab.length) == 0)
1907 >                tab = initTable();
1908 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1909 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1910 >                    delta = 1;
1911 >                    val = value;
1912 >                    break;
1913 >                }
1914 >            }
1915 >            else if ((fh = f.hash) == MOVED)
1916 >                tab = helpTransfer(tab, f);
1917 >            else {
1918 >                synchronized (f) {
1919 >                    if (tabAt(tab, i) == f) {
1920 >                        if (fh >= 0) {
1921 >                            binCount = 1;
1922 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1923 >                                K ek;
1924 >                                if (e.hash == h &&
1925 >                                    ((ek = e.key) == key ||
1926 >                                     (ek != null && key.equals(ek)))) {
1927 >                                    val = remappingFunction.apply(e.val, value);
1928 >                                    if (val != null)
1929 >                                        e.val = val;
1930 >                                    else {
1931 >                                        delta = -1;
1932 >                                        Node<K,V> en = e.next;
1933 >                                        if (pred != null)
1934 >                                            pred.next = en;
1935 >                                        else
1936 >                                            setTabAt(tab, i, en);
1937 >                                    }
1938 >                                    break;
1939 >                                }
1940 >                                pred = e;
1941 >                                if ((e = e.next) == null) {
1942 >                                    delta = 1;
1943 >                                    val = value;
1944 >                                    pred.next =
1945 >                                        new Node<K,V>(h, key, val, null);
1946 >                                    break;
1947 >                                }
1948 >                            }
1949 >                        }
1950 >                        else if (f instanceof TreeBin) {
1951 >                            binCount = 2;
1952 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1953 >                            TreeNode<K,V> r = t.root;
1954 >                            TreeNode<K,V> p = (r == null) ? null :
1955 >                                r.findTreeNode(h, key, null);
1956 >                            val = (p == null) ? value :
1957 >                                remappingFunction.apply(p.val, value);
1958 >                            if (val != null) {
1959 >                                if (p != null)
1960 >                                    p.val = val;
1961 >                                else {
1962 >                                    delta = 1;
1963 >                                    t.putTreeVal(h, key, val);
1964 >                                }
1965 >                            }
1966 >                            else if (p != null) {
1967 >                                delta = -1;
1968 >                                if (t.removeTreeNode(p))
1969 >                                    setTabAt(tab, i, untreeify(t.first));
1970 >                            }
1971 >                        }
1972 >                    }
1973 >                }
1974 >                if (binCount != 0) {
1975 >                    if (binCount >= TREEIFY_THRESHOLD)
1976 >                        treeifyBin(tab, i);
1977 >                    break;
1978 >                }
1979 >            }
1980 >        }
1981 >        if (delta != 0)
1982 >            addCount((long)delta, binCount);
1983 >        return val;
1984      }
1985  
1986 +    // Hashtable legacy methods
1987 +
1988      /**
1989 <     * Removes the key (and its corresponding value) from this map.
1990 <     * This method does nothing if the key is not in the map.
1989 >     * Legacy method testing if some key maps into the specified value
1990 >     * in this table.  This method is identical in functionality to
1991 >     * {@link #containsValue(Object)}, and exists solely to ensure
1992 >     * full compatibility with class {@link java.util.Hashtable},
1993 >     * which supported this method prior to introduction of the
1994 >     * Java Collections framework.
1995       *
1996 <     * @param  key the key that needs to be removed
1997 <     * @return the previous value associated with {@code key}, or
1998 <     *         {@code null} if there was no mapping for {@code key}
1999 <     * @throws NullPointerException if the specified key is null
1996 >     * @param  value a value to search for
1997 >     * @return {@code true} if and only if some key maps to the
1998 >     *         {@code value} argument in this table as
1999 >     *         determined by the {@code equals} method;
2000 >     *         {@code false} otherwise
2001 >     * @throws NullPointerException if the specified value is null
2002       */
2003 <    @SuppressWarnings("unchecked") public V remove(Object key) {
2004 <        if (key == null)
2938 <            throw new NullPointerException();
2939 <        return (V)internalReplace(key, null, null);
2003 >    @Deprecated public boolean contains(Object value) {
2004 >        return containsValue(value);
2005      }
2006  
2007      /**
2008 <     * {@inheritDoc}
2008 >     * Returns an enumeration of the keys in this table.
2009       *
2010 <     * @throws NullPointerException if the specified key is null
2010 >     * @return an enumeration of the keys in this table
2011 >     * @see #keySet()
2012       */
2013 <    public boolean remove(Object key, Object value) {
2014 <        if (key == null)
2015 <            throw new NullPointerException();
2016 <        if (value == null)
2951 <            return false;
2952 <        return internalReplace(key, null, value) != null;
2013 >    public Enumeration<K> keys() {
2014 >        Node<K,V>[] t;
2015 >        int f = (t = table) == null ? 0 : t.length;
2016 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2017      }
2018  
2019      /**
2020 <     * {@inheritDoc}
2020 >     * Returns an enumeration of the values in this table.
2021       *
2022 <     * @throws NullPointerException if any of the arguments are null
2022 >     * @return an enumeration of the values in this table
2023 >     * @see #values()
2024       */
2025 <    public boolean replace(K key, V oldValue, V newValue) {
2026 <        if (key == null || oldValue == null || newValue == null)
2027 <            throw new NullPointerException();
2028 <        return internalReplace(key, newValue, oldValue) != null;
2025 >    public Enumeration<V> elements() {
2026 >        Node<K,V>[] t;
2027 >        int f = (t = table) == null ? 0 : t.length;
2028 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2029      }
2030  
2031 +    // ConcurrentHashMap-only methods
2032 +
2033      /**
2034 <     * {@inheritDoc}
2034 >     * Returns the number of mappings. This method should be used
2035 >     * instead of {@link #size} because a ConcurrentHashMap may
2036 >     * contain more mappings than can be represented as an int. The
2037 >     * value returned is an estimate; the actual count may differ if
2038 >     * there are concurrent insertions or removals.
2039       *
2040 <     * @return the previous value associated with the specified key,
2041 <     *         or {@code null} if there was no mapping for the key
2971 <     * @throws NullPointerException if the specified key or value is null
2040 >     * @return the number of mappings
2041 >     * @since 1.8
2042       */
2043 <    @SuppressWarnings("unchecked") public V replace(K key, V value) {
2044 <        if (key == null || value == null)
2045 <            throw new NullPointerException();
2976 <        return (V)internalReplace(key, value, null);
2043 >    public long mappingCount() {
2044 >        long n = sumCount();
2045 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2046      }
2047  
2048      /**
2049 <     * Removes all of the mappings from this map.
2049 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2050 >     * from the given type to {@code Boolean.TRUE}.
2051 >     *
2052 >     * @return the new set
2053 >     * @since 1.8
2054       */
2055 <    public void clear() {
2056 <        internalClear();
2055 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2056 >        return new KeySetView<K,Boolean>
2057 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2058      }
2059  
2060      /**
2061 <     * Returns a {@link Set} view of the keys contained in this map.
2062 <     * The set is backed by the map, so changes to the map are
2989 <     * reflected in the set, and vice-versa.
2061 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2062 >     * from the given type to {@code Boolean.TRUE}.
2063       *
2064 <     * @return the set view
2064 >     * @param initialCapacity The implementation performs internal
2065 >     * sizing to accommodate this many elements.
2066 >     * @throws IllegalArgumentException if the initial capacity of
2067 >     * elements is negative
2068 >     * @return the new set
2069 >     * @since 1.8
2070       */
2071 <    public KeySetView<K,V> keySet() {
2072 <        KeySetView<K,V> ks = keySet;
2073 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2071 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2072 >        return new KeySetView<K,Boolean>
2073 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2074      }
2075  
2076      /**
2077       * Returns a {@link Set} view of the keys in this map, using the
2078       * given common mapped value for any additions (i.e., {@link
2079 <     * Collection#add} and {@link Collection#addAll}). This is of
2080 <     * course only appropriate if it is acceptable to use the same
2081 <     * value for all additions from this view.
2079 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2080 >     * This is of course only appropriate if it is acceptable to use
2081 >     * the same value for all additions from this view.
2082       *
2083 <     * @param mappedValue the mapped value to use for any
3006 <     * additions.
2083 >     * @param mappedValue the mapped value to use for any additions
2084       * @return the set view
2085       * @throws NullPointerException if the mappedValue is null
2086       */
# Line 3013 | Line 2090 | public class ConcurrentHashMap<K, V>
2090          return new KeySetView<K,V>(this, mappedValue);
2091      }
2092  
2093 +    /* ---------------- Special Nodes -------------- */
2094 +
2095      /**
2096 <     * Returns a {@link Collection} view of the values contained in this map.
3018 <     * The collection is backed by the map, so changes to the map are
3019 <     * reflected in the collection, and vice-versa.
2096 >     * A node inserted at head of bins during transfer operations.
2097       */
2098 <    public ValuesView<K,V> values() {
2099 <        ValuesView<K,V> vs = values;
2100 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2098 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2099 >        final Node<K,V>[] nextTable;
2100 >        ForwardingNode(Node<K,V>[] tab) {
2101 >            super(MOVED, null, null, null);
2102 >            this.nextTable = tab;
2103 >        }
2104 >
2105 >        Node<K,V> find(int h, Object k) {
2106 >            Node<K,V> e; int n;
2107 >            Node<K,V>[] tab = nextTable;
2108 >            if (k != null && tab != null && (n = tab.length) > 0 &&
2109 >                (e = tabAt(tab, (n - 1) & h)) != null) {
2110 >                do {
2111 >                    int eh; K ek;
2112 >                    if ((eh = e.hash) == h &&
2113 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2114 >                        return e;
2115 >                    if (eh < 0)
2116 >                        return e.find(h, k);
2117 >                } while ((e = e.next) != null);
2118 >            }
2119 >            return null;
2120 >        }
2121      }
2122  
2123      /**
2124 <     * Returns a {@link Set} view of the mappings contained in this map.
3028 <     * The set is backed by the map, so changes to the map are
3029 <     * reflected in the set, and vice-versa.  The set supports element
3030 <     * removal, which removes the corresponding mapping from the map,
3031 <     * via the {@code Iterator.remove}, {@code Set.remove},
3032 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
3033 <     * operations.  It does not support the {@code add} or
3034 <     * {@code addAll} operations.
3035 <     *
3036 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
3037 <     * that will never throw {@link ConcurrentModificationException},
3038 <     * and guarantees to traverse elements as they existed upon
3039 <     * construction of the iterator, and may (but is not guaranteed to)
3040 <     * reflect any modifications subsequent to construction.
2124 >     * A place-holder node used in computeIfAbsent and compute
2125       */
2126 <    public Set<Map.Entry<K,V>> entrySet() {
2127 <        EntrySetView<K,V> es = entrySet;
2128 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2126 >    static final class ReservationNode<K,V> extends Node<K,V> {
2127 >        ReservationNode() {
2128 >            super(RESERVED, null, null, null);
2129 >        }
2130 >
2131 >        Node<K,V> find(int h, Object k) {
2132 >            return null;
2133 >        }
2134      }
2135  
2136 +    /* ---------------- Table Initialization and Resizing -------------- */
2137 +
2138      /**
2139 <     * Returns an enumeration of the keys in this table.
3049 <     *
3050 <     * @return an enumeration of the keys in this table
3051 <     * @see #keySet()
2139 >     * Initializes table, using the size recorded in sizeCtl.
2140       */
2141 <    public Enumeration<K> keys() {
2142 <        return new KeyIterator<K,V>(this);
2141 >    private final Node<K,V>[] initTable() {
2142 >        Node<K,V>[] tab; int sc;
2143 >        while ((tab = table) == null || tab.length == 0) {
2144 >            if ((sc = sizeCtl) < 0)
2145 >                Thread.yield(); // lost initialization race; just spin
2146 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2147 >                try {
2148 >                    if ((tab = table) == null || tab.length == 0) {
2149 >                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2150 >                        @SuppressWarnings({"rawtypes","unchecked"})
2151 >                            Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2152 >                        table = tab = nt;
2153 >                        sc = n - (n >>> 2);
2154 >                    }
2155 >                } finally {
2156 >                    sizeCtl = sc;
2157 >                }
2158 >                break;
2159 >            }
2160 >        }
2161 >        return tab;
2162      }
2163  
2164      /**
2165 <     * Returns an enumeration of the values in this table.
2166 <     *
2167 <     * @return an enumeration of the values in this table
2168 <     * @see #values()
2165 >     * Adds to count, and if table is too small and not already
2166 >     * resizing, initiates transfer. If already resizing, helps
2167 >     * perform transfer if work is available.  Rechecks occupancy
2168 >     * after a transfer to see if another resize is already needed
2169 >     * because resizings are lagging additions.
2170 >     *
2171 >     * @param x the count to add
2172 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
2173 >     */
2174 >    private final void addCount(long x, int check) {
2175 >        CounterCell[] as; long b, s;
2176 >        if ((as = counterCells) != null ||
2177 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2178 >            CounterCell a; long v; int m;
2179 >            boolean uncontended = true;
2180 >            if (as == null || (m = as.length - 1) < 0 ||
2181 >                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
2182 >                !(uncontended =
2183 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2184 >                fullAddCount(x, uncontended);
2185 >                return;
2186 >            }
2187 >            if (check <= 1)
2188 >                return;
2189 >            s = sumCount();
2190 >        }
2191 >        if (check >= 0) {
2192 >            Node<K,V>[] tab, nt; int sc;
2193 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2194 >                   tab.length < MAXIMUM_CAPACITY) {
2195 >                if (sc < 0) {
2196 >                    if (sc == -1 || transferIndex <= transferOrigin ||
2197 >                        (nt = nextTable) == null)
2198 >                        break;
2199 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2200 >                        transfer(tab, nt);
2201 >                }
2202 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2203 >                    transfer(tab, null);
2204 >                s = sumCount();
2205 >            }
2206 >        }
2207 >    }
2208 >
2209 >    /**
2210 >     * Helps transfer if a resize is in progress.
2211       */
2212 <    public Enumeration<V> elements() {
2213 <        return new ValueIterator<K,V>(this);
2212 >    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2213 >        Node<K,V>[] nextTab; int sc;
2214 >        if ((f instanceof ForwardingNode) &&
2215 >            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2216 >            if (nextTab == nextTable && tab == table &&
2217 >                transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
2218 >                U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2219 >                transfer(tab, nextTab);
2220 >            return nextTab;
2221 >        }
2222 >        return table;
2223      }
2224  
2225      /**
2226 <     * Returns a partitionable iterator of the keys in this map.
2226 >     * Tries to presize table to accommodate the given number of elements.
2227       *
2228 <     * @return a partitionable iterator of the keys in this map
2228 >     * @param size number of elements (doesn't need to be perfectly accurate)
2229       */
2230 <    public Spliterator<K> keySpliterator() {
2231 <        return new KeyIterator<K,V>(this);
2230 >    private final void tryPresize(int size) {
2231 >        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2232 >            tableSizeFor(size + (size >>> 1) + 1);
2233 >        int sc;
2234 >        while ((sc = sizeCtl) >= 0) {
2235 >            Node<K,V>[] tab = table; int n;
2236 >            if (tab == null || (n = tab.length) == 0) {
2237 >                n = (sc > c) ? sc : c;
2238 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2239 >                    try {
2240 >                        if (table == tab) {
2241 >                            @SuppressWarnings({"rawtypes","unchecked"})
2242 >                                Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2243 >                            table = nt;
2244 >                            sc = n - (n >>> 2);
2245 >                        }
2246 >                    } finally {
2247 >                        sizeCtl = sc;
2248 >                    }
2249 >                }
2250 >            }
2251 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
2252 >                break;
2253 >            else if (tab == table &&
2254 >                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2255 >                transfer(tab, null);
2256 >        }
2257      }
2258  
2259      /**
2260 <     * Returns a partitionable iterator of the values in this map.
2261 <     *
3079 <     * @return a partitionable iterator of the values in this map
2260 >     * Moves and/or copies the nodes in each bin to new table. See
2261 >     * above for explanation.
2262       */
2263 <    public Spliterator<V> valueSpliterator() {
2264 <        return new ValueIterator<K,V>(this);
2263 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2264 >        int n = tab.length, stride;
2265 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2266 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
2267 >        if (nextTab == null) {            // initiating
2268 >            try {
2269 >                @SuppressWarnings({"rawtypes","unchecked"})
2270 >                    Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
2271 >                nextTab = nt;
2272 >            } catch (Throwable ex) {      // try to cope with OOME
2273 >                sizeCtl = Integer.MAX_VALUE;
2274 >                return;
2275 >            }
2276 >            nextTable = nextTab;
2277 >            transferOrigin = n;
2278 >            transferIndex = n;
2279 >            ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
2280 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
2281 >                int nextk = (k > stride) ? k - stride : 0;
2282 >                for (int m = nextk; m < k; ++m)
2283 >                    nextTab[m] = rev;
2284 >                for (int m = n + nextk; m < n + k; ++m)
2285 >                    nextTab[m] = rev;
2286 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
2287 >            }
2288 >        }
2289 >        int nextn = nextTab.length;
2290 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2291 >        boolean advance = true;
2292 >        for (int i = 0, bound = 0;;) {
2293 >            int nextIndex, nextBound, fh; Node<K,V> f;
2294 >            while (advance) {
2295 >                if (--i >= bound)
2296 >                    advance = false;
2297 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
2298 >                    i = -1;
2299 >                    advance = false;
2300 >                }
2301 >                else if (U.compareAndSwapInt
2302 >                         (this, TRANSFERINDEX, nextIndex,
2303 >                          nextBound = (nextIndex > stride ?
2304 >                                       nextIndex - stride : 0))) {
2305 >                    bound = nextBound;
2306 >                    i = nextIndex - 1;
2307 >                    advance = false;
2308 >                }
2309 >            }
2310 >            if (i < 0 || i >= n || i + n >= nextn) {
2311 >                for (int sc;;) {
2312 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2313 >                        if (sc == -1) {
2314 >                            nextTable = null;
2315 >                            table = nextTab;
2316 >                            sizeCtl = (n << 1) - (n >>> 1);
2317 >                        }
2318 >                        return;
2319 >                    }
2320 >                }
2321 >            }
2322 >            else if ((f = tabAt(tab, i)) == null) {
2323 >                if (casTabAt(tab, i, null, fwd)) {
2324 >                    setTabAt(nextTab, i, null);
2325 >                    setTabAt(nextTab, i + n, null);
2326 >                    advance = true;
2327 >                }
2328 >            }
2329 >            else if ((fh = f.hash) == MOVED)
2330 >                advance = true; // already processed
2331 >            else {
2332 >                synchronized (f) {
2333 >                    if (tabAt(tab, i) == f) {
2334 >                        Node<K,V> ln, hn;
2335 >                        if (fh >= 0) {
2336 >                            int runBit = fh & n;
2337 >                            Node<K,V> lastRun = f;
2338 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2339 >                                int b = p.hash & n;
2340 >                                if (b != runBit) {
2341 >                                    runBit = b;
2342 >                                    lastRun = p;
2343 >                                }
2344 >                            }
2345 >                            if (runBit == 0) {
2346 >                                ln = lastRun;
2347 >                                hn = null;
2348 >                            }
2349 >                            else {
2350 >                                hn = lastRun;
2351 >                                ln = null;
2352 >                            }
2353 >                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2354 >                                int ph = p.hash; K pk = p.key; V pv = p.val;
2355 >                                if ((ph & n) == 0)
2356 >                                    ln = new Node<K,V>(ph, pk, pv, ln);
2357 >                                else
2358 >                                    hn = new Node<K,V>(ph, pk, pv, hn);
2359 >                            }
2360 >                        }
2361 >                        else if (f instanceof TreeBin) {
2362 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2363 >                            TreeNode<K,V> lo = null, loTail = null;
2364 >                            TreeNode<K,V> hi = null, hiTail = null;
2365 >                            int lc = 0, hc = 0;
2366 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2367 >                                int h = e.hash;
2368 >                                TreeNode<K,V> p = new TreeNode<K,V>
2369 >                                    (h, e.key, e.val, null, null);
2370 >                                if ((h & n) == 0) {
2371 >                                    if ((p.prev = loTail) == null)
2372 >                                        lo = p;
2373 >                                    else
2374 >                                        loTail.next = p;
2375 >                                    loTail = p;
2376 >                                    ++lc;
2377 >                                }
2378 >                                else {
2379 >                                    if ((p.prev = hiTail) == null)
2380 >                                        hi = p;
2381 >                                    else
2382 >                                        hiTail.next = p;
2383 >                                    hiTail = p;
2384 >                                    ++hc;
2385 >                                }
2386 >                            }
2387 >                            ln = (lc <= UNTREEIFY_THRESHOLD ?  untreeify(lo) :
2388 >                                  (hc != 0) ? new TreeBin<K,V>(lo) : t);
2389 >                            hn = (hc <= UNTREEIFY_THRESHOLD ? untreeify(hi) :
2390 >                                  (lc != 0) ? new TreeBin<K,V>(hi) : t);
2391 >                        }
2392 >                        else
2393 >                            ln = hn = null;
2394 >                        setTabAt(nextTab, i, ln);
2395 >                        setTabAt(nextTab, i + n, hn);
2396 >                        setTabAt(tab, i, fwd);
2397 >                        advance = true;
2398 >                    }
2399 >                }
2400 >            }
2401 >        }
2402      }
2403  
2404 +    /* ---------------- Counter support -------------- */
2405 +
2406      /**
2407 <     * Returns a partitionable iterator of the entries in this map.
2408 <     *
3088 <     * @return a partitionable iterator of the entries in this map
2407 >     * A padded cell for distributing counts.  Adapted from LongAdder
2408 >     * and Striped64.  See their internal docs for explanation.
2409       */
2410 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
2411 <        return new EntryIterator<K,V>(this);
2410 >    @sun.misc.Contended static final class CounterCell {
2411 >        volatile long value;
2412 >        CounterCell(long x) { value = x; }
2413 >    }
2414 >
2415 >    final long sumCount() {
2416 >        CounterCell[] as = counterCells; CounterCell a;
2417 >        long sum = baseCount;
2418 >        if (as != null) {
2419 >            for (int i = 0; i < as.length; ++i) {
2420 >                if ((a = as[i]) != null)
2421 >                    sum += a.value;
2422 >            }
2423 >        }
2424 >        return sum;
2425      }
2426  
2427 +    // See LongAdder version for explanation
2428 +    private final void fullAddCount(long x, boolean wasUncontended) {
2429 +        int h;
2430 +        if ((h = ThreadLocalRandom.getProbe()) == 0) {
2431 +            ThreadLocalRandom.localInit();      // force initialization
2432 +            h = ThreadLocalRandom.getProbe();
2433 +            wasUncontended = true;
2434 +        }
2435 +        boolean collide = false;                // True if last slot nonempty
2436 +        for (;;) {
2437 +            CounterCell[] as; CounterCell a; int n; long v;
2438 +            if ((as = counterCells) != null && (n = as.length) > 0) {
2439 +                if ((a = as[(n - 1) & h]) == null) {
2440 +                    if (cellsBusy == 0) {            // Try to attach new Cell
2441 +                        CounterCell r = new CounterCell(x); // Optimistic create
2442 +                        if (cellsBusy == 0 &&
2443 +                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2444 +                            boolean created = false;
2445 +                            try {               // Recheck under lock
2446 +                                CounterCell[] rs; int m, j;
2447 +                                if ((rs = counterCells) != null &&
2448 +                                    (m = rs.length) > 0 &&
2449 +                                    rs[j = (m - 1) & h] == null) {
2450 +                                    rs[j] = r;
2451 +                                    created = true;
2452 +                                }
2453 +                            } finally {
2454 +                                cellsBusy = 0;
2455 +                            }
2456 +                            if (created)
2457 +                                break;
2458 +                            continue;           // Slot is now non-empty
2459 +                        }
2460 +                    }
2461 +                    collide = false;
2462 +                }
2463 +                else if (!wasUncontended)       // CAS already known to fail
2464 +                    wasUncontended = true;      // Continue after rehash
2465 +                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2466 +                    break;
2467 +                else if (counterCells != as || n >= NCPU)
2468 +                    collide = false;            // At max size or stale
2469 +                else if (!collide)
2470 +                    collide = true;
2471 +                else if (cellsBusy == 0 &&
2472 +                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2473 +                    try {
2474 +                        if (counterCells == as) {// Expand table unless stale
2475 +                            CounterCell[] rs = new CounterCell[n << 1];
2476 +                            for (int i = 0; i < n; ++i)
2477 +                                rs[i] = as[i];
2478 +                            counterCells = rs;
2479 +                        }
2480 +                    } finally {
2481 +                        cellsBusy = 0;
2482 +                    }
2483 +                    collide = false;
2484 +                    continue;                   // Retry with expanded table
2485 +                }
2486 +                h = ThreadLocalRandom.advanceProbe(h);
2487 +            }
2488 +            else if (cellsBusy == 0 && counterCells == as &&
2489 +                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2490 +                boolean init = false;
2491 +                try {                           // Initialize table
2492 +                    if (counterCells == as) {
2493 +                        CounterCell[] rs = new CounterCell[2];
2494 +                        rs[h & 1] = new CounterCell(x);
2495 +                        counterCells = rs;
2496 +                        init = true;
2497 +                    }
2498 +                } finally {
2499 +                    cellsBusy = 0;
2500 +                }
2501 +                if (init)
2502 +                    break;
2503 +            }
2504 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2505 +                break;                          // Fall back on using base
2506 +        }
2507 +    }
2508 +
2509 +    /* ---------------- Conversion from/to TreeBins -------------- */
2510 +
2511      /**
2512 <     * Returns the hash code value for this {@link Map}, i.e.,
2513 <     * the sum of, for each key-value pair in the map,
2514 <     * {@code key.hashCode() ^ value.hashCode()}.
2515 <     *
2516 <     * @return the hash code value for this map
2512 >     * Replaces all linked nodes in bin at given index unless table is
2513 >     * too small, in which case resizes instead.
2514 >     */
2515 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2516 >        Node<K,V> b; int n, sc;
2517 >        if (tab != null) {
2518 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2519 >                if (tab == table && (sc = sizeCtl) >= 0 &&
2520 >                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
2521 >                    transfer(tab, null);
2522 >            }
2523 >            else if ((b = tabAt(tab, index)) != null) {
2524 >                synchronized (b) {
2525 >                    if (tabAt(tab, index) == b) {
2526 >                        TreeNode<K,V> hd = null, tl = null;
2527 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2528 >                            TreeNode<K,V> p =
2529 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2530 >                                                  null, null);
2531 >                            if ((p.prev = tl) == null)
2532 >                                hd = p;
2533 >                            else
2534 >                                tl.next = p;
2535 >                            tl = p;
2536 >                        }
2537 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2538 >                    }
2539 >                }
2540 >            }
2541 >        }
2542 >    }
2543 >
2544 >    /**
2545 >     * Returns a list on non-TreeNodes replacing those in given list
2546       */
2547 <    public int hashCode() {
2548 <        int h = 0;
2549 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2550 <        Object v;
2551 <        while ((v = it.advance()) != null) {
2552 <            h += it.nextKey.hashCode() ^ v.hashCode();
2547 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2548 >        Node<K,V> hd = null, tl = null;
2549 >        for (Node<K,V> q = b; q != null; q = q.next) {
2550 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2551 >            if (tl == null)
2552 >                hd = p;
2553 >            else
2554 >                tl.next = p;
2555 >            tl = p;
2556          }
2557 <        return h;
2557 >        return hd;
2558      }
2559  
2560 +    /* ---------------- TreeNodes -------------- */
2561 +
2562      /**
2563 <     * Returns a string representation of this map.  The string
3113 <     * representation consists of a list of key-value mappings (in no
3114 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3115 <     * mappings are separated by the characters {@code ", "} (comma
3116 <     * and space).  Each key-value mapping is rendered as the key
3117 <     * followed by an equals sign ("{@code =}") followed by the
3118 <     * associated value.
3119 <     *
3120 <     * @return a string representation of this map
2563 >     * Nodes for use in TreeBins
2564       */
2565 <    public String toString() {
2566 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2567 <        StringBuilder sb = new StringBuilder();
2568 <        sb.append('{');
2569 <        Object v;
2570 <        if ((v = it.advance()) != null) {
2571 <            for (;;) {
2572 <                Object k = it.nextKey;
2573 <                sb.append(k == this ? "(this Map)" : k);
2574 <                sb.append('=');
2575 <                sb.append(v == this ? "(this Map)" : v);
2576 <                if ((v = it.advance()) == null)
2565 >    static final class TreeNode<K,V> extends Node<K,V> {
2566 >        TreeNode<K,V> parent;  // red-black tree links
2567 >        TreeNode<K,V> left;
2568 >        TreeNode<K,V> right;
2569 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2570 >        boolean red;
2571 >
2572 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2573 >                 TreeNode<K,V> parent) {
2574 >            super(hash, key, val, next);
2575 >            this.parent = parent;
2576 >        }
2577 >
2578 >        Node<K,V> find(int h, Object k) {
2579 >            return findTreeNode(h, k, null);
2580 >        }
2581 >
2582 >        /**
2583 >         * Returns the TreeNode (or null if not found) for the given key
2584 >         * starting at given root.
2585 >         */
2586 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2587 >            if (k != null) {
2588 >                TreeNode<K,V> p = this;
2589 >                do  {
2590 >                    int ph, dir; K pk; TreeNode<K,V> q;
2591 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2592 >                    if ((ph = p.hash) > h)
2593 >                        p = pl;
2594 >                    else if (ph < h)
2595 >                        p = pr;
2596 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2597 >                        return p;
2598 >                    else if (pl == null && pr == null)
2599 >                        break;
2600 >                    else if ((kc != null ||
2601 >                              (kc = comparableClassFor(k)) != null) &&
2602 >                             (dir = compareComparables(kc, k, pk)) != 0)
2603 >                        p = (dir < 0) ? pl : pr;
2604 >                    else if (pl == null)
2605 >                        p = pr;
2606 >                    else if (pr == null ||
2607 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2608 >                        p = pl;
2609 >                    else
2610 >                        return q;
2611 >                } while (p != null);
2612 >            }
2613 >            return null;
2614 >        }
2615 >    }
2616 >
2617 >    /* ---------------- TreeBins -------------- */
2618 >
2619 >    /**
2620 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2621 >     * keys or values, but instead point to list of TreeNodes and
2622 >     * their root. They also maintain a parasitic read-write lock
2623 >     * forcing writers (who hold bin lock) to wait for readers (who do
2624 >     * not) to complete before tree restructuring operations.
2625 >     */
2626 >    static final class TreeBin<K,V> extends Node<K,V> {
2627 >        TreeNode<K,V> root;
2628 >        volatile TreeNode<K,V> first;
2629 >        volatile Thread waiter;
2630 >        volatile int lockState;
2631 >        // values for lockState
2632 >        static final int WRITER = 1; // set while holding write lock
2633 >        static final int WAITER = 2; // set when waiting for write lock
2634 >        static final int READER = 4; // increment value for setting read lock
2635 >
2636 >        /**
2637 >         * Creates bin with initial set of nodes headed by b.
2638 >         */
2639 >        TreeBin(TreeNode<K,V> b) {
2640 >            super(TREEBIN, null, null, null);
2641 >            this.first = b;
2642 >            TreeNode<K,V> r = null;
2643 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2644 >                next = (TreeNode<K,V>)x.next;
2645 >                x.left = x.right = null;
2646 >                if (r == null) {
2647 >                    x.parent = null;
2648 >                    x.red = false;
2649 >                    r = x;
2650 >                }
2651 >                else {
2652 >                    Object key = x.key;
2653 >                    int hash = x.hash;
2654 >                    Class<?> kc = null;
2655 >                    for (TreeNode<K,V> p = r;;) {
2656 >                        int dir, ph;
2657 >                        if ((ph = p.hash) > hash)
2658 >                            dir = -1;
2659 >                        else if (ph < hash)
2660 >                            dir = 1;
2661 >                        else if ((kc != null ||
2662 >                                  (kc = comparableClassFor(key)) != null))
2663 >                            dir = compareComparables(kc, key, p.key);
2664 >                        else
2665 >                            dir = 0;
2666 >                        TreeNode<K,V> xp = p;
2667 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2668 >                            x.parent = xp;
2669 >                            if (dir <= 0)
2670 >                                xp.left = x;
2671 >                            else
2672 >                                xp.right = x;
2673 >                            r = balanceInsertion(r, x);
2674 >                            break;
2675 >                        }
2676 >                    }
2677 >                }
2678 >            }
2679 >            this.root = r;
2680 >        }
2681 >
2682 >        /**
2683 >         * Acquires write lock for tree restructuring
2684 >         */
2685 >        private final void lockRoot() {
2686 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2687 >                contendedLock(); // offload to separate method
2688 >        }
2689 >
2690 >        /**
2691 >         * Releases write lock for tree restructuring
2692 >         */
2693 >        private final void unlockRoot() {
2694 >            lockState = 0;
2695 >        }
2696 >
2697 >        /**
2698 >         * Possibly blocks awaiting root lock
2699 >         */
2700 >        private final void contendedLock() {
2701 >            boolean waiting = false;
2702 >            for (int s;;) {
2703 >                if (((s = lockState) & WRITER) == 0) {
2704 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2705 >                        if (waiting)
2706 >                            waiter = null;
2707 >                        return;
2708 >                    }
2709 >                }
2710 >                else if ((s | WAITER) == 0) {
2711 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2712 >                        waiting = true;
2713 >                        waiter = Thread.currentThread();
2714 >                    }
2715 >                }
2716 >                else if (waiting)
2717 >                    LockSupport.park(this);
2718 >            }
2719 >        }
2720 >
2721 >        /**
2722 >         * Returns matching node or null if none. Tries to search
2723 >         * using tree compareisons from root, but continues linear
2724 >         * search when lock not available.
2725 >         */
2726 >        final Node<K,V> find(int h, Object k) {
2727 >            if (k != null) {
2728 >                for (Node<K,V> e = first; e != null; e = e.next) {
2729 >                    int s; K ek;
2730 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2731 >                        if (e.hash == h &&
2732 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2733 >                            return e;
2734 >                    }
2735 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2736 >                                                 s + READER)) {
2737 >                        TreeNode<K,V> r, p;
2738 >                        try {
2739 >                            p = ((r = root) == null ? null :
2740 >                                 r.findTreeNode(h, k, null));
2741 >                        } finally {
2742 >                            Thread w;
2743 >                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2744 >                                (READER|WAITER) && (w = waiter) != null)
2745 >                                LockSupport.unpark(w);
2746 >                        }
2747 >                        return p;
2748 >                    }
2749 >                }
2750 >            }
2751 >            return null;
2752 >        }
2753 >
2754 >        /**
2755 >         * Finds or adds a node.
2756 >         * @return null if added
2757 >         */
2758 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2759 >            Class<?> kc = null;
2760 >            for (TreeNode<K,V> p = root;;) {
2761 >                int dir, ph; K pk; TreeNode<K,V> q, pr;
2762 >                if (p == null) {
2763 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2764                      break;
2765 <                sb.append(',').append(' ');
2765 >                }
2766 >                else if ((ph = p.hash) > h)
2767 >                    dir = -1;
2768 >                else if (ph < h)
2769 >                    dir = 1;
2770 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2771 >                    return p;
2772 >                else if ((kc == null &&
2773 >                          (kc = comparableClassFor(k)) == null) ||
2774 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2775 >                    if (p.left == null)
2776 >                        dir = 1;
2777 >                    else if ((pr = p.right) == null ||
2778 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2779 >                        dir = -1;
2780 >                    else
2781 >                        return q;
2782 >                }
2783 >                TreeNode<K,V> xp = p;
2784 >                if ((p = (dir < 0) ? p.left : p.right) == null) {
2785 >                    TreeNode<K,V> x, f = first;
2786 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2787 >                    if (f != null)
2788 >                        f.prev = x;
2789 >                    if (dir < 0)
2790 >                        xp.left = x;
2791 >                    else
2792 >                        xp.right = x;
2793 >                    if (!xp.red)
2794 >                        x.red = true;
2795 >                    else {
2796 >                        lockRoot();
2797 >                        try {
2798 >                            root = balanceInsertion(root, x);
2799 >                        } finally {
2800 >                            unlockRoot();
2801 >                        }
2802 >                    }
2803 >                    break;
2804 >                }
2805 >            }
2806 >            assert checkInvariants(root);
2807 >            return null;
2808 >        }
2809 >
2810 >        /**
2811 >         * Removes the given node, that must be present before this
2812 >         * call.  This is messier than typical red-black deletion code
2813 >         * because we cannot swap the contents of an interior node
2814 >         * with a leaf successor that is pinned by "next" pointers
2815 >         * that are accessible independently of lock. So instead we
2816 >         * swap the tree linkages.
2817 >         *
2818 >         * @return true if now too small so should be untreeified.
2819 >         */
2820 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2821 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2822 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2823 >            TreeNode<K,V> r, rl;
2824 >            if (pred == null)
2825 >                first = next;
2826 >            else
2827 >                pred.next = next;
2828 >            if (next != null)
2829 >                next.prev = pred;
2830 >            if (first == null) {
2831 >                root = null;
2832 >                return true;
2833 >            }
2834 >            if ((r = root) == null || r.right == null || // too small
2835 >                (rl = r.left) == null || rl.left == null)
2836 >                return true;
2837 >            lockRoot();
2838 >            try {
2839 >                TreeNode<K,V> replacement;
2840 >                TreeNode<K,V> pl = p.left;
2841 >                TreeNode<K,V> pr = p.right;
2842 >                if (pl != null && pr != null) {
2843 >                    TreeNode<K,V> s = pr, sl;
2844 >                    while ((sl = s.left) != null) // find successor
2845 >                        s = sl;
2846 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2847 >                    TreeNode<K,V> sr = s.right;
2848 >                    TreeNode<K,V> pp = p.parent;
2849 >                    if (s == pr) { // p was s's direct parent
2850 >                        p.parent = s;
2851 >                        s.right = p;
2852 >                    }
2853 >                    else {
2854 >                        TreeNode<K,V> sp = s.parent;
2855 >                        if ((p.parent = sp) != null) {
2856 >                            if (s == sp.left)
2857 >                                sp.left = p;
2858 >                            else
2859 >                                sp.right = p;
2860 >                        }
2861 >                        if ((s.right = pr) != null)
2862 >                            pr.parent = s;
2863 >                    }
2864 >                    p.left = null;
2865 >                    if ((p.right = sr) != null)
2866 >                        sr.parent = p;
2867 >                    if ((s.left = pl) != null)
2868 >                        pl.parent = s;
2869 >                    if ((s.parent = pp) == null)
2870 >                        r = s;
2871 >                    else if (p == pp.left)
2872 >                        pp.left = s;
2873 >                    else
2874 >                        pp.right = s;
2875 >                    if (sr != null)
2876 >                        replacement = sr;
2877 >                    else
2878 >                        replacement = p;
2879 >                }
2880 >                else if (pl != null)
2881 >                    replacement = pl;
2882 >                else if (pr != null)
2883 >                    replacement = pr;
2884 >                else
2885 >                    replacement = p;
2886 >                if (replacement != p) {
2887 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2888 >                    if (pp == null)
2889 >                        r = replacement;
2890 >                    else if (p == pp.left)
2891 >                        pp.left = replacement;
2892 >                    else
2893 >                        pp.right = replacement;
2894 >                    p.left = p.right = p.parent = null;
2895 >                }
2896 >
2897 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2898 >
2899 >                if (p == replacement) {  // detach pointers
2900 >                    TreeNode<K,V> pp;
2901 >                    if ((pp = p.parent) != null) {
2902 >                        if (p == pp.left)
2903 >                            pp.left = null;
2904 >                        else if (p == pp.right)
2905 >                            pp.right = null;
2906 >                        p.parent = null;
2907 >                    }
2908 >                }
2909 >            } finally {
2910 >                unlockRoot();
2911 >            }
2912 >            assert checkInvariants(root);
2913 >            return false;
2914 >        }
2915 >
2916 >        /* ------------------------------------------------------------ */
2917 >        // Red-black tree methods, all adapted from CLR
2918 >
2919 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2920 >                                              TreeNode<K,V> p) {
2921 >            TreeNode<K,V> r, pp, rl;
2922 >            if (p != null && (r = p.right) != null) {
2923 >                if ((rl = p.right = r.left) != null)
2924 >                    rl.parent = p;
2925 >                if ((pp = r.parent = p.parent) == null)
2926 >                    (root = r).red = false;
2927 >                else if (pp.left == p)
2928 >                    pp.left = r;
2929 >                else
2930 >                    pp.right = r;
2931 >                r.left = p;
2932 >                p.parent = r;
2933 >            }
2934 >            return root;
2935 >        }
2936 >
2937 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2938 >                                               TreeNode<K,V> p) {
2939 >            TreeNode<K,V> l, pp, lr;
2940 >            if (p != null && (l = p.left) != null) {
2941 >                if ((lr = p.left = l.right) != null)
2942 >                    lr.parent = p;
2943 >                if ((pp = l.parent = p.parent) == null)
2944 >                    (root = l).red = false;
2945 >                else if (pp.right == p)
2946 >                    pp.right = l;
2947 >                else
2948 >                    pp.left = l;
2949 >                l.right = p;
2950 >                p.parent = l;
2951 >            }
2952 >            return root;
2953 >        }
2954 >
2955 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2956 >                                                    TreeNode<K,V> x) {
2957 >            x.red = true;
2958 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2959 >                if ((xp = x.parent) == null) {
2960 >                    x.red = false;
2961 >                    return x;
2962 >                }
2963 >                else if (!xp.red || (xpp = xp.parent) == null)
2964 >                    return root;
2965 >                if (xp == (xppl = xpp.left)) {
2966 >                    if ((xppr = xpp.right) != null && xppr.red) {
2967 >                        xppr.red = false;
2968 >                        xp.red = false;
2969 >                        xpp.red = true;
2970 >                        x = xpp;
2971 >                    }
2972 >                    else {
2973 >                        if (x == xp.right) {
2974 >                            root = rotateLeft(root, x = xp);
2975 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2976 >                        }
2977 >                        if (xp != null) {
2978 >                            xp.red = false;
2979 >                            if (xpp != null) {
2980 >                                xpp.red = true;
2981 >                                root = rotateRight(root, xpp);
2982 >                            }
2983 >                        }
2984 >                    }
2985 >                }
2986 >                else {
2987 >                    if (xppl != null && xppl.red) {
2988 >                        xppl.red = false;
2989 >                        xp.red = false;
2990 >                        xpp.red = true;
2991 >                        x = xpp;
2992 >                    }
2993 >                    else {
2994 >                        if (x == xp.left) {
2995 >                            root = rotateRight(root, x = xp);
2996 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2997 >                        }
2998 >                        if (xp != null) {
2999 >                            xp.red = false;
3000 >                            if (xpp != null) {
3001 >                                xpp.red = true;
3002 >                                root = rotateLeft(root, xpp);
3003 >                            }
3004 >                        }
3005 >                    }
3006 >                }
3007 >            }
3008 >        }
3009 >
3010 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3011 >                                                   TreeNode<K,V> x) {
3012 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
3013 >                if (x == null || x == root)
3014 >                    return root;
3015 >                else if ((xp = x.parent) == null) {
3016 >                    x.red = false;
3017 >                    return x;
3018 >                }
3019 >                else if (x.red) {
3020 >                    x.red = false;
3021 >                    return root;
3022 >                }
3023 >                else if ((xpl = xp.left) == x) {
3024 >                    if ((xpr = xp.right) != null && xpr.red) {
3025 >                        xpr.red = false;
3026 >                        xp.red = true;
3027 >                        root = rotateLeft(root, xp);
3028 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3029 >                    }
3030 >                    if (xpr == null)
3031 >                        x = xp;
3032 >                    else {
3033 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3034 >                        if ((sr == null || !sr.red) &&
3035 >                            (sl == null || !sl.red)) {
3036 >                            xpr.red = true;
3037 >                            x = xp;
3038 >                        }
3039 >                        else {
3040 >                            if (sr == null || !sr.red) {
3041 >                                if (sl != null)
3042 >                                    sl.red = false;
3043 >                                xpr.red = true;
3044 >                                root = rotateRight(root, xpr);
3045 >                                xpr = (xp = x.parent) == null ?
3046 >                                    null : xp.right;
3047 >                            }
3048 >                            if (xpr != null) {
3049 >                                xpr.red = (xp == null) ? false : xp.red;
3050 >                                if ((sr = xpr.right) != null)
3051 >                                    sr.red = false;
3052 >                            }
3053 >                            if (xp != null) {
3054 >                                xp.red = false;
3055 >                                root = rotateLeft(root, xp);
3056 >                            }
3057 >                            x = root;
3058 >                        }
3059 >                    }
3060 >                }
3061 >                else { // symmetric
3062 >                    if (xpl != null && xpl.red) {
3063 >                        xpl.red = false;
3064 >                        xp.red = true;
3065 >                        root = rotateRight(root, xp);
3066 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3067 >                    }
3068 >                    if (xpl == null)
3069 >                        x = xp;
3070 >                    else {
3071 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3072 >                        if ((sl == null || !sl.red) &&
3073 >                            (sr == null || !sr.red)) {
3074 >                            xpl.red = true;
3075 >                            x = xp;
3076 >                        }
3077 >                        else {
3078 >                            if (sl == null || !sl.red) {
3079 >                                if (sr != null)
3080 >                                    sr.red = false;
3081 >                                xpl.red = true;
3082 >                                root = rotateLeft(root, xpl);
3083 >                                xpl = (xp = x.parent) == null ?
3084 >                                    null : xp.left;
3085 >                            }
3086 >                            if (xpl != null) {
3087 >                                xpl.red = (xp == null) ? false : xp.red;
3088 >                                if ((sl = xpl.left) != null)
3089 >                                    sl.red = false;
3090 >                            }
3091 >                            if (xp != null) {
3092 >                                xp.red = false;
3093 >                                root = rotateRight(root, xp);
3094 >                            }
3095 >                            x = root;
3096 >                        }
3097 >                    }
3098 >                }
3099 >            }
3100 >        }
3101 >        /**
3102 >         * Recursive invariant check
3103 >         */
3104 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3105 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3106 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3107 >            if (tb != null && tb.next != t)
3108 >                return false;
3109 >            if (tn != null && tn.prev != t)
3110 >                return false;
3111 >            if (tp != null && t != tp.left && t != tp.right)
3112 >                return false;
3113 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3114 >                return false;
3115 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3116 >                return false;
3117 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3118 >                return false;
3119 >            if (tl != null && !checkInvariants(tl))
3120 >                return false;
3121 >            if (tr != null && !checkInvariants(tr))
3122 >                return false;
3123 >            return true;
3124 >        }
3125 >
3126 >        private static final sun.misc.Unsafe U;
3127 >        private static final long LOCKSTATE;
3128 >        static {
3129 >            try {
3130 >                U = sun.misc.Unsafe.getUnsafe();
3131 >                Class<?> k = TreeBin.class;
3132 >                LOCKSTATE = U.objectFieldOffset
3133 >                    (k.getDeclaredField("lockState"));
3134 >            } catch (Exception e) {
3135 >                throw new Error(e);
3136              }
3137          }
3138        return sb.append('}').toString();
3138      }
3139  
3140 +    /* ----------------Table Traversal -------------- */
3141 +
3142      /**
3143 <     * Compares the specified object with this map for equality.
3144 <     * Returns {@code true} if the given object is a map with the same
3144 <     * mappings as this map.  This operation may return misleading
3145 <     * results if either map is concurrently modified during execution
3146 <     * of this method.
3143 >     * Encapsulates traversal for methods such as containsValue; also
3144 >     * serves as a base class for other iterators and spliterators.
3145       *
3146 <     * @param o object to be compared for equality with this map
3147 <     * @return {@code true} if the specified object is equal to this map
3146 >     * Method advance visits once each still-valid node that was
3147 >     * reachable upon iterator construction. It might miss some that
3148 >     * were added to a bin after the bin was visited, which is OK wrt
3149 >     * consistency guarantees. Maintaining this property in the face
3150 >     * of possible ongoing resizes requires a fair amount of
3151 >     * bookkeeping state that is difficult to optimize away amidst
3152 >     * volatile accesses.  Even so, traversal maintains reasonable
3153 >     * throughput.
3154 >     *
3155 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3156 >     * However, if the table has been resized, then all future steps
3157 >     * must traverse both the bin at the current index as well as at
3158 >     * (index + baseSize); and so on for further resizings. To
3159 >     * paranoically cope with potential sharing by users of iterators
3160 >     * across threads, iteration terminates if a bounds checks fails
3161 >     * for a table read.
3162       */
3163 <    public boolean equals(Object o) {
3164 <        if (o != this) {
3165 <            if (!(o instanceof Map))
3166 <                return false;
3167 <            Map<?,?> m = (Map<?,?>) o;
3168 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3169 <            Object val;
3170 <            while ((val = it.advance()) != null) {
3171 <                Object v = m.get(it.nextKey);
3172 <                if (v == null || (v != val && !v.equals(val)))
3173 <                    return false;
3174 <            }
3175 <            for (Map.Entry<?,?> e : m.entrySet()) {
3176 <                Object mk, mv, v;
3177 <                if ((mk = e.getKey()) == null ||
3178 <                    (mv = e.getValue()) == null ||
3179 <                    (v = internalGet(mk)) == null ||
3180 <                    (mv != v && !mv.equals(v)))
3181 <                    return false;
3163 >    static class Traverser<K,V> {
3164 >        Node<K,V>[] tab;        // current table; updated if resized
3165 >        Node<K,V> next;         // the next entry to use
3166 >        int index;              // index of bin to use next
3167 >        int baseIndex;          // current index of initial table
3168 >        int baseLimit;          // index bound for initial table
3169 >        final int baseSize;     // initial table size
3170 >
3171 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3172 >            this.tab = tab;
3173 >            this.baseSize = size;
3174 >            this.baseIndex = this.index = index;
3175 >            this.baseLimit = limit;
3176 >            this.next = null;
3177 >        }
3178 >
3179 >        /**
3180 >         * Advances if possible, returning next valid node, or null if none.
3181 >         */
3182 >        final Node<K,V> advance() {
3183 >            Node<K,V> e;
3184 >            if ((e = next) != null)
3185 >                e = e.next;
3186 >            for (;;) {
3187 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
3188 >                if (e != null)
3189 >                    return next = e;
3190 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3191 >                    (n = t.length) <= (i = index) || i < 0)
3192 >                    return next = null;
3193 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
3194 >                    if (e instanceof ForwardingNode) {
3195 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3196 >                        e = null;
3197 >                        continue;
3198 >                    }
3199 >                    else if (e instanceof TreeBin)
3200 >                        e = ((TreeBin<K,V>)e).first;
3201 >                    else
3202 >                        e = null;
3203 >                }
3204 >                if ((index += baseSize) >= n)
3205 >                    index = ++baseIndex;    // visit upper slots if present
3206              }
3207          }
3172        return true;
3208      }
3209  
3210 <    /* ----------------Iterators -------------- */
3211 <
3212 <    @SuppressWarnings("serial") static final class KeyIterator<K,V> extends Traverser<K,V,Object>
3213 <        implements Spliterator<K>, Enumeration<K> {
3214 <        KeyIterator(ConcurrentHashMap<K, V> map) { super(map); }
3215 <        KeyIterator(Traverser<K,V,Object> it) {
3216 <            super(it);
3210 >    /**
3211 >     * Base of key, value, and entry Iterators. Adds fields to
3212 >     * Traverser to support iterator.remove
3213 >     */
3214 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3215 >        final ConcurrentHashMap<K,V> map;
3216 >        Node<K,V> lastReturned;
3217 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3218 >                    ConcurrentHashMap<K,V> map) {
3219 >            super(tab, size, index, limit);
3220 >            this.map = map;
3221 >            advance();
3222          }
3223 <        public KeyIterator<K,V> split() {
3224 <            if (nextKey != null)
3223 >
3224 >        public final boolean hasNext() { return next != null; }
3225 >        public final boolean hasMoreElements() { return next != null; }
3226 >
3227 >        public final void remove() {
3228 >            Node<K,V> p;
3229 >            if ((p = lastReturned) == null)
3230                  throw new IllegalStateException();
3231 <            return new KeyIterator<K,V>(this);
3231 >            lastReturned = null;
3232 >            map.replaceNode(p.key, null, null);
3233          }
3234 <        @SuppressWarnings("unchecked") public final K next() {
3235 <            if (nextVal == null && advance() == null)
3234 >    }
3235 >
3236 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3237 >        implements Iterator<K>, Enumeration<K> {
3238 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3239 >                    ConcurrentHashMap<K,V> map) {
3240 >            super(tab, index, size, limit, map);
3241 >        }
3242 >
3243 >        public final K next() {
3244 >            Node<K,V> p;
3245 >            if ((p = next) == null)
3246                  throw new NoSuchElementException();
3247 <            Object k = nextKey;
3248 <            nextVal = null;
3249 <            return (K) k;
3247 >            K k = p.key;
3248 >            lastReturned = p;
3249 >            advance();
3250 >            return k;
3251          }
3252  
3253          public final K nextElement() { return next(); }
3254      }
3255  
3256 <    @SuppressWarnings("serial") static final class ValueIterator<K,V> extends Traverser<K,V,Object>
3257 <        implements Spliterator<V>, Enumeration<V> {
3258 <        ValueIterator(ConcurrentHashMap<K, V> map) { super(map); }
3259 <        ValueIterator(Traverser<K,V,Object> it) {
3260 <            super(it);
3204 <        }
3205 <        public ValueIterator<K,V> split() {
3206 <            if (nextKey != null)
3207 <                throw new IllegalStateException();
3208 <            return new ValueIterator<K,V>(this);
3256 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3257 >        implements Iterator<V>, Enumeration<V> {
3258 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3259 >                      ConcurrentHashMap<K,V> map) {
3260 >            super(tab, index, size, limit, map);
3261          }
3262  
3263 <        @SuppressWarnings("unchecked") public final V next() {
3264 <            Object v;
3265 <            if ((v = nextVal) == null && (v = advance()) == null)
3263 >        public final V next() {
3264 >            Node<K,V> p;
3265 >            if ((p = next) == null)
3266                  throw new NoSuchElementException();
3267 <            nextVal = null;
3268 <            return (V) v;
3267 >            V v = p.val;
3268 >            lastReturned = p;
3269 >            advance();
3270 >            return v;
3271          }
3272  
3273          public final V nextElement() { return next(); }
3274      }
3275  
3276 <    @SuppressWarnings("serial") static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3277 <        implements Spliterator<Map.Entry<K,V>> {
3278 <        EntryIterator(ConcurrentHashMap<K, V> map) { super(map); }
3279 <        EntryIterator(Traverser<K,V,Object> it) {
3280 <            super(it);
3227 <        }
3228 <        public EntryIterator<K,V> split() {
3229 <            if (nextKey != null)
3230 <                throw new IllegalStateException();
3231 <            return new EntryIterator<K,V>(this);
3276 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3277 >        implements Iterator<Map.Entry<K,V>> {
3278 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3279 >                      ConcurrentHashMap<K,V> map) {
3280 >            super(tab, index, size, limit, map);
3281          }
3282  
3283 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3284 <            Object v;
3285 <            if ((v = nextVal) == null && (v = advance()) == null)
3283 >        public final Map.Entry<K,V> next() {
3284 >            Node<K,V> p;
3285 >            if ((p = next) == null)
3286                  throw new NoSuchElementException();
3287 <            Object k = nextKey;
3288 <            nextVal = null;
3289 <            return new MapEntry<K,V>((K)k, (V)v, map);
3287 >            K k = p.key;
3288 >            V v = p.val;
3289 >            lastReturned = p;
3290 >            advance();
3291 >            return new MapEntry<K,V>(k, v, map);
3292          }
3293      }
3294  
3295      /**
3296 <     * Exported Entry for iterators
3296 >     * Exported Entry for EntryIterator
3297       */
3298 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3298 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3299          final K key; // non-null
3300          V val;       // non-null
3301 <        final ConcurrentHashMap<K, V> map;
3302 <        MapEntry(K key, V val, ConcurrentHashMap<K, V> map) {
3301 >        final ConcurrentHashMap<K,V> map;
3302 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3303              this.key = key;
3304              this.val = val;
3305              this.map = map;
3306          }
3307 <        public final K getKey()       { return key; }
3308 <        public final V getValue()     { return val; }
3309 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3310 <        public final String toString(){ return key + "=" + val; }
3307 >        public K getKey()        { return key; }
3308 >        public V getValue()      { return val; }
3309 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3310 >        public String toString() { return key + "=" + val; }
3311  
3312 <        public final boolean equals(Object o) {
3312 >        public boolean equals(Object o) {
3313              Object k, v; Map.Entry<?,?> e;
3314              return ((o instanceof Map.Entry) &&
3315                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3272 | Line 3323 | public class ConcurrentHashMap<K, V>
3323           * value to return is somewhat arbitrary here. Since we do not
3324           * necessarily track asynchronous changes, the most recent
3325           * "previous" value could be different from what we return (or
3326 <         * could even have been removed in which case the put will
3326 >         * could even have been removed, in which case the put will
3327           * re-establish). We do not and cannot guarantee more.
3328           */
3329 <        public final V setValue(V value) {
3329 >        public V setValue(V value) {
3330              if (value == null) throw new NullPointerException();
3331              V v = val;
3332              val = value;
# Line 3284 | Line 3335 | public class ConcurrentHashMap<K, V>
3335          }
3336      }
3337  
3338 <    /* ---------------- Serialization Support -------------- */
3338 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3339 >        implements Spliterator<K> {
3340 >        long est;               // size estimate
3341 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3342 >                       long est) {
3343 >            super(tab, size, index, limit);
3344 >            this.est = est;
3345 >        }
3346 >
3347 >        public Spliterator<K> trySplit() {
3348 >            int i, f, h;
3349 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3350 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3351 >                                        f, est >>>= 1);
3352 >        }
3353  
3354 <    /**
3355 <     * Stripped-down version of helper class used in previous version,
3356 <     * declared for the sake of serialization compatibility
3357 <     */
3358 <    static class Segment<K,V> implements Serializable {
3294 <        private static final long serialVersionUID = 2249069246763182397L;
3295 <        final float loadFactor;
3296 <        Segment(float lf) { this.loadFactor = lf; }
3297 <    }
3354 >        public void forEachRemaining(Consumer<? super K> action) {
3355 >            if (action == null) throw new NullPointerException();
3356 >            for (Node<K,V> p; (p = advance()) != null;)
3357 >                action.accept(p.key);
3358 >        }
3359  
3360 <    /**
3361 <     * Saves the state of the {@code ConcurrentHashMap} instance to a
3362 <     * stream (i.e., serializes it).
3363 <     * @param s the stream
3364 <     * @serialData
3365 <     * the key (Object) and value (Object)
3366 <     * for each key-value mapping, followed by a null pair.
3367 <     * The key-value mappings are emitted in no particular order.
3368 <     */
3369 <    @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s)
3370 <        throws java.io.IOException {
3371 <        if (segments == null) { // for serialization compatibility
3372 <            segments = (Segment<K,V>[])
3373 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3313 <            for (int i = 0; i < segments.length; ++i)
3314 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3315 <        }
3316 <        s.defaultWriteObject();
3317 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3318 <        Object v;
3319 <        while ((v = it.advance()) != null) {
3320 <            s.writeObject(it.nextKey);
3321 <            s.writeObject(v);
3360 >        public boolean tryAdvance(Consumer<? super K> action) {
3361 >            if (action == null) throw new NullPointerException();
3362 >            Node<K,V> p;
3363 >            if ((p = advance()) == null)
3364 >                return false;
3365 >            action.accept(p.key);
3366 >            return true;
3367 >        }
3368 >
3369 >        public long estimateSize() { return est; }
3370 >
3371 >        public int characteristics() {
3372 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3373 >                Spliterator.NONNULL;
3374          }
3323        s.writeObject(null);
3324        s.writeObject(null);
3325        segments = null; // throw away
3375      }
3376  
3377 <    /**
3378 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3379 <     * @param s the stream
3380 <     */
3381 <    @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
3382 <        throws java.io.IOException, ClassNotFoundException {
3383 <        s.defaultReadObject();
3384 <        this.segments = null; // unneeded
3336 <        // initialize transient final field
3337 <        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
3377 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3378 >        implements Spliterator<V> {
3379 >        long est;               // size estimate
3380 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3381 >                         long est) {
3382 >            super(tab, size, index, limit);
3383 >            this.est = est;
3384 >        }
3385  
3386 <        // Create all nodes, then place in table once size is known
3387 <        long size = 0L;
3388 <        Node p = null;
3389 <        for (;;) {
3390 <            K k = (K) s.readObject();
3344 <            V v = (V) s.readObject();
3345 <            if (k != null && v != null) {
3346 <                int h = spread(k.hashCode());
3347 <                p = new Node(h, k, v, p);
3348 <                ++size;
3349 <            }
3350 <            else
3351 <                break;
3386 >        public Spliterator<V> trySplit() {
3387 >            int i, f, h;
3388 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3389 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3390 >                                          f, est >>>= 1);
3391          }
3392 <        if (p != null) {
3393 <            boolean init = false;
3394 <            int n;
3395 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3396 <                n = MAXIMUM_CAPACITY;
3397 <            else {
3398 <                int sz = (int)size;
3399 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3400 <            }
3401 <            int sc = sizeCtl;
3402 <            boolean collide = false;
3403 <            if (n > sc &&
3404 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3405 <                try {
3406 <                    if (table == null) {
3407 <                        init = true;
3408 <                        Node[] tab = new Node[n];
3409 <                        int mask = n - 1;
3410 <                        while (p != null) {
3411 <                            int j = p.hash & mask;
3373 <                            Node next = p.next;
3374 <                            Node q = p.next = tabAt(tab, j);
3375 <                            setTabAt(tab, j, p);
3376 <                            if (!collide && q != null && q.hash == p.hash)
3377 <                                collide = true;
3378 <                            p = next;
3379 <                        }
3380 <                        table = tab;
3381 <                        counter.add(size);
3382 <                        sc = n - (n >>> 2);
3383 <                    }
3384 <                } finally {
3385 <                    sizeCtl = sc;
3386 <                }
3387 <                if (collide) { // rescan and convert to TreeBins
3388 <                    Node[] tab = table;
3389 <                    for (int i = 0; i < tab.length; ++i) {
3390 <                        int c = 0;
3391 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3392 <                            if (++c > TREE_THRESHOLD &&
3393 <                                (e.key instanceof Comparable)) {
3394 <                                replaceWithTreeBin(tab, i, e.key);
3395 <                                break;
3396 <                            }
3397 <                        }
3398 <                    }
3399 <                }
3400 <            }
3401 <            if (!init) { // Can only happen if unsafely published.
3402 <                while (p != null) {
3403 <                    internalPut(p.key, p.val);
3404 <                    p = p.next;
3405 <                }
3406 <            }
3392 >
3393 >        public void forEachRemaining(Consumer<? super V> action) {
3394 >            if (action == null) throw new NullPointerException();
3395 >            for (Node<K,V> p; (p = advance()) != null;)
3396 >                action.accept(p.val);
3397 >        }
3398 >
3399 >        public boolean tryAdvance(Consumer<? super V> action) {
3400 >            if (action == null) throw new NullPointerException();
3401 >            Node<K,V> p;
3402 >            if ((p = advance()) == null)
3403 >                return false;
3404 >            action.accept(p.val);
3405 >            return true;
3406 >        }
3407 >
3408 >        public long estimateSize() { return est; }
3409 >
3410 >        public int characteristics() {
3411 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3412          }
3413      }
3414  
3415 +    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3416 +        implements Spliterator<Map.Entry<K,V>> {
3417 +        final ConcurrentHashMap<K,V> map; // To export MapEntry
3418 +        long est;               // size estimate
3419 +        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3420 +                         long est, ConcurrentHashMap<K,V> map) {
3421 +            super(tab, size, index, limit);
3422 +            this.map = map;
3423 +            this.est = est;
3424 +        }
3425  
3426 <    // -------------------------------------------------------
3426 >        public Spliterator<Map.Entry<K,V>> trySplit() {
3427 >            int i, f, h;
3428 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3429 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3430 >                                          f, est >>>= 1, map);
3431 >        }
3432  
3433 <    // Sams
3434 <    /** Interface describing a void action of one argument */
3435 <    public interface Action<A> { void apply(A a); }
3436 <    /** Interface describing a void action of two arguments */
3437 <    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); }
3433 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3434 >            if (action == null) throw new NullPointerException();
3435 >            for (Node<K,V> p; (p = advance()) != null; )
3436 >                action.accept(new MapEntry<K,V>(p.key, p.val, map));
3437 >        }
3438  
3439 +        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3440 +            if (action == null) throw new NullPointerException();
3441 +            Node<K,V> p;
3442 +            if ((p = advance()) == null)
3443 +                return false;
3444 +            action.accept(new MapEntry<K,V>(p.key, p.val, map));
3445 +            return true;
3446 +        }
3447  
3448 <    // -------------------------------------------------------
3448 >        public long estimateSize() { return est; }
3449 >
3450 >        public int characteristics() {
3451 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3452 >                Spliterator.NONNULL;
3453 >        }
3454 >    }
3455 >
3456 >    // Parallel bulk operations
3457 >
3458 >    /**
3459 >     * Computes initial batch value for bulk tasks. The returned value
3460 >     * is approximately exp2 of the number of times (minus one) to
3461 >     * split task by two before executing leaf action. This value is
3462 >     * faster to compute and more convenient to use as a guide to
3463 >     * splitting than is the depth, since it is used while dividing by
3464 >     * two anyway.
3465 >     */
3466 >    final int batchFor(long b) {
3467 >        long n;
3468 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3469 >            return 0;
3470 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3471 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3472 >    }
3473  
3474      /**
3475       * Performs the given action for each (key, value).
3476       *
3477 +     * @param parallelismThreshold the (estimated) number of elements
3478 +     * needed for this operation to be executed in parallel
3479       * @param action the action
3480 +     * @since 1.8
3481       */
3482 <    public void forEach(BiAction<K,V> action) {
3483 <        ForkJoinTasks.forEach
3484 <            (this, action).invoke();
3482 >    public void forEach(long parallelismThreshold,
3483 >                        BiConsumer<? super K,? super V> action) {
3484 >        if (action == null) throw new NullPointerException();
3485 >        new ForEachMappingTask<K,V>
3486 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3487 >             action).invoke();
3488      }
3489  
3490      /**
3491       * Performs the given action for each non-null transformation
3492       * of each (key, value).
3493       *
3494 +     * @param parallelismThreshold the (estimated) number of elements
3495 +     * needed for this operation to be executed in parallel
3496       * @param transformer a function returning the transformation
3497 <     * for an element, or null of there is no transformation (in
3498 <     * which case the action is not applied).
3497 >     * for an element, or null if there is no transformation (in
3498 >     * which case the action is not applied)
3499       * @param action the action
3500 +     * @since 1.8
3501       */
3502 <    public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3503 <                            Action<U> action) {
3504 <        ForkJoinTasks.forEach
3505 <            (this, transformer, action).invoke();
3502 >    public <U> void forEach(long parallelismThreshold,
3503 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3504 >                            Consumer<? super U> action) {
3505 >        if (transformer == null || action == null)
3506 >            throw new NullPointerException();
3507 >        new ForEachTransformedMappingTask<K,V,U>
3508 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3509 >             transformer, action).invoke();
3510      }
3511  
3512      /**
# Line 3481 | Line 3516 | public class ConcurrentHashMap<K, V>
3516       * results of any other parallel invocations of the search
3517       * function are ignored.
3518       *
3519 +     * @param parallelismThreshold the (estimated) number of elements
3520 +     * needed for this operation to be executed in parallel
3521       * @param searchFunction a function returning a non-null
3522       * result on success, else null
3523       * @return a non-null result from applying the given search
3524       * function on each (key, value), or null if none
3525 +     * @since 1.8
3526       */
3527 <    public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3528 <        return ForkJoinTasks.search
3529 <            (this, searchFunction).invoke();
3527 >    public <U> U search(long parallelismThreshold,
3528 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3529 >        if (searchFunction == null) throw new NullPointerException();
3530 >        return new SearchMappingsTask<K,V,U>
3531 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3532 >             searchFunction, new AtomicReference<U>()).invoke();
3533      }
3534  
3535      /**
# Line 3496 | Line 3537 | public class ConcurrentHashMap<K, V>
3537       * of all (key, value) pairs using the given reducer to
3538       * combine values, or null if none.
3539       *
3540 +     * @param parallelismThreshold the (estimated) number of elements
3541 +     * needed for this operation to be executed in parallel
3542       * @param transformer a function returning the transformation
3543 <     * for an element, or null of there is no transformation (in
3544 <     * which case it is not combined).
3543 >     * for an element, or null if there is no transformation (in
3544 >     * which case it is not combined)
3545       * @param reducer a commutative associative combining function
3546       * @return the result of accumulating the given transformation
3547       * of all (key, value) pairs
3548 +     * @since 1.8
3549       */
3550 <    public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3551 <                        BiFun<? super U, ? super U, ? extends U> reducer) {
3552 <        return ForkJoinTasks.reduce
3553 <            (this, transformer, reducer).invoke();
3550 >    public <U> U reduce(long parallelismThreshold,
3551 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3552 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3553 >        if (transformer == null || reducer == null)
3554 >            throw new NullPointerException();
3555 >        return new MapReduceMappingsTask<K,V,U>
3556 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3557 >             null, transformer, reducer).invoke();
3558      }
3559  
3560      /**
# Line 3514 | Line 3562 | public class ConcurrentHashMap<K, V>
3562       * of all (key, value) pairs using the given reducer to
3563       * combine values, and the given basis as an identity value.
3564       *
3565 +     * @param parallelismThreshold the (estimated) number of elements
3566 +     * needed for this operation to be executed in parallel
3567       * @param transformer a function returning the transformation
3568       * for an element
3569       * @param basis the identity (initial default value) for the reduction
3570       * @param reducer a commutative associative combining function
3571       * @return the result of accumulating the given transformation
3572       * of all (key, value) pairs
3573 +     * @since 1.8
3574       */
3575 <    public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
3576 <                                 double basis,
3577 <                                 DoubleByDoubleToDouble reducer) {
3578 <        return ForkJoinTasks.reduceToDouble
3579 <            (this, transformer, basis, reducer).invoke();
3575 >    public double reduceToDoubleIn(long parallelismThreshold,
3576 >                                   ToDoubleBiFunction<? super K, ? super V> transformer,
3577 >                                   double basis,
3578 >                                   DoubleBinaryOperator reducer) {
3579 >        if (transformer == null || reducer == null)
3580 >            throw new NullPointerException();
3581 >        return new MapReduceMappingsToDoubleTask<K,V>
3582 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3583 >             null, transformer, basis, reducer).invoke();
3584      }
3585  
3586      /**
# Line 3533 | Line 3588 | public class ConcurrentHashMap<K, V>
3588       * of all (key, value) pairs using the given reducer to
3589       * combine values, and the given basis as an identity value.
3590       *
3591 +     * @param parallelismThreshold the (estimated) number of elements
3592 +     * needed for this operation to be executed in parallel
3593       * @param transformer a function returning the transformation
3594       * for an element
3595       * @param basis the identity (initial default value) for the reduction
3596       * @param reducer a commutative associative combining function
3597       * @return the result of accumulating the given transformation
3598       * of all (key, value) pairs
3599 +     * @since 1.8
3600       */
3601 <    public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
3601 >    public long reduceToLong(long parallelismThreshold,
3602 >                             ToLongBiFunction<? super K, ? super V> transformer,
3603                               long basis,
3604 <                             LongByLongToLong reducer) {
3605 <        return ForkJoinTasks.reduceToLong
3606 <            (this, transformer, basis, reducer).invoke();
3604 >                             LongBinaryOperator reducer) {
3605 >        if (transformer == null || reducer == null)
3606 >            throw new NullPointerException();
3607 >        return new MapReduceMappingsToLongTask<K,V>
3608 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3609 >             null, transformer, basis, reducer).invoke();
3610      }
3611  
3612      /**
# Line 3552 | Line 3614 | public class ConcurrentHashMap<K, V>
3614       * of all (key, value) pairs using the given reducer to
3615       * combine values, and the given basis as an identity value.
3616       *
3617 +     * @param parallelismThreshold the (estimated) number of elements
3618 +     * needed for this operation to be executed in parallel
3619       * @param transformer a function returning the transformation
3620       * for an element
3621       * @param basis the identity (initial default value) for the reduction
3622       * @param reducer a commutative associative combining function
3623       * @return the result of accumulating the given transformation
3624       * of all (key, value) pairs
3625 +     * @since 1.8
3626       */
3627 <    public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
3627 >    public int reduceToInt(long parallelismThreshold,
3628 >                           ToIntBiFunction<? super K, ? super V> transformer,
3629                             int basis,
3630 <                           IntByIntToInt reducer) {
3631 <        return ForkJoinTasks.reduceToInt
3632 <            (this, transformer, basis, reducer).invoke();
3630 >                           IntBinaryOperator reducer) {
3631 >        if (transformer == null || reducer == null)
3632 >            throw new NullPointerException();
3633 >        return new MapReduceMappingsToIntTask<K,V>
3634 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3635 >             null, transformer, basis, reducer).invoke();
3636      }
3637  
3638      /**
3639       * Performs the given action for each key.
3640       *
3641 +     * @param parallelismThreshold the (estimated) number of elements
3642 +     * needed for this operation to be executed in parallel
3643       * @param action the action
3644 +     * @since 1.8
3645       */
3646 <    public void forEachKey(Action<K> action) {
3647 <        ForkJoinTasks.forEachKey
3648 <            (this, action).invoke();
3646 >    public void forEachKey(long parallelismThreshold,
3647 >                           Consumer<? super K> action) {
3648 >        if (action == null) throw new NullPointerException();
3649 >        new ForEachKeyTask<K,V>
3650 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3651 >             action).invoke();
3652      }
3653  
3654      /**
3655       * Performs the given action for each non-null transformation
3656       * of each key.
3657       *
3658 +     * @param parallelismThreshold the (estimated) number of elements
3659 +     * needed for this operation to be executed in parallel
3660       * @param transformer a function returning the transformation
3661 <     * for an element, or null of there is no transformation (in
3662 <     * which case the action is not applied).
3661 >     * for an element, or null if there is no transformation (in
3662 >     * which case the action is not applied)
3663       * @param action the action
3664 +     * @since 1.8
3665       */
3666 <    public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
3667 <                               Action<U> action) {
3668 <        ForkJoinTasks.forEachKey
3669 <            (this, transformer, action).invoke();
3666 >    public <U> void forEachKey(long parallelismThreshold,
3667 >                               Function<? super K, ? extends U> transformer,
3668 >                               Consumer<? super U> action) {
3669 >        if (transformer == null || action == null)
3670 >            throw new NullPointerException();
3671 >        new ForEachTransformedKeyTask<K,V,U>
3672 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3673 >             transformer, action).invoke();
3674      }
3675  
3676      /**
# Line 3598 | Line 3680 | public class ConcurrentHashMap<K, V>
3680       * any other parallel invocations of the search function are
3681       * ignored.
3682       *
3683 +     * @param parallelismThreshold the (estimated) number of elements
3684 +     * needed for this operation to be executed in parallel
3685       * @param searchFunction a function returning a non-null
3686       * result on success, else null
3687       * @return a non-null result from applying the given search
3688       * function on each key, or null if none
3689 +     * @since 1.8
3690       */
3691 <    public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
3692 <        return ForkJoinTasks.searchKeys
3693 <            (this, searchFunction).invoke();
3691 >    public <U> U searchKeys(long parallelismThreshold,
3692 >                            Function<? super K, ? extends U> searchFunction) {
3693 >        if (searchFunction == null) throw new NullPointerException();
3694 >        return new SearchKeysTask<K,V,U>
3695 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3696 >             searchFunction, new AtomicReference<U>()).invoke();
3697      }
3698  
3699      /**
3700       * Returns the result of accumulating all keys using the given
3701       * reducer to combine values, or null if none.
3702       *
3703 +     * @param parallelismThreshold the (estimated) number of elements
3704 +     * needed for this operation to be executed in parallel
3705       * @param reducer a commutative associative combining function
3706       * @return the result of accumulating all keys using the given
3707       * reducer to combine values, or null if none
3708 +     * @since 1.8
3709       */
3710 <    public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
3711 <        return ForkJoinTasks.reduceKeys
3712 <            (this, reducer).invoke();
3710 >    public K reduceKeys(long parallelismThreshold,
3711 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3712 >        if (reducer == null) throw new NullPointerException();
3713 >        return new ReduceKeysTask<K,V>
3714 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3715 >             null, reducer).invoke();
3716      }
3717  
3718      /**
# Line 3626 | Line 3720 | public class ConcurrentHashMap<K, V>
3720       * of all keys using the given reducer to combine values, or
3721       * null if none.
3722       *
3723 +     * @param parallelismThreshold the (estimated) number of elements
3724 +     * needed for this operation to be executed in parallel
3725       * @param transformer a function returning the transformation
3726 <     * for an element, or null of there is no transformation (in
3727 <     * which case it is not combined).
3726 >     * for an element, or null if there is no transformation (in
3727 >     * which case it is not combined)
3728       * @param reducer a commutative associative combining function
3729       * @return the result of accumulating the given transformation
3730       * of all keys
3731 +     * @since 1.8
3732       */
3733 <    public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
3734 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
3735 <        return ForkJoinTasks.reduceKeys
3736 <            (this, transformer, reducer).invoke();
3733 >    public <U> U reduceKeys(long parallelismThreshold,
3734 >                            Function<? super K, ? extends U> transformer,
3735 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3736 >        if (transformer == null || reducer == null)
3737 >            throw new NullPointerException();
3738 >        return new MapReduceKeysTask<K,V,U>
3739 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3740 >             null, transformer, reducer).invoke();
3741      }
3742  
3743      /**
# Line 3644 | Line 3745 | public class ConcurrentHashMap<K, V>
3745       * of all keys using the given reducer to combine values, and
3746       * the given basis as an identity value.
3747       *
3748 +     * @param parallelismThreshold the (estimated) number of elements
3749 +     * needed for this operation to be executed in parallel
3750       * @param transformer a function returning the transformation
3751       * for an element
3752       * @param basis the identity (initial default value) for the reduction
3753       * @param reducer a commutative associative combining function
3754 <     * @return  the result of accumulating the given transformation
3754 >     * @return the result of accumulating the given transformation
3755       * of all keys
3756 +     * @since 1.8
3757       */
3758 <    public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
3758 >    public double reduceKeysToDouble(long parallelismThreshold,
3759 >                                     ToDoubleFunction<? super K> transformer,
3760                                       double basis,
3761 <                                     DoubleByDoubleToDouble reducer) {
3762 <        return ForkJoinTasks.reduceKeysToDouble
3763 <            (this, transformer, basis, reducer).invoke();
3761 >                                     DoubleBinaryOperator reducer) {
3762 >        if (transformer == null || reducer == null)
3763 >            throw new NullPointerException();
3764 >        return new MapReduceKeysToDoubleTask<K,V>
3765 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3766 >             null, transformer, basis, reducer).invoke();
3767      }
3768  
3769      /**
# Line 3663 | Line 3771 | public class ConcurrentHashMap<K, V>
3771       * of all keys using the given reducer to combine values, and
3772       * the given basis as an identity value.
3773       *
3774 +     * @param parallelismThreshold the (estimated) number of elements
3775 +     * needed for this operation to be executed in parallel
3776       * @param transformer a function returning the transformation
3777       * for an element
3778       * @param basis the identity (initial default value) for the reduction
3779       * @param reducer a commutative associative combining function
3780       * @return the result of accumulating the given transformation
3781       * of all keys
3782 +     * @since 1.8
3783       */
3784 <    public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3784 >    public long reduceKeysToLong(long parallelismThreshold,
3785 >                                 ToLongFunction<? super K> transformer,
3786                                   long basis,
3787 <                                 LongByLongToLong reducer) {
3788 <        return ForkJoinTasks.reduceKeysToLong
3789 <            (this, transformer, basis, reducer).invoke();
3787 >                                 LongBinaryOperator reducer) {
3788 >        if (transformer == null || reducer == null)
3789 >            throw new NullPointerException();
3790 >        return new MapReduceKeysToLongTask<K,V>
3791 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3792 >             null, transformer, basis, reducer).invoke();
3793      }
3794  
3795      /**
# Line 3682 | Line 3797 | public class ConcurrentHashMap<K, V>
3797       * of all keys using the given reducer to combine values, and
3798       * the given basis as an identity value.
3799       *
3800 +     * @param parallelismThreshold the (estimated) number of elements
3801 +     * needed for this operation to be executed in parallel
3802       * @param transformer a function returning the transformation
3803       * for an element
3804       * @param basis the identity (initial default value) for the reduction
3805       * @param reducer a commutative associative combining function
3806       * @return the result of accumulating the given transformation
3807       * of all keys
3808 +     * @since 1.8
3809       */
3810 <    public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3810 >    public int reduceKeysToInt(long parallelismThreshold,
3811 >                               ToIntFunction<? super K> transformer,
3812                                 int basis,
3813 <                               IntByIntToInt reducer) {
3814 <        return ForkJoinTasks.reduceKeysToInt
3815 <            (this, transformer, basis, reducer).invoke();
3813 >                               IntBinaryOperator reducer) {
3814 >        if (transformer == null || reducer == null)
3815 >            throw new NullPointerException();
3816 >        return new MapReduceKeysToIntTask<K,V>
3817 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3818 >             null, transformer, basis, reducer).invoke();
3819      }
3820  
3821      /**
3822       * Performs the given action for each value.
3823       *
3824 +     * @param parallelismThreshold the (estimated) number of elements
3825 +     * needed for this operation to be executed in parallel
3826       * @param action the action
3827 +     * @since 1.8
3828       */
3829 <    public void forEachValue(Action<V> action) {
3830 <        ForkJoinTasks.forEachValue
3831 <            (this, action).invoke();
3829 >    public void forEachValue(long parallelismThreshold,
3830 >                             Consumer<? super V> action) {
3831 >        if (action == null)
3832 >            throw new NullPointerException();
3833 >        new ForEachValueTask<K,V>
3834 >            (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 value.
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 forEachValue(Fun<? super V, ? extends U> transformer,
3851 <                                 Action<U> action) {
3852 <        ForkJoinTasks.forEachValue
3853 <            (this, transformer, action).invoke();
3850 >    public <U> void forEachValue(long parallelismThreshold,
3851 >                                 Function<? super V, ? extends U> transformer,
3852 >                                 Consumer<? super U> action) {
3853 >        if (transformer == null || action == null)
3854 >            throw new NullPointerException();
3855 >        new ForEachTransformedValueTask<K,V,U>
3856 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3857 >             transformer, action).invoke();
3858      }
3859  
3860      /**
# Line 3727 | 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 value, or null if none
3873 <     *
3873 >     * @since 1.8
3874       */
3875 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
3876 <        return ForkJoinTasks.searchValues
3877 <            (this, searchFunction).invoke();
3875 >    public <U> U searchValues(long parallelismThreshold,
3876 >                              Function<? super V, ? extends U> searchFunction) {
3877 >        if (searchFunction == null) throw new NullPointerException();
3878 >        return new SearchValuesTask<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 values 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 values
3890 >     * @return the result of accumulating all values
3891 >     * @since 1.8
3892       */
3893 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
3894 <        return ForkJoinTasks.reduceValues
3895 <            (this, reducer).invoke();
3893 >    public V reduceValues(long parallelismThreshold,
3894 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
3895 >        if (reducer == null) throw new NullPointerException();
3896 >        return new ReduceValuesTask<K,V>
3897 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3898 >             null, reducer).invoke();
3899      }
3900  
3901      /**
# Line 3755 | Line 3903 | public class ConcurrentHashMap<K, V>
3903       * of all values using the given reducer to combine values, or
3904       * 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 values
3914 +     * @since 1.8
3915       */
3916 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
3917 <                              BiFun<? super U, ? super U, ? extends U> reducer) {
3918 <        return ForkJoinTasks.reduceValues
3919 <            (this, transformer, reducer).invoke();
3916 >    public <U> U reduceValues(long parallelismThreshold,
3917 >                              Function<? super 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 MapReduceValuesTask<K,V,U>
3922 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3923 >             null, transformer, reducer).invoke();
3924      }
3925  
3926      /**
# Line 3773 | Line 3928 | public class ConcurrentHashMap<K, V>
3928       * of all values 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 values
3939 +     * @since 1.8
3940       */
3941 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
3941 >    public double reduceValuesToDouble(long parallelismThreshold,
3942 >                                       ToDoubleFunction<? super V> transformer,
3943                                         double basis,
3944 <                                       DoubleByDoubleToDouble reducer) {
3945 <        return ForkJoinTasks.reduceValuesToDouble
3946 <            (this, transformer, basis, reducer).invoke();
3944 >                                       DoubleBinaryOperator reducer) {
3945 >        if (transformer == null || reducer == null)
3946 >            throw new NullPointerException();
3947 >        return new MapReduceValuesToDoubleTask<K,V>
3948 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3949 >             null, transformer, basis, reducer).invoke();
3950      }
3951  
3952      /**
# Line 3792 | Line 3954 | public class ConcurrentHashMap<K, V>
3954       * of all values 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
3964       * of all values
3965 +     * @since 1.8
3966       */
3967 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
3967 >    public long reduceValuesToLong(long parallelismThreshold,
3968 >                                   ToLongFunction<? super V> transformer,
3969                                     long basis,
3970 <                                   LongByLongToLong reducer) {
3971 <        return ForkJoinTasks.reduceValuesToLong
3972 <            (this, transformer, basis, reducer).invoke();
3970 >                                   LongBinaryOperator reducer) {
3971 >        if (transformer == null || reducer == null)
3972 >            throw new NullPointerException();
3973 >        return new MapReduceValuesToLongTask<K,V>
3974 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3975 >             null, transformer, basis, reducer).invoke();
3976      }
3977  
3978      /**
# Line 3811 | Line 3980 | public class ConcurrentHashMap<K, V>
3980       * of all values using the given reducer to combine values,
3981       * and the given basis as an identity value.
3982       *
3983 +     * @param parallelismThreshold the (estimated) number of elements
3984 +     * needed for this operation to be executed in parallel
3985       * @param transformer a function returning the transformation
3986       * for an element
3987       * @param basis the identity (initial default value) for the reduction
3988       * @param reducer a commutative associative combining function
3989       * @return the result of accumulating the given transformation
3990       * of all values
3991 +     * @since 1.8
3992       */
3993 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
3993 >    public int reduceValuesToInt(long parallelismThreshold,
3994 >                                 ToIntFunction<? super V> transformer,
3995                                   int basis,
3996 <                                 IntByIntToInt reducer) {
3997 <        return ForkJoinTasks.reduceValuesToInt
3998 <            (this, transformer, basis, reducer).invoke();
3996 >                                 IntBinaryOperator reducer) {
3997 >        if (transformer == null || reducer == null)
3998 >            throw new NullPointerException();
3999 >        return new MapReduceValuesToIntTask<K,V>
4000 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4001 >             null, transformer, basis, reducer).invoke();
4002      }
4003  
4004      /**
4005       * Performs the given action for each entry.
4006       *
4007 +     * @param parallelismThreshold the (estimated) number of elements
4008 +     * needed for this operation to be executed in parallel
4009       * @param action the action
4010 +     * @since 1.8
4011       */
4012 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
4013 <        ForkJoinTasks.forEachEntry
4014 <            (this, action).invoke();
4012 >    public void forEachEntry(long parallelismThreshold,
4013 >                             Consumer<? super Map.Entry<K,V>> action) {
4014 >        if (action == null) throw new NullPointerException();
4015 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4016 >                                  action).invoke();
4017      }
4018  
4019      /**
4020       * Performs the given action for each non-null transformation
4021       * of each entry.
4022       *
4023 +     * @param parallelismThreshold the (estimated) number of elements
4024 +     * needed for this operation to be executed in parallel
4025       * @param transformer a function returning the transformation
4026 <     * for an element, or null of there is no transformation (in
4027 <     * which case the action is not applied).
4026 >     * for an element, or null if there is no transformation (in
4027 >     * which case the action is not applied)
4028       * @param action the action
4029 +     * @since 1.8
4030       */
4031 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4032 <                                 Action<U> action) {
4033 <        ForkJoinTasks.forEachEntry
4034 <            (this, transformer, action).invoke();
4031 >    public <U> void forEachEntry(long parallelismThreshold,
4032 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
4033 >                                 Consumer<? super U> action) {
4034 >        if (transformer == null || action == null)
4035 >            throw new NullPointerException();
4036 >        new ForEachTransformedEntryTask<K,V,U>
4037 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4038 >             transformer, action).invoke();
4039      }
4040  
4041      /**
# Line 3857 | Line 4045 | public class ConcurrentHashMap<K, V>
4045       * any other parallel invocations of the search function are
4046       * ignored.
4047       *
4048 +     * @param parallelismThreshold the (estimated) number of elements
4049 +     * needed for this operation to be executed in parallel
4050       * @param searchFunction a function returning a non-null
4051       * result on success, else null
4052       * @return a non-null result from applying the given search
4053       * function on each entry, or null if none
4054 +     * @since 1.8
4055       */
4056 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4057 <        return ForkJoinTasks.searchEntries
4058 <            (this, searchFunction).invoke();
4056 >    public <U> U searchEntries(long parallelismThreshold,
4057 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4058 >        if (searchFunction == null) throw new NullPointerException();
4059 >        return new SearchEntriesTask<K,V,U>
4060 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4061 >             searchFunction, new AtomicReference<U>()).invoke();
4062      }
4063  
4064      /**
4065       * Returns the result of accumulating all entries using the
4066       * given reducer to combine values, or null if none.
4067       *
4068 +     * @param parallelismThreshold the (estimated) number of elements
4069 +     * needed for this operation to be executed in parallel
4070       * @param reducer a commutative associative combining function
4071       * @return the result of accumulating all entries
4072 +     * @since 1.8
4073       */
4074 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4075 <        return ForkJoinTasks.reduceEntries
4076 <            (this, reducer).invoke();
4074 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4075 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4076 >        if (reducer == null) throw new NullPointerException();
4077 >        return new ReduceEntriesTask<K,V>
4078 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4079 >             null, reducer).invoke();
4080      }
4081  
4082      /**
# Line 3884 | Line 4084 | public class ConcurrentHashMap<K, V>
4084       * of all entries using the given reducer to combine values,
4085       * or null if none.
4086       *
4087 +     * @param parallelismThreshold the (estimated) number of elements
4088 +     * needed for this operation to be executed in parallel
4089       * @param transformer a function returning the transformation
4090 <     * for an element, or null of there is no transformation (in
4091 <     * which case it is not combined).
4090 >     * for an element, or null if there is no transformation (in
4091 >     * which case it is not combined)
4092       * @param reducer a commutative associative combining function
4093       * @return the result of accumulating the given transformation
4094       * of all entries
4095 +     * @since 1.8
4096       */
4097 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4098 <                               BiFun<? super U, ? super U, ? extends U> reducer) {
4099 <        return ForkJoinTasks.reduceEntries
4100 <            (this, transformer, reducer).invoke();
4097 >    public <U> U reduceEntries(long parallelismThreshold,
4098 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
4099 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
4100 >        if (transformer == null || reducer == null)
4101 >            throw new NullPointerException();
4102 >        return new MapReduceEntriesTask<K,V,U>
4103 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4104 >             null, transformer, reducer).invoke();
4105      }
4106  
4107      /**
# Line 3902 | Line 4109 | public class ConcurrentHashMap<K, V>
4109       * of all entries using the given reducer to combine values,
4110       * and the given basis as an identity value.
4111       *
4112 +     * @param parallelismThreshold the (estimated) number of elements
4113 +     * needed for this operation to be executed in parallel
4114       * @param transformer a function returning the transformation
4115       * for an element
4116       * @param basis the identity (initial default value) for the reduction
4117       * @param reducer a commutative associative combining function
4118       * @return the result of accumulating the given transformation
4119       * of all entries
4120 +     * @since 1.8
4121       */
4122 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4122 >    public double reduceEntriesToDouble(long parallelismThreshold,
4123 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
4124                                          double basis,
4125 <                                        DoubleByDoubleToDouble reducer) {
4126 <        return ForkJoinTasks.reduceEntriesToDouble
4127 <            (this, transformer, basis, reducer).invoke();
4125 >                                        DoubleBinaryOperator reducer) {
4126 >        if (transformer == null || reducer == null)
4127 >            throw new NullPointerException();
4128 >        return new MapReduceEntriesToDoubleTask<K,V>
4129 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4130 >             null, transformer, basis, reducer).invoke();
4131      }
4132  
4133      /**
# Line 3921 | Line 4135 | public class ConcurrentHashMap<K, V>
4135       * of all entries using the given reducer to combine values,
4136       * and the given basis as an identity value.
4137       *
4138 +     * @param parallelismThreshold the (estimated) number of elements
4139 +     * needed for this operation to be executed in parallel
4140       * @param transformer a function returning the transformation
4141       * for an element
4142       * @param basis the identity (initial default value) for the reduction
4143       * @param reducer a commutative associative combining function
4144 <     * @return  the result of accumulating the given transformation
4144 >     * @return the result of accumulating the given transformation
4145       * of all entries
4146 +     * @since 1.8
4147       */
4148 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4148 >    public long reduceEntriesToLong(long parallelismThreshold,
4149 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
4150                                      long basis,
4151 <                                    LongByLongToLong reducer) {
4152 <        return ForkJoinTasks.reduceEntriesToLong
4153 <            (this, transformer, basis, reducer).invoke();
4151 >                                    LongBinaryOperator reducer) {
4152 >        if (transformer == null || reducer == null)
4153 >            throw new NullPointerException();
4154 >        return new MapReduceEntriesToLongTask<K,V>
4155 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4156 >             null, transformer, basis, reducer).invoke();
4157      }
4158  
4159      /**
# Line 3940 | Line 4161 | public class ConcurrentHashMap<K, V>
4161       * of all entries using the given reducer to combine values,
4162       * and the given basis as an identity value.
4163       *
4164 +     * @param parallelismThreshold the (estimated) number of elements
4165 +     * needed for this operation to be executed in parallel
4166       * @param transformer a function returning the transformation
4167       * for an element
4168       * @param basis the identity (initial default value) for the reduction
4169       * @param reducer a commutative associative combining function
4170       * @return the result of accumulating the given transformation
4171       * of all entries
4172 +     * @since 1.8
4173       */
4174 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4174 >    public int reduceEntriesToInt(long parallelismThreshold,
4175 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
4176                                    int basis,
4177 <                                  IntByIntToInt reducer) {
4178 <        return ForkJoinTasks.reduceEntriesToInt
4179 <            (this, transformer, basis, reducer).invoke();
4177 >                                  IntBinaryOperator reducer) {
4178 >        if (transformer == null || reducer == null)
4179 >            throw new NullPointerException();
4180 >        return new MapReduceEntriesToIntTask<K,V>
4181 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4182 >             null, transformer, basis, reducer).invoke();
4183      }
4184  
4185 +
4186      /* ----------------Views -------------- */
4187  
4188      /**
4189       * Base class for views.
4190       */
4191 <    static abstract class CHMView<K, V> {
4192 <        final ConcurrentHashMap<K, V> map;
4193 <        CHMView(ConcurrentHashMap<K, V> map)  { this.map = map; }
4191 >    abstract static class CollectionView<K,V,E>
4192 >        implements Collection<E>, java.io.Serializable {
4193 >        private static final long serialVersionUID = 7249069246763182397L;
4194 >        final ConcurrentHashMap<K,V> map;
4195 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4196  
4197          /**
4198           * Returns the map backing this view.
# Line 3970 | Line 4201 | public class ConcurrentHashMap<K, V>
4201           */
4202          public ConcurrentHashMap<K,V> getMap() { return map; }
4203  
4204 <        public final int size()                 { return map.size(); }
4205 <        public final boolean isEmpty()          { return map.isEmpty(); }
4206 <        public final void clear()               { map.clear(); }
4204 >        /**
4205 >         * Removes all of the elements from this view, by removing all
4206 >         * the mappings from the map backing this view.
4207 >         */
4208 >        public final void clear()      { map.clear(); }
4209 >        public final int size()        { return map.size(); }
4210 >        public final boolean isEmpty() { return map.isEmpty(); }
4211  
4212          // implementations below rely on concrete classes supplying these
4213 <        abstract public Iterator<?> iterator();
4214 <        abstract public boolean contains(Object o);
4215 <        abstract public boolean remove(Object o);
4213 >        // abstract methods
4214 >        /**
4215 >         * Returns a "weakly consistent" iterator that will never
4216 >         * throw {@link ConcurrentModificationException}, and
4217 >         * guarantees to traverse elements as they existed upon
4218 >         * construction of the iterator, and may (but is not
4219 >         * guaranteed to) reflect any modifications subsequent to
4220 >         * construction.
4221 >         */
4222 >        public abstract Iterator<E> iterator();
4223 >        public abstract boolean contains(Object o);
4224 >        public abstract boolean remove(Object o);
4225  
4226          private static final String oomeMsg = "Required array size too large";
4227  
4228          public final Object[] toArray() {
4229              long sz = map.mappingCount();
4230 <            if (sz > (long)(MAX_ARRAY_SIZE))
4230 >            if (sz > MAX_ARRAY_SIZE)
4231                  throw new OutOfMemoryError(oomeMsg);
4232              int n = (int)sz;
4233              Object[] r = new Object[n];
4234              int i = 0;
4235 <            Iterator<?> it = iterator();
3992 <            while (it.hasNext()) {
4235 >            for (E e : this) {
4236                  if (i == n) {
4237                      if (n >= MAX_ARRAY_SIZE)
4238                          throw new OutOfMemoryError(oomeMsg);
# Line 3999 | Line 4242 | public class ConcurrentHashMap<K, V>
4242                          n += (n >>> 1) + 1;
4243                      r = Arrays.copyOf(r, n);
4244                  }
4245 <                r[i++] = it.next();
4245 >                r[i++] = e;
4246              }
4247              return (i == n) ? r : Arrays.copyOf(r, i);
4248          }
4249  
4250 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4250 >        @SuppressWarnings("unchecked")
4251 >        public final <T> T[] toArray(T[] a) {
4252              long sz = map.mappingCount();
4253 <            if (sz > (long)(MAX_ARRAY_SIZE))
4253 >            if (sz > MAX_ARRAY_SIZE)
4254                  throw new OutOfMemoryError(oomeMsg);
4255              int m = (int)sz;
4256              T[] r = (a.length >= m) ? a :
# Line 4014 | Line 4258 | public class ConcurrentHashMap<K, V>
4258                  .newInstance(a.getClass().getComponentType(), m);
4259              int n = r.length;
4260              int i = 0;
4261 <            Iterator<?> it = iterator();
4018 <            while (it.hasNext()) {
4261 >            for (E e : this) {
4262                  if (i == n) {
4263                      if (n >= MAX_ARRAY_SIZE)
4264                          throw new OutOfMemoryError(oomeMsg);
# Line 4025 | Line 4268 | public class ConcurrentHashMap<K, V>
4268                          n += (n >>> 1) + 1;
4269                      r = Arrays.copyOf(r, n);
4270                  }
4271 <                r[i++] = (T)it.next();
4271 >                r[i++] = (T)e;
4272              }
4273              if (a == r && i < n) {
4274                  r[i] = null; // null-terminate
# Line 4034 | Line 4277 | public class ConcurrentHashMap<K, V>
4277              return (i == n) ? r : Arrays.copyOf(r, i);
4278          }
4279  
4280 <        public final int hashCode() {
4281 <            int h = 0;
4282 <            for (Iterator<?> it = iterator(); it.hasNext();)
4283 <                h += it.next().hashCode();
4284 <            return h;
4285 <        }
4286 <
4280 >        /**
4281 >         * Returns a string representation of this collection.
4282 >         * The string representation consists of the string representations
4283 >         * of the collection's elements in the order they are returned by
4284 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4285 >         * Adjacent elements are separated by the characters {@code ", "}
4286 >         * (comma and space).  Elements are converted to strings as by
4287 >         * {@link String#valueOf(Object)}.
4288 >         *
4289 >         * @return a string representation of this collection
4290 >         */
4291          public final String toString() {
4292              StringBuilder sb = new StringBuilder();
4293              sb.append('[');
4294 <            Iterator<?> it = iterator();
4294 >            Iterator<E> it = iterator();
4295              if (it.hasNext()) {
4296                  for (;;) {
4297                      Object e = it.next();
# Line 4059 | Line 4306 | public class ConcurrentHashMap<K, V>
4306  
4307          public final boolean containsAll(Collection<?> c) {
4308              if (c != this) {
4309 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4063 <                    Object e = it.next();
4309 >                for (Object e : c) {
4310                      if (e == null || !contains(e))
4311                          return false;
4312                  }
# Line 4070 | Line 4316 | public class ConcurrentHashMap<K, V>
4316  
4317          public final boolean removeAll(Collection<?> c) {
4318              boolean modified = false;
4319 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4319 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4320                  if (c.contains(it.next())) {
4321                      it.remove();
4322                      modified = true;
# Line 4081 | Line 4327 | public class ConcurrentHashMap<K, V>
4327  
4328          public final boolean retainAll(Collection<?> c) {
4329              boolean modified = false;
4330 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4330 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4331                  if (!c.contains(it.next())) {
4332                      it.remove();
4333                      modified = true;
# Line 4095 | Line 4341 | public class ConcurrentHashMap<K, V>
4341      /**
4342       * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4343       * which additions may optionally be enabled by mapping to a
4344 <     * common value.  This class cannot be directly instantiated. See
4345 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4346 <     * {@link #newKeySet(int)}.
4344 >     * common value.  This class cannot be directly instantiated.
4345 >     * See {@link #keySet() keySet()},
4346 >     * {@link #keySet(Object) keySet(V)},
4347 >     * {@link #newKeySet() newKeySet()},
4348 >     * {@link #newKeySet(int) newKeySet(int)}.
4349 >     *
4350 >     * @since 1.8
4351       */
4352 <    public static class KeySetView<K,V> extends CHMView<K,V> implements Set<K>, java.io.Serializable {
4352 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4353 >        implements Set<K>, java.io.Serializable {
4354          private static final long serialVersionUID = 7249069246763182397L;
4355          private final V value;
4356 <        KeySetView(ConcurrentHashMap<K, V> map, V value) {  // non-public
4356 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4357              super(map);
4358              this.value = value;
4359          }
# Line 4112 | Line 4363 | public class ConcurrentHashMap<K, V>
4363           * or {@code null} if additions are not supported.
4364           *
4365           * @return the default mapped value for additions, or {@code null}
4366 <         * if not supported.
4366 >         * if not supported
4367           */
4368          public V getMappedValue() { return value; }
4369  
4370 <        // implement Set API
4371 <
4370 >        /**
4371 >         * {@inheritDoc}
4372 >         * @throws NullPointerException if the specified key is null
4373 >         */
4374          public boolean contains(Object o) { return map.containsKey(o); }
4122        public boolean remove(Object o)   { return map.remove(o) != null; }
4375  
4376          /**
4377 <         * Returns a "weakly consistent" iterator that will never
4378 <         * throw {@link ConcurrentModificationException}, and
4379 <         * guarantees to traverse elements as they existed upon
4380 <         * construction of the iterator, and may (but is not
4381 <         * guaranteed to) reflect any modifications subsequent to
4382 <         * construction.
4377 >         * Removes the key from this map view, by removing the key (and its
4378 >         * corresponding value) from the backing map.  This method does
4379 >         * nothing if the key is not in the map.
4380 >         *
4381 >         * @param  o the key to be removed from the backing map
4382 >         * @return {@code true} if the backing map contained the specified key
4383 >         * @throws NullPointerException if the specified key is null
4384 >         */
4385 >        public boolean remove(Object o) { return map.remove(o) != null; }
4386 >
4387 >        /**
4388 >         * @return an iterator over the keys of the backing map
4389 >         */
4390 >        public Iterator<K> iterator() {
4391 >            Node<K,V>[] t;
4392 >            ConcurrentHashMap<K,V> m = map;
4393 >            int f = (t = m.table) == null ? 0 : t.length;
4394 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4395 >        }
4396 >
4397 >        /**
4398 >         * Adds the specified key to this set view by mapping the key to
4399 >         * the default mapped value in the backing map, if defined.
4400           *
4401 <         * @return an iterator over the keys of this map
4401 >         * @param e key to be added
4402 >         * @return {@code true} if this set changed as a result of the call
4403 >         * @throws NullPointerException if the specified key is null
4404 >         * @throws UnsupportedOperationException if no default mapped value
4405 >         * for additions was provided
4406           */
4134        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4407          public boolean add(K e) {
4408              V v;
4409              if ((v = value) == null)
4410                  throw new UnsupportedOperationException();
4411 <            if (e == null)
4140 <                throw new NullPointerException();
4141 <            return map.internalPutIfAbsent(e, v) == null;
4411 >            return map.putVal(e, v, true) == null;
4412          }
4413 +
4414 +        /**
4415 +         * Adds all of the elements in the specified collection to this set,
4416 +         * as if by calling {@link #add} on each one.
4417 +         *
4418 +         * @param c the elements to be inserted into this set
4419 +         * @return {@code true} if this set changed as a result of the call
4420 +         * @throws NullPointerException if the collection or any of its
4421 +         * elements are {@code null}
4422 +         * @throws UnsupportedOperationException if no default mapped value
4423 +         * for additions was provided
4424 +         */
4425          public boolean addAll(Collection<? extends K> c) {
4426              boolean added = false;
4427              V v;
4428              if ((v = value) == null)
4429                  throw new UnsupportedOperationException();
4430              for (K e : c) {
4431 <                if (e == null)
4150 <                    throw new NullPointerException();
4151 <                if (map.internalPutIfAbsent(e, v) == null)
4431 >                if (map.putVal(e, v, true) == null)
4432                      added = true;
4433              }
4434              return added;
4435          }
4436 +
4437 +        public int hashCode() {
4438 +            int h = 0;
4439 +            for (K e : this)
4440 +                h += e.hashCode();
4441 +            return h;
4442 +        }
4443 +
4444          public boolean equals(Object o) {
4445              Set<?> c;
4446              return ((o instanceof Set) &&
# Line 4160 | Line 4448 | public class ConcurrentHashMap<K, V>
4448                       (containsAll(c) && c.containsAll(this))));
4449          }
4450  
4451 <        /**
4452 <         * Performs the given action for each key.
4453 <         *
4454 <         * @param action the action
4455 <         */
4456 <        public void forEach(Action<K> action) {
4169 <            ForkJoinTasks.forEachKey
4170 <                (map, action).invoke();
4451 >        public Spliterator<K> spliterator() {
4452 >            Node<K,V>[] t;
4453 >            ConcurrentHashMap<K,V> m = map;
4454 >            long n = m.sumCount();
4455 >            int f = (t = m.table) == null ? 0 : t.length;
4456 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4457          }
4458  
4459 <        /**
4460 <         * Performs the given action for each non-null transformation
4461 <         * of each key.
4462 <         *
4463 <         * @param transformer a function returning the transformation
4464 <         * for an element, or null of there is no transformation (in
4465 <         * which case the action is not applied).
4466 <         * @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();
4255 <        }
4256 <
4257 <        /**
4258 <         * Returns the result of accumulating the given transformation
4259 <         * of all keys using the given reducer to combine values, and
4260 <         * the given basis as an identity value.
4261 <         *
4262 <         * @param transformer a function returning the transformation
4263 <         * for an element
4264 <         * @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();
4459 >        public void forEach(Consumer<? super K> action) {
4460 >            if (action == null) throw new NullPointerException();
4461 >            Node<K,V>[] t;
4462 >            if ((t = map.table) != null) {
4463 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4464 >                for (Node<K,V> p; (p = it.advance()) != null; )
4465 >                    action.accept(p.key);
4466 >            }
4467          }
4275
4468      }
4469  
4470      /**
4471       * A view of a ConcurrentHashMap as a {@link Collection} of
4472       * values, in which additions are disabled. This class cannot be
4473 <     * 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.
4473 >     * directly instantiated. See {@link #values()}.
4474       */
4475 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4476 <        implements Collection<V> {
4477 <        ValuesView(ConcurrentHashMap<K, V> map)   { super(map); }
4478 <        public final boolean contains(Object o) { return map.containsValue(o); }
4475 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4476 >        implements Collection<V>, java.io.Serializable {
4477 >        private static final long serialVersionUID = 2249069246763182397L;
4478 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4479 >        public final boolean contains(Object o) {
4480 >            return map.containsValue(o);
4481 >        }
4482 >
4483          public final boolean remove(Object o) {
4484              if (o != null) {
4485 <                Iterator<V> it = new ValueIterator<K,V>(map);
4296 <                while (it.hasNext()) {
4485 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4486                      if (o.equals(it.next())) {
4487                          it.remove();
4488                          return true;
# Line 4303 | Line 4492 | public class ConcurrentHashMap<K, V>
4492              return false;
4493          }
4494  
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         */
4495          public final Iterator<V> iterator() {
4496 <            return new ValueIterator<K,V>(map);
4496 >            ConcurrentHashMap<K,V> m = map;
4497 >            Node<K,V>[] t;
4498 >            int f = (t = m.table) == null ? 0 : t.length;
4499 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4500          }
4501 +
4502          public final boolean add(V e) {
4503              throw new UnsupportedOperationException();
4504          }
# Line 4323 | Line 4506 | public class ConcurrentHashMap<K, V>
4506              throw new UnsupportedOperationException();
4507          }
4508  
4509 <        /**
4510 <         * Performs the given action for each value.
4511 <         *
4512 <         * @param action the action
4513 <         */
4514 <        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();
4509 >        public Spliterator<V> spliterator() {
4510 >            Node<K,V>[] t;
4511 >            ConcurrentHashMap<K,V> m = map;
4512 >            long n = m.sumCount();
4513 >            int f = (t = m.table) == null ? 0 : t.length;
4514 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4515          }
4516  
4517 <        /**
4518 <         * Returns the result of accumulating the given transformation
4519 <         * of all values using the given reducer to combine values, or
4520 <         * null if none.
4521 <         *
4522 <         * @param transformer a function returning the transformation
4523 <         * for an element, or null of there is no transformation (in
4524 <         * 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();
4396 <        }
4397 <
4398 <        /**
4399 <         * Returns the result of accumulating the given transformation
4400 <         * of all values using the given reducer to combine values,
4401 <         * and the given basis as an identity value.
4402 <         *
4403 <         * @param transformer a function returning the transformation
4404 <         * for an element
4405 <         * @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();
4517 >        public void forEach(Consumer<? super V> action) {
4518 >            if (action == null) throw new NullPointerException();
4519 >            Node<K,V>[] t;
4520 >            if ((t = map.table) != null) {
4521 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4522 >                for (Node<K,V> p; (p = it.advance()) != null; )
4523 >                    action.accept(p.val);
4524 >            }
4525          }
4454
4526      }
4527  
4528      /**
4529       * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4530       * entries.  This class cannot be directly instantiated. See
4531 <     * {@link #entrySet}.
4531 >     * {@link #entrySet()}.
4532       */
4533 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4534 <        implements Set<Map.Entry<K,V>> {
4535 <        EntrySetView(ConcurrentHashMap<K, V> map) { super(map); }
4536 <        public final boolean contains(Object o) {
4533 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4534 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4535 >        private static final long serialVersionUID = 2249069246763182397L;
4536 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4537 >
4538 >        public boolean contains(Object o) {
4539              Object k, v, r; Map.Entry<?,?> e;
4540              return ((o instanceof Map.Entry) &&
4541                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4470 | Line 4543 | public class ConcurrentHashMap<K, V>
4543                      (v = e.getValue()) != null &&
4544                      (v == r || v.equals(r)));
4545          }
4546 <        public final boolean remove(Object o) {
4546 >
4547 >        public boolean remove(Object o) {
4548              Object k, v; Map.Entry<?,?> e;
4549              return ((o instanceof Map.Entry) &&
4550                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4479 | Line 4553 | public class ConcurrentHashMap<K, V>
4553          }
4554  
4555          /**
4556 <         * 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
4556 >         * @return an iterator over the entries of the backing map
4557           */
4558 <        public final Iterator<Map.Entry<K,V>> iterator() {
4559 <            return new EntryIterator<K,V>(map);
4558 >        public Iterator<Map.Entry<K,V>> iterator() {
4559 >            ConcurrentHashMap<K,V> m = map;
4560 >            Node<K,V>[] t;
4561 >            int f = (t = m.table) == null ? 0 : t.length;
4562 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4563          }
4564  
4565 <        public final boolean add(Entry<K,V> e) {
4566 <            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;
4565 >        public boolean add(Entry<K,V> e) {
4566 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4567          }
4568 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4568 >
4569 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4570              boolean added = false;
4571              for (Entry<K,V> e : c) {
4572                  if (add(e))
# Line 4507 | Line 4574 | public class ConcurrentHashMap<K, V>
4574              }
4575              return added;
4576          }
4577 <        public boolean equals(Object o) {
4577 >
4578 >        public final int hashCode() {
4579 >            int h = 0;
4580 >            Node<K,V>[] t;
4581 >            if ((t = map.table) != null) {
4582 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4583 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4584 >                    h += p.hashCode();
4585 >                }
4586 >            }
4587 >            return h;
4588 >        }
4589 >
4590 >        public final boolean equals(Object o) {
4591              Set<?> c;
4592              return ((o instanceof Set) &&
4593                      ((c = (Set<?>)o) == this ||
4594                       (containsAll(c) && c.containsAll(this))));
4595          }
4596  
4597 <        /**
4598 <         * Performs the given action for each entry.
4599 <         *
4600 <         * @param action the action
4601 <         */
4602 <        public void forEach(Action<Map.Entry<K,V>> action) {
4523 <            ForkJoinTasks.forEachEntry
4524 <                (map, action).invoke();
4597 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4598 >            Node<K,V>[] t;
4599 >            ConcurrentHashMap<K,V> m = map;
4600 >            long n = m.sumCount();
4601 >            int f = (t = m.table) == null ? 0 : t.length;
4602 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4603          }
4604  
4605 <        /**
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) {
4605 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4606              if (action == null) throw new NullPointerException();
4607 <            return new ForEachMappingTask<K,V>(map, null, -1, null, action);
4608 <        }
4609 <
4610 <        /**
4611 <         * Returns a task that when invoked, performs the given
4612 <         * 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);
5144 <        }
5145 <
5146 <        /**
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) {
5156 <            if (action == null) throw new NullPointerException();
5157 <            return new ForEachEntryTask<K,V>(map, null, -1, null, action);
5158 <        }
5159 <
5160 <        /**
5161 <         * Returns a task that when invoked, perform the given action
5162 <         * 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);
4607 >            Node<K,V>[] t;
4608 >            if ((t = map.table) != null) {
4609 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4610 >                for (Node<K,V> p; (p = it.advance()) != null; )
4611 >                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
4612 >            }
4613          }
4614  
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        }
4615      }
4616  
4617      // -------------------------------------------------------
4618  
4619      /**
4620 <     * Base for FJ tasks for bulk operations. This adds a variant of
4621 <     * 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
4620 >     * Base class for bulk tasks. Repeats some fields and code from
4621 >     * class Traverser, because we need to subclass CountedCompleter.
4622       */
4623 <    @SuppressWarnings("serial") static abstract class BulkAction<K,V,R> extends BulkTask<K,V,R> {
4624 <        BulkAction<K,V,?> nextTask;
4625 <        BulkAction(ConcurrentHashMap<K,V> map, BulkTask<K,V,?> parent,
4626 <                   int batch, BulkAction<K,V,?> nextTask) {
4627 <            super(map, parent, batch);
4628 <            this.nextTask = nextTask;
4623 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4624 >        Node<K,V>[] tab;        // same as Traverser
4625 >        Node<K,V> next;
4626 >        int index;
4627 >        int baseIndex;
4628 >        int baseLimit;
4629 >        final int baseSize;
4630 >        int batch;              // split control
4631 >
4632 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4633 >            super(par);
4634 >            this.batch = b;
4635 >            this.index = this.baseIndex = i;
4636 >            if ((this.tab = t) == null)
4637 >                this.baseSize = this.baseLimit = 0;
4638 >            else if (par == null)
4639 >                this.baseSize = this.baseLimit = t.length;
4640 >            else {
4641 >                this.baseLimit = f;
4642 >                this.baseSize = par.baseSize;
4643 >            }
4644          }
4645  
4646          /**
4647 <         * 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.
4647 >         * Same as Traverser version
4648           */
4649 <        final void tryComplete(BulkAction<K,V,?> subtasks) {
4650 <            BulkTask<K,V,?> a = this, s = a;
4651 <            for (int c;;) {
4652 <                if ((c = a.pending) == 0) {
4653 <                    if ((a = (s = a).parent) == null) {
4654 <                        s.quietlyComplete();
4655 <                        break;
4656 <                    }
4657 <                }
4658 <                else if (a.casPending(c, c - 1)) {
4659 <                    if (subtasks != null && !inForkJoinPool()) {
4660 <                        while ((s = a.parent) != null)
4661 <                            a = s;
4662 <                        while (!a.isDone()) {
4663 <                            BulkAction<K,V,?> next = subtasks.nextTask;
4664 <                            if (subtasks.tryUnfork())
5459 <                                subtasks.exec();
5460 <                            if ((subtasks = next) == null)
5461 <                                break;
5462 <                        }
4649 >        final Node<K,V> advance() {
4650 >            Node<K,V> e;
4651 >            if ((e = next) != null)
4652 >                e = e.next;
4653 >            for (;;) {
4654 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4655 >                if (e != null)
4656 >                    return next = e;
4657 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4658 >                    (n = t.length) <= (i = index) || i < 0)
4659 >                    return next = null;
4660 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4661 >                    if (e instanceof ForwardingNode) {
4662 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4663 >                        e = null;
4664 >                        continue;
4665                      }
4666 <                    break;
4666 >                    else if (e instanceof TreeBin)
4667 >                        e = ((TreeBin<K,V>)e).first;
4668 >                    else
4669 >                        e = null;
4670                  }
4671 +                if ((index += baseSize) >= n)
4672 +                    index = ++baseIndex;    // visit upper slots if present
4673              }
4674          }
5468
4675      }
4676  
4677      /*
4678       * Task classes. Coded in a regular but ugly format/style to
4679       * simplify checks that each variant differs in the right way from
4680 <     * others.
4681 <     */
4682 <
4683 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4684 <        extends BulkAction<K,V,Void> {
4685 <        final Action<K> action;
4680 >     * others. The null screenings exist because compilers cannot tell
4681 >     * that we've already null-checked task arguments, so we force
4682 >     * simplest hoisted bypass to help avoid convoluted traps.
4683 >     */
4684 >    @SuppressWarnings("serial")
4685 >    static final class ForEachKeyTask<K,V>
4686 >        extends BulkTask<K,V,Void> {
4687 >        final Consumer<? super K> action;
4688          ForEachKeyTask
4689 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4690 <             ForEachKeyTask<K,V> nextTask,
4691 <             Action<K> action) {
5484 <            super(m, p, b, nextTask);
4689 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4690 >             Consumer<? super K> action) {
4691 >            super(p, b, i, f, t);
4692              this.action = action;
4693          }
4694 <        @SuppressWarnings("unchecked") public final boolean exec() {
4695 <            final Action<K> action = this.action;
4696 <            if (action == null)
4697 <                return abortOnNullFunction();
4698 <            ForEachKeyTask<K,V> subtasks = null;
4699 <            try {
4700 <                int b = batch(), c;
4701 <                while (b > 1 && baseIndex != baseLimit) {
4702 <                    do {} while (!casPending(c = pending, c+1));
4703 <                    (subtasks = new ForEachKeyTask<K,V>
4704 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4705 <                }
4706 <                while (advance() != null)
5500 <                    action.apply((K)nextKey);
5501 <            } catch (Throwable ex) {
5502 <                return tryCompleteComputation(ex);
4694 >        public final void compute() {
4695 >            final Consumer<? super K> action;
4696 >            if ((action = this.action) != null) {
4697 >                for (int i = baseIndex, f, h; batch > 0 &&
4698 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4699 >                    addToPendingCount(1);
4700 >                    new ForEachKeyTask<K,V>
4701 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4702 >                         action).fork();
4703 >                }
4704 >                for (Node<K,V> p; (p = advance()) != null;)
4705 >                    action.accept(p.key);
4706 >                propagateCompletion();
4707              }
5504            tryComplete(subtasks);
5505            return false;
4708          }
4709      }
4710  
4711 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4712 <        extends BulkAction<K,V,Void> {
4713 <        final Action<V> action;
4711 >    @SuppressWarnings("serial")
4712 >    static final class ForEachValueTask<K,V>
4713 >        extends BulkTask<K,V,Void> {
4714 >        final Consumer<? super V> action;
4715          ForEachValueTask
4716 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4717 <             ForEachValueTask<K,V> nextTask,
4718 <             Action<V> action) {
5516 <            super(m, p, b, nextTask);
4716 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4717 >             Consumer<? super V> action) {
4718 >            super(p, b, i, f, t);
4719              this.action = action;
4720          }
4721 <        @SuppressWarnings("unchecked") public final boolean exec() {
4722 <            final Action<V> action = this.action;
4723 <            if (action == null)
4724 <                return abortOnNullFunction();
4725 <            ForEachValueTask<K,V> subtasks = null;
4726 <            try {
4727 <                int b = batch(), c;
4728 <                while (b > 1 && baseIndex != baseLimit) {
4729 <                    do {} while (!casPending(c = pending, c+1));
4730 <                    (subtasks = new ForEachValueTask<K,V>
4731 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4732 <                }
4733 <                Object v;
5532 <                while ((v = advance()) != null)
5533 <                    action.apply((V)v);
5534 <            } catch (Throwable ex) {
5535 <                return tryCompleteComputation(ex);
4721 >        public final void compute() {
4722 >            final Consumer<? super V> action;
4723 >            if ((action = this.action) != null) {
4724 >                for (int i = baseIndex, f, h; batch > 0 &&
4725 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4726 >                    addToPendingCount(1);
4727 >                    new ForEachValueTask<K,V>
4728 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4729 >                         action).fork();
4730 >                }
4731 >                for (Node<K,V> p; (p = advance()) != null;)
4732 >                    action.accept(p.val);
4733 >                propagateCompletion();
4734              }
5537            tryComplete(subtasks);
5538            return false;
4735          }
4736      }
4737  
4738 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4739 <        extends BulkAction<K,V,Void> {
4740 <        final Action<Entry<K,V>> action;
4738 >    @SuppressWarnings("serial")
4739 >    static final class ForEachEntryTask<K,V>
4740 >        extends BulkTask<K,V,Void> {
4741 >        final Consumer<? super Entry<K,V>> action;
4742          ForEachEntryTask
4743 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4744 <             ForEachEntryTask<K,V> nextTask,
4745 <             Action<Entry<K,V>> action) {
5549 <            super(m, p, b, nextTask);
4743 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4744 >             Consumer<? super Entry<K,V>> action) {
4745 >            super(p, b, i, f, t);
4746              this.action = action;
4747          }
4748 <        @SuppressWarnings("unchecked") public final boolean exec() {
4749 <            final Action<Entry<K,V>> action = this.action;
4750 <            if (action == null)
4751 <                return abortOnNullFunction();
4752 <            ForEachEntryTask<K,V> subtasks = null;
4753 <            try {
4754 <                int b = batch(), c;
4755 <                while (b > 1 && baseIndex != baseLimit) {
4756 <                    do {} while (!casPending(c = pending, c+1));
4757 <                    (subtasks = new ForEachEntryTask<K,V>
4758 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4759 <                }
4760 <                Object v;
5565 <                while ((v = advance()) != null)
5566 <                    action.apply(entryFor((K)nextKey, (V)v));
5567 <            } catch (Throwable ex) {
5568 <                return tryCompleteComputation(ex);
4748 >        public final void compute() {
4749 >            final Consumer<? super Entry<K,V>> action;
4750 >            if ((action = this.action) != null) {
4751 >                for (int i = baseIndex, f, h; batch > 0 &&
4752 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4753 >                    addToPendingCount(1);
4754 >                    new ForEachEntryTask<K,V>
4755 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4756 >                         action).fork();
4757 >                }
4758 >                for (Node<K,V> p; (p = advance()) != null; )
4759 >                    action.accept(p);
4760 >                propagateCompletion();
4761              }
5570            tryComplete(subtasks);
5571            return false;
4762          }
4763      }
4764  
4765 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4766 <        extends BulkAction<K,V,Void> {
4767 <        final BiAction<K,V> action;
4765 >    @SuppressWarnings("serial")
4766 >    static final class ForEachMappingTask<K,V>
4767 >        extends BulkTask<K,V,Void> {
4768 >        final BiConsumer<? super K, ? super V> action;
4769          ForEachMappingTask
4770 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4771 <             ForEachMappingTask<K,V> nextTask,
4772 <             BiAction<K,V> action) {
5582 <            super(m, p, b, nextTask);
4770 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4771 >             BiConsumer<? super K,? super V> action) {
4772 >            super(p, b, i, f, t);
4773              this.action = action;
4774          }
4775 <        @SuppressWarnings("unchecked") public final boolean exec() {
4776 <            final BiAction<K,V> action = this.action;
4777 <            if (action == null)
4778 <                return abortOnNullFunction();
4779 <            ForEachMappingTask<K,V> subtasks = null;
4780 <            try {
4781 <                int b = batch(), c;
4782 <                while (b > 1 && baseIndex != baseLimit) {
4783 <                    do {} while (!casPending(c = pending, c+1));
4784 <                    (subtasks = new ForEachMappingTask<K,V>
4785 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4786 <                }
4787 <                Object v;
5598 <                while ((v = advance()) != null)
5599 <                    action.apply((K)nextKey, (V)v);
5600 <            } catch (Throwable ex) {
5601 <                return tryCompleteComputation(ex);
4775 >        public final void compute() {
4776 >            final BiConsumer<? super K, ? super V> action;
4777 >            if ((action = this.action) != null) {
4778 >                for (int i = baseIndex, f, h; batch > 0 &&
4779 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4780 >                    addToPendingCount(1);
4781 >                    new ForEachMappingTask<K,V>
4782 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4783 >                         action).fork();
4784 >                }
4785 >                for (Node<K,V> p; (p = advance()) != null; )
4786 >                    action.accept(p.key, p.val);
4787 >                propagateCompletion();
4788              }
5603            tryComplete(subtasks);
5604            return false;
4789          }
4790      }
4791  
4792 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4793 <        extends BulkAction<K,V,Void> {
4794 <        final Fun<? super K, ? extends U> transformer;
4795 <        final Action<U> action;
4792 >    @SuppressWarnings("serial")
4793 >    static final class ForEachTransformedKeyTask<K,V,U>
4794 >        extends BulkTask<K,V,Void> {
4795 >        final Function<? super K, ? extends U> transformer;
4796 >        final Consumer<? super U> action;
4797          ForEachTransformedKeyTask
4798 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4799 <             ForEachTransformedKeyTask<K,V,U> nextTask,
4800 <             Fun<? super K, ? extends U> transformer,
4801 <             Action<U> action) {
4802 <            super(m, p, b, nextTask);
4803 <            this.transformer = transformer;
4804 <            this.action = action;
4805 <
4806 <        }
4807 <        @SuppressWarnings("unchecked") public final boolean exec() {
4808 <            final Fun<? super K, ? extends U> transformer =
4809 <                this.transformer;
4810 <            final Action<U> action = this.action;
4811 <            if (transformer == null || action == null)
4812 <                return abortOnNullFunction();
4813 <            ForEachTransformedKeyTask<K,V,U> subtasks = null;
4814 <            try {
4815 <                int b = batch(), c;
4816 <                while (b > 1 && baseIndex != baseLimit) {
4817 <                    do {} while (!casPending(c = pending, c+1));
4818 <                    (subtasks = new ForEachTransformedKeyTask<K,V,U>
4819 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
4820 <                }
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);
4798 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4799 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
4800 >            super(p, b, i, f, t);
4801 >            this.transformer = transformer; this.action = action;
4802 >        }
4803 >        public final void compute() {
4804 >            final Function<? super K, ? extends U> transformer;
4805 >            final Consumer<? super U> action;
4806 >            if ((transformer = this.transformer) != null &&
4807 >                (action = this.action) != null) {
4808 >                for (int i = baseIndex, f, h; batch > 0 &&
4809 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4810 >                    addToPendingCount(1);
4811 >                    new ForEachTransformedKeyTask<K,V,U>
4812 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4813 >                         transformer, action).fork();
4814 >                }
4815 >                for (Node<K,V> p; (p = advance()) != null; ) {
4816 >                    U u;
4817 >                    if ((u = transformer.apply(p.key)) != null)
4818 >                        action.accept(u);
4819 >                }
4820 >                propagateCompletion();
4821              }
5644            tryComplete(subtasks);
5645            return false;
4822          }
4823      }
4824  
4825 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
4826 <        extends BulkAction<K,V,Void> {
4827 <        final Fun<? super V, ? extends U> transformer;
4828 <        final Action<U> action;
4825 >    @SuppressWarnings("serial")
4826 >    static final class ForEachTransformedValueTask<K,V,U>
4827 >        extends BulkTask<K,V,Void> {
4828 >        final Function<? super V, ? extends U> transformer;
4829 >        final Consumer<? super U> action;
4830          ForEachTransformedValueTask
4831 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4832 <             ForEachTransformedValueTask<K,V,U> nextTask,
4833 <             Fun<? super V, ? extends U> transformer,
4834 <             Action<U> action) {
4835 <            super(m, p, b, nextTask);
4836 <            this.transformer = transformer;
4837 <            this.action = action;
4838 <
4839 <        }
4840 <        @SuppressWarnings("unchecked") public final boolean exec() {
4841 <            final Fun<? super V, ? extends U> transformer =
4842 <                this.transformer;
4843 <            final Action<U> action = this.action;
4844 <            if (transformer == null || action == null)
4845 <                return abortOnNullFunction();
4846 <            ForEachTransformedValueTask<K,V,U> subtasks = null;
4847 <            try {
4848 <                int b = batch(), c;
4849 <                while (b > 1 && baseIndex != baseLimit) {
4850 <                    do {} while (!casPending(c = pending, c+1));
4851 <                    (subtasks = new ForEachTransformedValueTask<K,V,U>
4852 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
4853 <                }
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);
4831 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4832 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
4833 >            super(p, b, i, f, t);
4834 >            this.transformer = transformer; this.action = action;
4835 >        }
4836 >        public final void compute() {
4837 >            final Function<? super V, ? extends U> transformer;
4838 >            final Consumer<? super U> action;
4839 >            if ((transformer = this.transformer) != null &&
4840 >                (action = this.action) != null) {
4841 >                for (int i = baseIndex, f, h; batch > 0 &&
4842 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4843 >                    addToPendingCount(1);
4844 >                    new ForEachTransformedValueTask<K,V,U>
4845 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4846 >                         transformer, action).fork();
4847 >                }
4848 >                for (Node<K,V> p; (p = advance()) != null; ) {
4849 >                    U u;
4850 >                    if ((u = transformer.apply(p.val)) != null)
4851 >                        action.accept(u);
4852 >                }
4853 >                propagateCompletion();
4854              }
5685            tryComplete(subtasks);
5686            return false;
4855          }
4856      }
4857  
4858 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
4859 <        extends BulkAction<K,V,Void> {
4860 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
4861 <        final Action<U> action;
4858 >    @SuppressWarnings("serial")
4859 >    static final class ForEachTransformedEntryTask<K,V,U>
4860 >        extends BulkTask<K,V,Void> {
4861 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
4862 >        final Consumer<? super U> action;
4863          ForEachTransformedEntryTask
4864 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4865 <             ForEachTransformedEntryTask<K,V,U> nextTask,
4866 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4867 <             Action<U> action) {
4868 <            super(m, p, b, nextTask);
4869 <            this.transformer = transformer;
4870 <            this.action = action;
4871 <
4872 <        }
4873 <        @SuppressWarnings("unchecked") public final boolean exec() {
4874 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
4875 <                this.transformer;
4876 <            final Action<U> action = this.action;
4877 <            if (transformer == null || action == null)
4878 <                return abortOnNullFunction();
4879 <            ForEachTransformedEntryTask<K,V,U> subtasks = null;
4880 <            try {
4881 <                int b = batch(), c;
4882 <                while (b > 1 && baseIndex != baseLimit) {
4883 <                    do {} while (!casPending(c = pending, c+1));
4884 <                    (subtasks = new ForEachTransformedEntryTask<K,V,U>
4885 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
4886 <                }
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);
4864 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4865 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
4866 >            super(p, b, i, f, t);
4867 >            this.transformer = transformer; this.action = action;
4868 >        }
4869 >        public final void compute() {
4870 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
4871 >            final Consumer<? super U> action;
4872 >            if ((transformer = this.transformer) != null &&
4873 >                (action = this.action) != null) {
4874 >                for (int i = baseIndex, f, h; batch > 0 &&
4875 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4876 >                    addToPendingCount(1);
4877 >                    new ForEachTransformedEntryTask<K,V,U>
4878 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4879 >                         transformer, action).fork();
4880 >                }
4881 >                for (Node<K,V> p; (p = advance()) != null; ) {
4882 >                    U u;
4883 >                    if ((u = transformer.apply(p)) != null)
4884 >                        action.accept(u);
4885 >                }
4886 >                propagateCompletion();
4887              }
5726            tryComplete(subtasks);
5727            return false;
4888          }
4889      }
4890  
4891 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
4892 <        extends BulkAction<K,V,Void> {
4893 <        final BiFun<? super K, ? super V, ? extends U> transformer;
4894 <        final Action<U> action;
4891 >    @SuppressWarnings("serial")
4892 >    static final class ForEachTransformedMappingTask<K,V,U>
4893 >        extends BulkTask<K,V,Void> {
4894 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
4895 >        final Consumer<? super U> action;
4896          ForEachTransformedMappingTask
4897 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4898 <             ForEachTransformedMappingTask<K,V,U> nextTask,
4899 <             BiFun<? super K, ? super V, ? extends U> transformer,
4900 <             Action<U> action) {
4901 <            super(m, p, b, nextTask);
4902 <            this.transformer = transformer;
4903 <            this.action = action;
4904 <
4905 <        }
4906 <        @SuppressWarnings("unchecked") public final boolean exec() {
4907 <            final BiFun<? super K, ? super V, ? extends U> transformer =
4908 <                this.transformer;
4909 <            final Action<U> action = this.action;
4910 <            if (transformer == null || action == null)
4911 <                return abortOnNullFunction();
4912 <            ForEachTransformedMappingTask<K,V,U> subtasks = null;
4913 <            try {
4914 <                int b = batch(), c;
4915 <                while (b > 1 && baseIndex != baseLimit) {
4916 <                    do {} while (!casPending(c = pending, c+1));
4917 <                    (subtasks = new ForEachTransformedMappingTask<K,V,U>
4918 <                     (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);
4897 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4898 >             BiFunction<? super K, ? super V, ? extends U> transformer,
4899 >             Consumer<? super U> action) {
4900 >            super(p, b, i, f, t);
4901 >            this.transformer = transformer; this.action = action;
4902 >        }
4903 >        public final void compute() {
4904 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
4905 >            final Consumer<? super U> action;
4906 >            if ((transformer = this.transformer) != null &&
4907 >                (action = this.action) != null) {
4908 >                for (int i = baseIndex, f, h; batch > 0 &&
4909 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4910 >                    addToPendingCount(1);
4911 >                    new ForEachTransformedMappingTask<K,V,U>
4912 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4913 >                         transformer, action).fork();
4914 >                }
4915 >                for (Node<K,V> p; (p = advance()) != null; ) {
4916 >                    U u;
4917 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4918 >                        action.accept(u);
4919                  }
4920 <            } catch (Throwable ex) {
5765 <                return tryCompleteComputation(ex);
4920 >                propagateCompletion();
4921              }
5767            tryComplete(subtasks);
5768            return false;
4922          }
4923      }
4924  
4925 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
4926 <        extends BulkAction<K,V,U> {
4927 <        final Fun<? super K, ? extends U> searchFunction;
4925 >    @SuppressWarnings("serial")
4926 >    static final class SearchKeysTask<K,V,U>
4927 >        extends BulkTask<K,V,U> {
4928 >        final Function<? super K, ? extends U> searchFunction;
4929          final AtomicReference<U> result;
4930          SearchKeysTask
4931 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4932 <             SearchKeysTask<K,V,U> nextTask,
5779 <             Fun<? super K, ? extends U> searchFunction,
4931 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4932 >             Function<? super K, ? extends U> searchFunction,
4933               AtomicReference<U> result) {
4934 <            super(m, p, b, nextTask);
4934 >            super(p, b, i, f, t);
4935              this.searchFunction = searchFunction; this.result = result;
4936          }
4937 <        @SuppressWarnings("unchecked") public final boolean exec() {
4938 <            AtomicReference<U> result = this.result;
4939 <            final Fun<? super K, ? extends U> searchFunction =
4940 <                this.searchFunction;
4941 <            if (searchFunction == null || result == null)
4942 <                return abortOnNullFunction();
4943 <            SearchKeysTask<K,V,U> subtasks = null;
4944 <            try {
4945 <                int b = batch(), c;
4946 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4947 <                    do {} while (!casPending(c = pending, c+1));
4948 <                    (subtasks = new SearchKeysTask<K,V,U>
4949 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
4950 <                }
4951 <                U u;
4952 <                while (result.get() == null && advance() != null) {
4953 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
4937 >        public final U getRawResult() { return result.get(); }
4938 >        public final void compute() {
4939 >            final Function<? super K, ? extends U> searchFunction;
4940 >            final AtomicReference<U> result;
4941 >            if ((searchFunction = this.searchFunction) != null &&
4942 >                (result = this.result) != null) {
4943 >                for (int i = baseIndex, f, h; batch > 0 &&
4944 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4945 >                    if (result.get() != null)
4946 >                        return;
4947 >                    addToPendingCount(1);
4948 >                    new SearchKeysTask<K,V,U>
4949 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4950 >                         searchFunction, result).fork();
4951 >                }
4952 >                while (result.get() == null) {
4953 >                    U u;
4954 >                    Node<K,V> p;
4955 >                    if ((p = advance()) == null) {
4956 >                        propagateCompletion();
4957 >                        break;
4958 >                    }
4959 >                    if ((u = searchFunction.apply(p.key)) != null) {
4960                          if (result.compareAndSet(null, u))
4961 <                            tryCompleteComputation(null);
4961 >                            quietlyCompleteRoot();
4962                          break;
4963                      }
4964                  }
5806            } catch (Throwable ex) {
5807                return tryCompleteComputation(ex);
4965              }
5809            tryComplete(subtasks);
5810            return false;
4966          }
5812        public final U getRawResult() { return result.get(); }
4967      }
4968  
4969 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
4970 <        extends BulkAction<K,V,U> {
4971 <        final Fun<? super V, ? extends U> searchFunction;
4969 >    @SuppressWarnings("serial")
4970 >    static final class SearchValuesTask<K,V,U>
4971 >        extends BulkTask<K,V,U> {
4972 >        final Function<? super V, ? extends U> searchFunction;
4973          final AtomicReference<U> result;
4974          SearchValuesTask
4975 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4976 <             SearchValuesTask<K,V,U> nextTask,
5822 <             Fun<? super V, ? extends U> searchFunction,
4975 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4976 >             Function<? super V, ? extends U> searchFunction,
4977               AtomicReference<U> result) {
4978 <            super(m, p, b, nextTask);
4978 >            super(p, b, i, f, t);
4979              this.searchFunction = searchFunction; this.result = result;
4980          }
4981 <        @SuppressWarnings("unchecked") public final boolean exec() {
4982 <            AtomicReference<U> result = this.result;
4983 <            final Fun<? super V, ? extends U> searchFunction =
4984 <                this.searchFunction;
4985 <            if (searchFunction == null || result == null)
4986 <                return abortOnNullFunction();
4987 <            SearchValuesTask<K,V,U> subtasks = null;
4988 <            try {
4989 <                int b = batch(), c;
4990 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4991 <                    do {} while (!casPending(c = pending, c+1));
4992 <                    (subtasks = new SearchValuesTask<K,V,U>
4993 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
4994 <                }
4995 <                Object v; U u;
4996 <                while (result.get() == null && (v = advance()) != null) {
4997 <                    if ((u = searchFunction.apply((V)v)) != null) {
4981 >        public final U getRawResult() { return result.get(); }
4982 >        public final void compute() {
4983 >            final Function<? super V, ? extends U> searchFunction;
4984 >            final AtomicReference<U> result;
4985 >            if ((searchFunction = this.searchFunction) != null &&
4986 >                (result = this.result) != null) {
4987 >                for (int i = baseIndex, f, h; batch > 0 &&
4988 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4989 >                    if (result.get() != null)
4990 >                        return;
4991 >                    addToPendingCount(1);
4992 >                    new SearchValuesTask<K,V,U>
4993 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4994 >                         searchFunction, result).fork();
4995 >                }
4996 >                while (result.get() == null) {
4997 >                    U u;
4998 >                    Node<K,V> p;
4999 >                    if ((p = advance()) == null) {
5000 >                        propagateCompletion();
5001 >                        break;
5002 >                    }
5003 >                    if ((u = searchFunction.apply(p.val)) != null) {
5004                          if (result.compareAndSet(null, u))
5005 <                            tryCompleteComputation(null);
5005 >                            quietlyCompleteRoot();
5006                          break;
5007                      }
5008                  }
5849            } catch (Throwable ex) {
5850                return tryCompleteComputation(ex);
5009              }
5852            tryComplete(subtasks);
5853            return false;
5010          }
5855        public final U getRawResult() { return result.get(); }
5011      }
5012  
5013 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5014 <        extends BulkAction<K,V,U> {
5015 <        final Fun<Entry<K,V>, ? extends U> searchFunction;
5013 >    @SuppressWarnings("serial")
5014 >    static final class SearchEntriesTask<K,V,U>
5015 >        extends BulkTask<K,V,U> {
5016 >        final Function<Entry<K,V>, ? extends U> searchFunction;
5017          final AtomicReference<U> result;
5018          SearchEntriesTask
5019 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5020 <             SearchEntriesTask<K,V,U> nextTask,
5865 <             Fun<Entry<K,V>, ? extends U> searchFunction,
5019 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5020 >             Function<Entry<K,V>, ? extends U> searchFunction,
5021               AtomicReference<U> result) {
5022 <            super(m, p, b, nextTask);
5022 >            super(p, b, i, f, t);
5023              this.searchFunction = searchFunction; this.result = result;
5024          }
5025 <        @SuppressWarnings("unchecked") public final boolean exec() {
5026 <            AtomicReference<U> result = this.result;
5027 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
5028 <                this.searchFunction;
5029 <            if (searchFunction == null || result == null)
5030 <                return abortOnNullFunction();
5031 <            SearchEntriesTask<K,V,U> subtasks = null;
5032 <            try {
5033 <                int b = batch(), c;
5034 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5035 <                    do {} while (!casPending(c = pending, c+1));
5036 <                    (subtasks = new SearchEntriesTask<K,V,U>
5037 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5038 <                }
5039 <                Object v; U u;
5040 <                while (result.get() == null && (v = advance()) != null) {
5041 <                    if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
5042 <                        if (result.compareAndSet(null, u))
5043 <                            tryCompleteComputation(null);
5025 >        public final U getRawResult() { return result.get(); }
5026 >        public final void compute() {
5027 >            final Function<Entry<K,V>, ? extends U> searchFunction;
5028 >            final AtomicReference<U> result;
5029 >            if ((searchFunction = this.searchFunction) != null &&
5030 >                (result = this.result) != null) {
5031 >                for (int i = baseIndex, f, h; batch > 0 &&
5032 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5033 >                    if (result.get() != null)
5034 >                        return;
5035 >                    addToPendingCount(1);
5036 >                    new SearchEntriesTask<K,V,U>
5037 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5038 >                         searchFunction, result).fork();
5039 >                }
5040 >                while (result.get() == null) {
5041 >                    U u;
5042 >                    Node<K,V> p;
5043 >                    if ((p = advance()) == null) {
5044 >                        propagateCompletion();
5045                          break;
5046                      }
5047 +                    if ((u = searchFunction.apply(p)) != null) {
5048 +                        if (result.compareAndSet(null, u))
5049 +                            quietlyCompleteRoot();
5050 +                        return;
5051 +                    }
5052                  }
5892            } catch (Throwable ex) {
5893                return tryCompleteComputation(ex);
5053              }
5895            tryComplete(subtasks);
5896            return false;
5054          }
5898        public final U getRawResult() { return result.get(); }
5055      }
5056  
5057 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5058 <        extends BulkAction<K,V,U> {
5059 <        final BiFun<? super K, ? super V, ? extends U> searchFunction;
5057 >    @SuppressWarnings("serial")
5058 >    static final class SearchMappingsTask<K,V,U>
5059 >        extends BulkTask<K,V,U> {
5060 >        final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5061          final AtomicReference<U> result;
5062          SearchMappingsTask
5063 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5064 <             SearchMappingsTask<K,V,U> nextTask,
5908 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
5063 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5064 >             BiFunction<? super K, ? super V, ? extends U> searchFunction,
5065               AtomicReference<U> result) {
5066 <            super(m, p, b, nextTask);
5066 >            super(p, b, i, f, t);
5067              this.searchFunction = searchFunction; this.result = result;
5068          }
5069 <        @SuppressWarnings("unchecked") public final boolean exec() {
5070 <            AtomicReference<U> result = this.result;
5071 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
5072 <                this.searchFunction;
5073 <            if (searchFunction == null || result == null)
5074 <                return abortOnNullFunction();
5075 <            SearchMappingsTask<K,V,U> subtasks = null;
5076 <            try {
5077 <                int b = batch(), c;
5078 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5079 <                    do {} while (!casPending(c = pending, c+1));
5080 <                    (subtasks = new SearchMappingsTask<K,V,U>
5081 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5082 <                }
5083 <                Object v; U u;
5084 <                while (result.get() == null && (v = advance()) != null) {
5085 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5069 >        public final U getRawResult() { return result.get(); }
5070 >        public final void compute() {
5071 >            final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5072 >            final AtomicReference<U> result;
5073 >            if ((searchFunction = this.searchFunction) != null &&
5074 >                (result = this.result) != null) {
5075 >                for (int i = baseIndex, f, h; batch > 0 &&
5076 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5077 >                    if (result.get() != null)
5078 >                        return;
5079 >                    addToPendingCount(1);
5080 >                    new SearchMappingsTask<K,V,U>
5081 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5082 >                         searchFunction, result).fork();
5083 >                }
5084 >                while (result.get() == null) {
5085 >                    U u;
5086 >                    Node<K,V> p;
5087 >                    if ((p = advance()) == null) {
5088 >                        propagateCompletion();
5089 >                        break;
5090 >                    }
5091 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5092                          if (result.compareAndSet(null, u))
5093 <                            tryCompleteComputation(null);
5093 >                            quietlyCompleteRoot();
5094                          break;
5095                      }
5096                  }
5935            } catch (Throwable ex) {
5936                return tryCompleteComputation(ex);
5097              }
5938            tryComplete(subtasks);
5939            return false;
5098          }
5941        public final U getRawResult() { return result.get(); }
5099      }
5100  
5101 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5101 >    @SuppressWarnings("serial")
5102 >    static final class ReduceKeysTask<K,V>
5103          extends BulkTask<K,V,K> {
5104 <        final BiFun<? super K, ? super K, ? extends K> reducer;
5104 >        final BiFunction<? super K, ? super K, ? extends K> reducer;
5105          K result;
5106          ReduceKeysTask<K,V> rights, nextRight;
5107          ReduceKeysTask
5108 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5108 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5109               ReduceKeysTask<K,V> nextRight,
5110 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5111 <            super(m, p, b); this.nextRight = nextRight;
5110 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
5111 >            super(p, b, i, f, t); this.nextRight = nextRight;
5112              this.reducer = reducer;
5113          }
5114 <        @SuppressWarnings("unchecked") public final boolean exec() {
5115 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5116 <                this.reducer;
5117 <            if (reducer == null)
5118 <                return abortOnNullFunction();
5119 <            try {
5120 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5963 <                    do {} while (!casPending(c = pending, c+1));
5114 >        public final K getRawResult() { return result; }
5115 >        public final void compute() {
5116 >            final BiFunction<? super K, ? super K, ? extends K> reducer;
5117 >            if ((reducer = this.reducer) != null) {
5118 >                for (int i = baseIndex, f, h; batch > 0 &&
5119 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5120 >                    addToPendingCount(1);
5121                      (rights = new ReduceKeysTask<K,V>
5122 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5122 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5123 >                      rights, reducer)).fork();
5124                  }
5125                  K r = null;
5126 <                while (advance() != null) {
5127 <                    K u = (K)nextKey;
5128 <                    r = (r == null) ? u : reducer.apply(r, u);
5126 >                for (Node<K,V> p; (p = advance()) != null; ) {
5127 >                    K u = p.key;
5128 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5129                  }
5130                  result = r;
5131 <                for (ReduceKeysTask<K,V> t = this, s;;) {
5132 <                    int c; BulkTask<K,V,?> par; K tr, sr;
5133 <                    if ((c = t.pending) == 0) {
5134 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5135 <                            if ((sr = s.result) != null)
5136 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5137 <                        }
5138 <                        if ((par = t.parent) == null ||
5139 <                            !(par instanceof ReduceKeysTask)) {
5140 <                            t.quietlyComplete();
5141 <                            break;
5984 <                        }
5985 <                        t = (ReduceKeysTask<K,V>)par;
5131 >                CountedCompleter<?> c;
5132 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5133 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5134 >                        t = (ReduceKeysTask<K,V>)c,
5135 >                        s = t.rights;
5136 >                    while (s != null) {
5137 >                        K tr, sr;
5138 >                        if ((sr = s.result) != null)
5139 >                            t.result = (((tr = t.result) == null) ? sr :
5140 >                                        reducer.apply(tr, sr));
5141 >                        s = t.rights = s.nextRight;
5142                      }
5987                    else if (t.casPending(c, c - 1))
5988                        break;
5143                  }
5990            } catch (Throwable ex) {
5991                return tryCompleteComputation(ex);
5144              }
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;
5145          }
6002        public final K getRawResult() { return result; }
5146      }
5147  
5148 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5148 >    @SuppressWarnings("serial")
5149 >    static final class ReduceValuesTask<K,V>
5150          extends BulkTask<K,V,V> {
5151 <        final BiFun<? super V, ? super V, ? extends V> reducer;
5151 >        final BiFunction<? super V, ? super V, ? extends V> reducer;
5152          V result;
5153          ReduceValuesTask<K,V> rights, nextRight;
5154          ReduceValuesTask
5155 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5155 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5156               ReduceValuesTask<K,V> nextRight,
5157 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5158 <            super(m, p, b); this.nextRight = nextRight;
5157 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
5158 >            super(p, b, i, f, t); this.nextRight = nextRight;
5159              this.reducer = reducer;
5160          }
5161 <        @SuppressWarnings("unchecked") public final boolean exec() {
5162 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5163 <                this.reducer;
5164 <            if (reducer == null)
5165 <                return abortOnNullFunction();
5166 <            try {
5167 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6024 <                    do {} while (!casPending(c = pending, c+1));
5161 >        public final V getRawResult() { return result; }
5162 >        public final void compute() {
5163 >            final BiFunction<? super V, ? super V, ? extends V> reducer;
5164 >            if ((reducer = this.reducer) != null) {
5165 >                for (int i = baseIndex, f, h; batch > 0 &&
5166 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5167 >                    addToPendingCount(1);
5168                      (rights = new ReduceValuesTask<K,V>
5169 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5169 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5170 >                      rights, reducer)).fork();
5171                  }
5172                  V r = null;
5173 <                Object v;
5174 <                while ((v = advance()) != null) {
5175 <                    V u = (V)v;
6032 <                    r = (r == null) ? u : reducer.apply(r, u);
5173 >                for (Node<K,V> p; (p = advance()) != null; ) {
5174 >                    V v = p.val;
5175 >                    r = (r == null) ? v : reducer.apply(r, v);
5176                  }
5177                  result = r;
5178 <                for (ReduceValuesTask<K,V> t = this, s;;) {
5179 <                    int c; BulkTask<K,V,?> par; V tr, sr;
5180 <                    if ((c = t.pending) == 0) {
5181 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5182 <                            if ((sr = s.result) != null)
5183 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5184 <                        }
5185 <                        if ((par = t.parent) == null ||
5186 <                            !(par instanceof ReduceValuesTask)) {
5187 <                            t.quietlyComplete();
5188 <                            break;
6046 <                        }
6047 <                        t = (ReduceValuesTask<K,V>)par;
5178 >                CountedCompleter<?> c;
5179 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5180 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5181 >                        t = (ReduceValuesTask<K,V>)c,
5182 >                        s = t.rights;
5183 >                    while (s != null) {
5184 >                        V tr, sr;
5185 >                        if ((sr = s.result) != null)
5186 >                            t.result = (((tr = t.result) == null) ? sr :
5187 >                                        reducer.apply(tr, sr));
5188 >                        s = t.rights = s.nextRight;
5189                      }
6049                    else if (t.casPending(c, c - 1))
6050                        break;
5190                  }
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);
5191              }
6062            return false;
5192          }
6064        public final V getRawResult() { return result; }
5193      }
5194  
5195 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5195 >    @SuppressWarnings("serial")
5196 >    static final class ReduceEntriesTask<K,V>
5197          extends BulkTask<K,V,Map.Entry<K,V>> {
5198 <        final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5198 >        final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5199          Map.Entry<K,V> result;
5200          ReduceEntriesTask<K,V> rights, nextRight;
5201          ReduceEntriesTask
5202 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5202 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5203               ReduceEntriesTask<K,V> nextRight,
5204 <             BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5205 <            super(m, p, b); this.nextRight = nextRight;
5204 >             BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5205 >            super(p, b, i, f, t); this.nextRight = nextRight;
5206              this.reducer = reducer;
5207          }
5208 <        @SuppressWarnings("unchecked") public final boolean exec() {
5209 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
5210 <                this.reducer;
5211 <            if (reducer == null)
5212 <                return abortOnNullFunction();
5213 <            try {
5214 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6086 <                    do {} while (!casPending(c = pending, c+1));
5208 >        public final Map.Entry<K,V> getRawResult() { return result; }
5209 >        public final void compute() {
5210 >            final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5211 >            if ((reducer = this.reducer) != null) {
5212 >                for (int i = baseIndex, f, h; batch > 0 &&
5213 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5214 >                    addToPendingCount(1);
5215                      (rights = new ReduceEntriesTask<K,V>
5216 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5216 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5217 >                      rights, reducer)).fork();
5218                  }
5219                  Map.Entry<K,V> r = null;
5220 <                Object v;
5221 <                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 <                }
5220 >                for (Node<K,V> p; (p = advance()) != null; )
5221 >                    r = (r == null) ? p : reducer.apply(r, p);
5222                  result = r;
5223 <                for (ReduceEntriesTask<K,V> t = this, s;;) {
5224 <                    int c; BulkTask<K,V,?> par; Map.Entry<K,V> tr, sr;
5225 <                    if ((c = t.pending) == 0) {
5226 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5227 <                            if ((sr = s.result) != null)
5228 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5229 <                        }
5230 <                        if ((par = t.parent) == null ||
5231 <                            !(par instanceof ReduceEntriesTask)) {
5232 <                            t.quietlyComplete();
5233 <                            break;
6108 <                        }
6109 <                        t = (ReduceEntriesTask<K,V>)par;
5223 >                CountedCompleter<?> c;
5224 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5225 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5226 >                        t = (ReduceEntriesTask<K,V>)c,
5227 >                        s = t.rights;
5228 >                    while (s != null) {
5229 >                        Map.Entry<K,V> tr, sr;
5230 >                        if ((sr = s.result) != null)
5231 >                            t.result = (((tr = t.result) == null) ? sr :
5232 >                                        reducer.apply(tr, sr));
5233 >                        s = t.rights = s.nextRight;
5234                      }
6111                    else if (t.casPending(c, c - 1))
6112                        break;
5235                  }
6114            } catch (Throwable ex) {
6115                return tryCompleteComputation(ex);
5236              }
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;
5237          }
6126        public final Map.Entry<K,V> getRawResult() { return result; }
5238      }
5239  
5240 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5240 >    @SuppressWarnings("serial")
5241 >    static final class MapReduceKeysTask<K,V,U>
5242          extends BulkTask<K,V,U> {
5243 <        final Fun<? super K, ? extends U> transformer;
5244 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5243 >        final Function<? super K, ? extends U> transformer;
5244 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5245          U result;
5246          MapReduceKeysTask<K,V,U> rights, nextRight;
5247          MapReduceKeysTask
5248 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5248 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5249               MapReduceKeysTask<K,V,U> nextRight,
5250 <             Fun<? super K, ? extends U> transformer,
5251 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5252 <            super(m, p, b); this.nextRight = nextRight;
5250 >             Function<? super K, ? extends U> transformer,
5251 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5252 >            super(p, b, i, f, t); this.nextRight = nextRight;
5253              this.transformer = transformer;
5254              this.reducer = reducer;
5255          }
5256 <        @SuppressWarnings("unchecked") public final boolean exec() {
5257 <            final Fun<? super K, ? extends U> transformer =
5258 <                this.transformer;
5259 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5260 <                this.reducer;
5261 <            if (transformer == null || reducer == null)
5262 <                return abortOnNullFunction();
5263 <            try {
5264 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6153 <                    do {} while (!casPending(c = pending, c+1));
5256 >        public final U getRawResult() { return result; }
5257 >        public final void compute() {
5258 >            final Function<? super K, ? extends U> transformer;
5259 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5260 >            if ((transformer = this.transformer) != null &&
5261 >                (reducer = this.reducer) != null) {
5262 >                for (int i = baseIndex, f, h; batch > 0 &&
5263 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5264 >                    addToPendingCount(1);
5265                      (rights = new MapReduceKeysTask<K,V,U>
5266 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5266 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5267 >                      rights, transformer, reducer)).fork();
5268                  }
5269 <                U r = null, u;
5270 <                while (advance() != null) {
5271 <                    if ((u = transformer.apply((K)nextKey)) != null)
5269 >                U r = null;
5270 >                for (Node<K,V> p; (p = advance()) != null; ) {
5271 >                    U u;
5272 >                    if ((u = transformer.apply(p.key)) != null)
5273                          r = (r == null) ? u : reducer.apply(r, u);
5274                  }
5275                  result = r;
5276 <                for (MapReduceKeysTask<K,V,U> t = this, s;;) {
5277 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5278 <                    if ((c = t.pending) == 0) {
5279 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5280 <                            if ((sr = s.result) != null)
5281 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5282 <                        }
5283 <                        if ((par = t.parent) == null ||
5284 <                            !(par instanceof MapReduceKeysTask)) {
5285 <                            t.quietlyComplete();
5286 <                            break;
6174 <                        }
6175 <                        t = (MapReduceKeysTask<K,V,U>)par;
5276 >                CountedCompleter<?> c;
5277 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5278 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5279 >                        t = (MapReduceKeysTask<K,V,U>)c,
5280 >                        s = t.rights;
5281 >                    while (s != null) {
5282 >                        U tr, sr;
5283 >                        if ((sr = s.result) != null)
5284 >                            t.result = (((tr = t.result) == null) ? sr :
5285 >                                        reducer.apply(tr, sr));
5286 >                        s = t.rights = s.nextRight;
5287                      }
6177                    else if (t.casPending(c, c - 1))
6178                        break;
5288                  }
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);
5289              }
6190            return false;
5290          }
6192        public final U getRawResult() { return result; }
5291      }
5292  
5293 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5293 >    @SuppressWarnings("serial")
5294 >    static final class MapReduceValuesTask<K,V,U>
5295          extends BulkTask<K,V,U> {
5296 <        final Fun<? super V, ? extends U> transformer;
5297 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5296 >        final Function<? super V, ? extends U> transformer;
5297 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5298          U result;
5299          MapReduceValuesTask<K,V,U> rights, nextRight;
5300          MapReduceValuesTask
5301 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5301 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5302               MapReduceValuesTask<K,V,U> nextRight,
5303 <             Fun<? super V, ? extends U> transformer,
5304 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5305 <            super(m, p, b); this.nextRight = nextRight;
5303 >             Function<? super V, ? extends U> transformer,
5304 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5305 >            super(p, b, i, f, t); this.nextRight = nextRight;
5306              this.transformer = transformer;
5307              this.reducer = reducer;
5308          }
5309 <        @SuppressWarnings("unchecked") public final boolean exec() {
5310 <            final Fun<? super V, ? extends U> transformer =
5311 <                this.transformer;
5312 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5313 <                this.reducer;
5314 <            if (transformer == null || reducer == null)
5315 <                return abortOnNullFunction();
5316 <            try {
5317 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6219 <                    do {} while (!casPending(c = pending, c+1));
5309 >        public final U getRawResult() { return result; }
5310 >        public final void compute() {
5311 >            final Function<? super V, ? extends U> transformer;
5312 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5313 >            if ((transformer = this.transformer) != null &&
5314 >                (reducer = this.reducer) != null) {
5315 >                for (int i = baseIndex, f, h; batch > 0 &&
5316 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5317 >                    addToPendingCount(1);
5318                      (rights = new MapReduceValuesTask<K,V,U>
5319 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5319 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5320 >                      rights, transformer, reducer)).fork();
5321                  }
5322 <                U r = null, u;
5323 <                Object v;
5324 <                while ((v = advance()) != null) {
5325 <                    if ((u = transformer.apply((V)v)) != null)
5322 >                U r = null;
5323 >                for (Node<K,V> p; (p = advance()) != null; ) {
5324 >                    U u;
5325 >                    if ((u = transformer.apply(p.val)) != null)
5326                          r = (r == null) ? u : reducer.apply(r, u);
5327                  }
5328                  result = r;
5329 <                for (MapReduceValuesTask<K,V,U> t = this, s;;) {
5330 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5331 <                    if ((c = t.pending) == 0) {
5332 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5333 <                            if ((sr = s.result) != null)
5334 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5335 <                        }
5336 <                        if ((par = t.parent) == null ||
5337 <                            !(par instanceof MapReduceValuesTask)) {
5338 <                            t.quietlyComplete();
5339 <                            break;
6241 <                        }
6242 <                        t = (MapReduceValuesTask<K,V,U>)par;
5329 >                CountedCompleter<?> c;
5330 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5331 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5332 >                        t = (MapReduceValuesTask<K,V,U>)c,
5333 >                        s = t.rights;
5334 >                    while (s != null) {
5335 >                        U tr, sr;
5336 >                        if ((sr = s.result) != null)
5337 >                            t.result = (((tr = t.result) == null) ? sr :
5338 >                                        reducer.apply(tr, sr));
5339 >                        s = t.rights = s.nextRight;
5340                      }
6244                    else if (t.casPending(c, c - 1))
6245                        break;
5341                  }
6247            } catch (Throwable ex) {
6248                return tryCompleteComputation(ex);
5342              }
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;
5343          }
6259        public final U getRawResult() { return result; }
5344      }
5345  
5346 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5346 >    @SuppressWarnings("serial")
5347 >    static final class MapReduceEntriesTask<K,V,U>
5348          extends BulkTask<K,V,U> {
5349 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5350 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5349 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5350 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5351          U result;
5352          MapReduceEntriesTask<K,V,U> rights, nextRight;
5353          MapReduceEntriesTask
5354 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5354 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5355               MapReduceEntriesTask<K,V,U> nextRight,
5356 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5357 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5358 <            super(m, p, b); this.nextRight = nextRight;
5356 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5357 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5358 >            super(p, b, i, f, t); this.nextRight = nextRight;
5359              this.transformer = transformer;
5360              this.reducer = reducer;
5361          }
5362 <        @SuppressWarnings("unchecked") public final boolean exec() {
5363 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5364 <                this.transformer;
5365 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5366 <                this.reducer;
5367 <            if (transformer == null || reducer == null)
5368 <                return abortOnNullFunction();
5369 <            try {
5370 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6286 <                    do {} while (!casPending(c = pending, c+1));
5362 >        public final U getRawResult() { return result; }
5363 >        public final void compute() {
5364 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5365 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5366 >            if ((transformer = this.transformer) != null &&
5367 >                (reducer = this.reducer) != null) {
5368 >                for (int i = baseIndex, f, h; batch > 0 &&
5369 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5370 >                    addToPendingCount(1);
5371                      (rights = new MapReduceEntriesTask<K,V,U>
5372 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5372 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5373 >                      rights, transformer, reducer)).fork();
5374                  }
5375 <                U r = null, u;
5376 <                Object v;
5377 <                while ((v = advance()) != null) {
5378 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5375 >                U r = null;
5376 >                for (Node<K,V> p; (p = advance()) != null; ) {
5377 >                    U u;
5378 >                    if ((u = transformer.apply(p)) != null)
5379                          r = (r == null) ? u : reducer.apply(r, u);
5380                  }
5381                  result = r;
5382 <                for (MapReduceEntriesTask<K,V,U> t = this, s;;) {
5383 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5384 <                    if ((c = t.pending) == 0) {
5385 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5386 <                            if ((sr = s.result) != null)
5387 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5388 <                        }
5389 <                        if ((par = t.parent) == null ||
5390 <                            !(par instanceof MapReduceEntriesTask)) {
5391 <                            t.quietlyComplete();
5392 <                            break;
6308 <                        }
6309 <                        t = (MapReduceEntriesTask<K,V,U>)par;
5382 >                CountedCompleter<?> c;
5383 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5384 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5385 >                        t = (MapReduceEntriesTask<K,V,U>)c,
5386 >                        s = t.rights;
5387 >                    while (s != null) {
5388 >                        U tr, sr;
5389 >                        if ((sr = s.result) != null)
5390 >                            t.result = (((tr = t.result) == null) ? sr :
5391 >                                        reducer.apply(tr, sr));
5392 >                        s = t.rights = s.nextRight;
5393                      }
6311                    else if (t.casPending(c, c - 1))
6312                        break;
5394                  }
6314            } catch (Throwable ex) {
6315                return tryCompleteComputation(ex);
5395              }
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;
5396          }
6326        public final U getRawResult() { return result; }
5397      }
5398  
5399 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5399 >    @SuppressWarnings("serial")
5400 >    static final class MapReduceMappingsTask<K,V,U>
5401          extends BulkTask<K,V,U> {
5402 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5403 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5402 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5403 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5404          U result;
5405          MapReduceMappingsTask<K,V,U> rights, nextRight;
5406          MapReduceMappingsTask
5407 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5407 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5408               MapReduceMappingsTask<K,V,U> nextRight,
5409 <             BiFun<? super K, ? super V, ? extends U> transformer,
5410 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5411 <            super(m, p, b); this.nextRight = nextRight;
5409 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5410 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5411 >            super(p, b, i, f, t); this.nextRight = nextRight;
5412              this.transformer = transformer;
5413              this.reducer = reducer;
5414          }
5415 <        @SuppressWarnings("unchecked") public final boolean exec() {
5416 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5417 <                this.transformer;
5418 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5419 <                this.reducer;
5420 <            if (transformer == null || reducer == null)
5421 <                return abortOnNullFunction();
5422 <            try {
5423 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6353 <                    do {} while (!casPending(c = pending, c+1));
5415 >        public final U getRawResult() { return result; }
5416 >        public final void compute() {
5417 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5418 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5419 >            if ((transformer = this.transformer) != null &&
5420 >                (reducer = this.reducer) != null) {
5421 >                for (int i = baseIndex, f, h; batch > 0 &&
5422 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5423 >                    addToPendingCount(1);
5424                      (rights = new MapReduceMappingsTask<K,V,U>
5425 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5425 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5426 >                      rights, transformer, reducer)).fork();
5427                  }
5428 <                U r = null, u;
5429 <                Object v;
5430 <                while ((v = advance()) != null) {
5431 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5428 >                U r = null;
5429 >                for (Node<K,V> p; (p = advance()) != null; ) {
5430 >                    U u;
5431 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5432                          r = (r == null) ? u : reducer.apply(r, u);
5433                  }
5434                  result = r;
5435 <                for (MapReduceMappingsTask<K,V,U> t = this, s;;) {
5436 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5437 <                    if ((c = t.pending) == 0) {
5438 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5439 <                            if ((sr = s.result) != null)
5440 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5441 <                        }
5442 <                        if ((par = t.parent) == null ||
5443 <                            !(par instanceof MapReduceMappingsTask)) {
5444 <                            t.quietlyComplete();
5445 <                            break;
6375 <                        }
6376 <                        t = (MapReduceMappingsTask<K,V,U>)par;
5435 >                CountedCompleter<?> c;
5436 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5437 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5438 >                        t = (MapReduceMappingsTask<K,V,U>)c,
5439 >                        s = t.rights;
5440 >                    while (s != null) {
5441 >                        U tr, sr;
5442 >                        if ((sr = s.result) != null)
5443 >                            t.result = (((tr = t.result) == null) ? sr :
5444 >                                        reducer.apply(tr, sr));
5445 >                        s = t.rights = s.nextRight;
5446                      }
6378                    else if (t.casPending(c, c - 1))
6379                        break;
5447                  }
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);
5448              }
6391            return false;
5449          }
6393        public final U getRawResult() { return result; }
5450      }
5451  
5452 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5452 >    @SuppressWarnings("serial")
5453 >    static final class MapReduceKeysToDoubleTask<K,V>
5454          extends BulkTask<K,V,Double> {
5455 <        final ObjectToDouble<? super K> transformer;
5456 <        final DoubleByDoubleToDouble reducer;
5455 >        final ToDoubleFunction<? super K> transformer;
5456 >        final DoubleBinaryOperator reducer;
5457          final double basis;
5458          double result;
5459          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5460          MapReduceKeysToDoubleTask
5461 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5461 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5462               MapReduceKeysToDoubleTask<K,V> nextRight,
5463 <             ObjectToDouble<? super K> transformer,
5463 >             ToDoubleFunction<? super K> transformer,
5464               double basis,
5465 <             DoubleByDoubleToDouble reducer) {
5466 <            super(m, p, b); this.nextRight = nextRight;
5465 >             DoubleBinaryOperator reducer) {
5466 >            super(p, b, i, f, t); this.nextRight = nextRight;
5467              this.transformer = transformer;
5468              this.basis = basis; this.reducer = reducer;
5469          }
5470 <        @SuppressWarnings("unchecked") public final boolean exec() {
5471 <            final ObjectToDouble<? super K> transformer =
5472 <                this.transformer;
5473 <            final DoubleByDoubleToDouble reducer = this.reducer;
5474 <            if (transformer == null || reducer == null)
5475 <                return abortOnNullFunction();
5476 <            try {
5477 <                final double id = this.basis;
5478 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5479 <                    do {} while (!casPending(c = pending, c+1));
5470 >        public final Double getRawResult() { return result; }
5471 >        public final void compute() {
5472 >            final ToDoubleFunction<? super K> transformer;
5473 >            final DoubleBinaryOperator reducer;
5474 >            if ((transformer = this.transformer) != null &&
5475 >                (reducer = this.reducer) != null) {
5476 >                double r = this.basis;
5477 >                for (int i = baseIndex, f, h; batch > 0 &&
5478 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5479 >                    addToPendingCount(1);
5480                      (rights = new MapReduceKeysToDoubleTask<K,V>
5481 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5481 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5482 >                      rights, transformer, r, reducer)).fork();
5483                  }
5484 <                double r = id;
5485 <                while (advance() != null)
6428 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5484 >                for (Node<K,V> p; (p = advance()) != null; )
5485 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5486                  result = r;
5487 <                for (MapReduceKeysToDoubleTask<K,V> t = this, s;;) {
5488 <                    int c; BulkTask<K,V,?> par;
5489 <                    if ((c = t.pending) == 0) {
5490 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5491 <                            t.result = reducer.apply(t.result, s.result);
5492 <                        }
5493 <                        if ((par = t.parent) == null ||
5494 <                            !(par instanceof MapReduceKeysToDoubleTask)) {
6438 <                            t.quietlyComplete();
6439 <                            break;
6440 <                        }
6441 <                        t = (MapReduceKeysToDoubleTask<K,V>)par;
5487 >                CountedCompleter<?> c;
5488 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5489 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5490 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
5491 >                        s = t.rights;
5492 >                    while (s != null) {
5493 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5494 >                        s = t.rights = s.nextRight;
5495                      }
6443                    else if (t.casPending(c, c - 1))
6444                        break;
5496                  }
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);
5497              }
6456            return false;
5498          }
6458        public final Double getRawResult() { return result; }
5499      }
5500  
5501 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5501 >    @SuppressWarnings("serial")
5502 >    static final class MapReduceValuesToDoubleTask<K,V>
5503          extends BulkTask<K,V,Double> {
5504 <        final ObjectToDouble<? super V> transformer;
5505 <        final DoubleByDoubleToDouble reducer;
5504 >        final ToDoubleFunction<? super V> transformer;
5505 >        final DoubleBinaryOperator reducer;
5506          final double basis;
5507          double result;
5508          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5509          MapReduceValuesToDoubleTask
5510 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5510 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5511               MapReduceValuesToDoubleTask<K,V> nextRight,
5512 <             ObjectToDouble<? super V> transformer,
5512 >             ToDoubleFunction<? super V> transformer,
5513               double basis,
5514 <             DoubleByDoubleToDouble reducer) {
5515 <            super(m, p, b); this.nextRight = nextRight;
5514 >             DoubleBinaryOperator reducer) {
5515 >            super(p, b, i, f, t); this.nextRight = nextRight;
5516              this.transformer = transformer;
5517              this.basis = basis; this.reducer = reducer;
5518          }
5519 <        @SuppressWarnings("unchecked") public final boolean exec() {
5520 <            final ObjectToDouble<? super V> transformer =
5521 <                this.transformer;
5522 <            final DoubleByDoubleToDouble reducer = this.reducer;
5523 <            if (transformer == null || reducer == null)
5524 <                return abortOnNullFunction();
5525 <            try {
5526 <                final double id = this.basis;
5527 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5528 <                    do {} while (!casPending(c = pending, c+1));
5519 >        public final Double getRawResult() { return result; }
5520 >        public final void compute() {
5521 >            final ToDoubleFunction<? super V> transformer;
5522 >            final DoubleBinaryOperator reducer;
5523 >            if ((transformer = this.transformer) != null &&
5524 >                (reducer = this.reducer) != null) {
5525 >                double r = this.basis;
5526 >                for (int i = baseIndex, f, h; batch > 0 &&
5527 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5528 >                    addToPendingCount(1);
5529                      (rights = new MapReduceValuesToDoubleTask<K,V>
5530 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5530 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5531 >                      rights, transformer, r, reducer)).fork();
5532                  }
5533 <                double r = id;
5534 <                Object v;
6493 <                while ((v = advance()) != null)
6494 <                    r = reducer.apply(r, transformer.apply((V)v));
5533 >                for (Node<K,V> p; (p = advance()) != null; )
5534 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5535                  result = r;
5536 <                for (MapReduceValuesToDoubleTask<K,V> t = this, s;;) {
5537 <                    int c; BulkTask<K,V,?> par;
5538 <                    if ((c = t.pending) == 0) {
5539 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5540 <                            t.result = reducer.apply(t.result, s.result);
5541 <                        }
5542 <                        if ((par = t.parent) == null ||
5543 <                            !(par instanceof MapReduceValuesToDoubleTask)) {
6504 <                            t.quietlyComplete();
6505 <                            break;
6506 <                        }
6507 <                        t = (MapReduceValuesToDoubleTask<K,V>)par;
5536 >                CountedCompleter<?> c;
5537 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5538 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5539 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
5540 >                        s = t.rights;
5541 >                    while (s != null) {
5542 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5543 >                        s = t.rights = s.nextRight;
5544                      }
6509                    else if (t.casPending(c, c - 1))
6510                        break;
5545                  }
6512            } catch (Throwable ex) {
6513                return tryCompleteComputation(ex);
6514            }
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);
5546              }
6522            return false;
5547          }
6524        public final Double getRawResult() { return result; }
5548      }
5549  
5550 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5550 >    @SuppressWarnings("serial")
5551 >    static final class MapReduceEntriesToDoubleTask<K,V>
5552          extends BulkTask<K,V,Double> {
5553 <        final ObjectToDouble<Map.Entry<K,V>> transformer;
5554 <        final DoubleByDoubleToDouble reducer;
5553 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
5554 >        final DoubleBinaryOperator reducer;
5555          final double basis;
5556          double result;
5557          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5558          MapReduceEntriesToDoubleTask
5559 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5559 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5560               MapReduceEntriesToDoubleTask<K,V> nextRight,
5561 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5561 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5562               double basis,
5563 <             DoubleByDoubleToDouble reducer) {
5564 <            super(m, p, b); this.nextRight = nextRight;
5563 >             DoubleBinaryOperator reducer) {
5564 >            super(p, b, i, f, t); this.nextRight = nextRight;
5565              this.transformer = transformer;
5566              this.basis = basis; this.reducer = reducer;
5567          }
5568 <        @SuppressWarnings("unchecked") public final boolean exec() {
5569 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
5570 <                this.transformer;
5571 <            final DoubleByDoubleToDouble reducer = this.reducer;
5572 <            if (transformer == null || reducer == null)
5573 <                return abortOnNullFunction();
5574 <            try {
5575 <                final double id = this.basis;
5576 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5577 <                    do {} while (!casPending(c = pending, c+1));
5568 >        public final Double getRawResult() { return result; }
5569 >        public final void compute() {
5570 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
5571 >            final DoubleBinaryOperator reducer;
5572 >            if ((transformer = this.transformer) != null &&
5573 >                (reducer = this.reducer) != null) {
5574 >                double r = this.basis;
5575 >                for (int i = baseIndex, f, h; batch > 0 &&
5576 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5577 >                    addToPendingCount(1);
5578                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5579 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5579 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5580 >                      rights, transformer, r, reducer)).fork();
5581                  }
5582 <                double r = id;
5583 <                Object v;
6559 <                while ((v = advance()) != null)
6560 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5582 >                for (Node<K,V> p; (p = advance()) != null; )
5583 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5584                  result = r;
5585 <                for (MapReduceEntriesToDoubleTask<K,V> t = this, s;;) {
5586 <                    int c; BulkTask<K,V,?> par;
5587 <                    if ((c = t.pending) == 0) {
5588 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5589 <                            t.result = reducer.apply(t.result, s.result);
5590 <                        }
5591 <                        if ((par = t.parent) == null ||
5592 <                            !(par instanceof MapReduceEntriesToDoubleTask)) {
6570 <                            t.quietlyComplete();
6571 <                            break;
6572 <                        }
6573 <                        t = (MapReduceEntriesToDoubleTask<K,V>)par;
5585 >                CountedCompleter<?> c;
5586 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5587 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5588 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
5589 >                        s = t.rights;
5590 >                    while (s != null) {
5591 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5592 >                        s = t.rights = s.nextRight;
5593                      }
6575                    else if (t.casPending(c, c - 1))
6576                        break;
5594                  }
6578            } catch (Throwable ex) {
6579                return tryCompleteComputation(ex);
5595              }
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);
6587            }
6588            return false;
5596          }
6590        public final Double getRawResult() { return result; }
5597      }
5598  
5599 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5599 >    @SuppressWarnings("serial")
5600 >    static final class MapReduceMappingsToDoubleTask<K,V>
5601          extends BulkTask<K,V,Double> {
5602 <        final ObjectByObjectToDouble<? super K, ? super V> transformer;
5603 <        final DoubleByDoubleToDouble reducer;
5602 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
5603 >        final DoubleBinaryOperator reducer;
5604          final double basis;
5605          double result;
5606          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5607          MapReduceMappingsToDoubleTask
5608 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5608 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5609               MapReduceMappingsToDoubleTask<K,V> nextRight,
5610 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
5610 >             ToDoubleBiFunction<? super K, ? super V> transformer,
5611               double basis,
5612 <             DoubleByDoubleToDouble reducer) {
5613 <            super(m, p, b); this.nextRight = nextRight;
5612 >             DoubleBinaryOperator reducer) {
5613 >            super(p, b, i, f, t); this.nextRight = nextRight;
5614              this.transformer = transformer;
5615              this.basis = basis; this.reducer = reducer;
5616          }
5617 <        @SuppressWarnings("unchecked") public final boolean exec() {
5618 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
5619 <                this.transformer;
5620 <            final DoubleByDoubleToDouble reducer = this.reducer;
5621 <            if (transformer == null || reducer == null)
5622 <                return abortOnNullFunction();
5623 <            try {
5624 <                final double id = this.basis;
5625 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5626 <                    do {} while (!casPending(c = pending, c+1));
5617 >        public final Double getRawResult() { return result; }
5618 >        public final void compute() {
5619 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
5620 >            final DoubleBinaryOperator reducer;
5621 >            if ((transformer = this.transformer) != null &&
5622 >                (reducer = this.reducer) != null) {
5623 >                double r = this.basis;
5624 >                for (int i = baseIndex, f, h; batch > 0 &&
5625 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5626 >                    addToPendingCount(1);
5627                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5628 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5628 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5629 >                      rights, transformer, r, reducer)).fork();
5630                  }
5631 <                double r = id;
5632 <                Object v;
6625 <                while ((v = advance()) != null)
6626 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5631 >                for (Node<K,V> p; (p = advance()) != null; )
5632 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5633                  result = r;
5634 <                for (MapReduceMappingsToDoubleTask<K,V> t = this, s;;) {
5635 <                    int c; BulkTask<K,V,?> par;
5636 <                    if ((c = t.pending) == 0) {
5637 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5638 <                            t.result = reducer.apply(t.result, s.result);
5639 <                        }
5640 <                        if ((par = t.parent) == null ||
5641 <                            !(par instanceof MapReduceMappingsToDoubleTask)) {
6636 <                            t.quietlyComplete();
6637 <                            break;
6638 <                        }
6639 <                        t = (MapReduceMappingsToDoubleTask<K,V>)par;
5634 >                CountedCompleter<?> c;
5635 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5636 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5637 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
5638 >                        s = t.rights;
5639 >                    while (s != null) {
5640 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5641 >                        s = t.rights = s.nextRight;
5642                      }
6641                    else if (t.casPending(c, c - 1))
6642                        break;
5643                  }
6644            } catch (Throwable ex) {
6645                return tryCompleteComputation(ex);
5644              }
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;
5645          }
6656        public final Double getRawResult() { return result; }
5646      }
5647  
5648 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5648 >    @SuppressWarnings("serial")
5649 >    static final class MapReduceKeysToLongTask<K,V>
5650          extends BulkTask<K,V,Long> {
5651 <        final ObjectToLong<? super K> transformer;
5652 <        final LongByLongToLong reducer;
5651 >        final ToLongFunction<? super K> transformer;
5652 >        final LongBinaryOperator reducer;
5653          final long basis;
5654          long result;
5655          MapReduceKeysToLongTask<K,V> rights, nextRight;
5656          MapReduceKeysToLongTask
5657 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5657 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5658               MapReduceKeysToLongTask<K,V> nextRight,
5659 <             ObjectToLong<? super K> transformer,
5659 >             ToLongFunction<? super K> transformer,
5660               long basis,
5661 <             LongByLongToLong reducer) {
5662 <            super(m, p, b); this.nextRight = nextRight;
5661 >             LongBinaryOperator reducer) {
5662 >            super(p, b, i, f, t); this.nextRight = nextRight;
5663              this.transformer = transformer;
5664              this.basis = basis; this.reducer = reducer;
5665          }
5666 <        @SuppressWarnings("unchecked") public final boolean exec() {
5667 <            final ObjectToLong<? super K> transformer =
5668 <                this.transformer;
5669 <            final LongByLongToLong reducer = this.reducer;
5670 <            if (transformer == null || reducer == null)
5671 <                return abortOnNullFunction();
5672 <            try {
5673 <                final long id = this.basis;
5674 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5675 <                    do {} while (!casPending(c = pending, c+1));
5666 >        public final Long getRawResult() { return result; }
5667 >        public final void compute() {
5668 >            final ToLongFunction<? super K> transformer;
5669 >            final LongBinaryOperator reducer;
5670 >            if ((transformer = this.transformer) != null &&
5671 >                (reducer = this.reducer) != null) {
5672 >                long r = this.basis;
5673 >                for (int i = baseIndex, f, h; batch > 0 &&
5674 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5675 >                    addToPendingCount(1);
5676                      (rights = new MapReduceKeysToLongTask<K,V>
5677 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5677 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5678 >                      rights, transformer, r, reducer)).fork();
5679                  }
5680 <                long r = id;
5681 <                while (advance() != null)
6691 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5680 >                for (Node<K,V> p; (p = advance()) != null; )
5681 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5682                  result = r;
5683 <                for (MapReduceKeysToLongTask<K,V> t = this, s;;) {
5684 <                    int c; BulkTask<K,V,?> par;
5685 <                    if ((c = t.pending) == 0) {
5686 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5687 <                            t.result = reducer.apply(t.result, s.result);
5688 <                        }
5689 <                        if ((par = t.parent) == null ||
5690 <                            !(par instanceof MapReduceKeysToLongTask)) {
6701 <                            t.quietlyComplete();
6702 <                            break;
6703 <                        }
6704 <                        t = (MapReduceKeysToLongTask<K,V>)par;
5683 >                CountedCompleter<?> c;
5684 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5685 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5686 >                        t = (MapReduceKeysToLongTask<K,V>)c,
5687 >                        s = t.rights;
5688 >                    while (s != null) {
5689 >                        t.result = reducer.applyAsLong(t.result, s.result);
5690 >                        s = t.rights = s.nextRight;
5691                      }
6706                    else if (t.casPending(c, c - 1))
6707                        break;
5692                  }
6709            } catch (Throwable ex) {
6710                return tryCompleteComputation(ex);
5693              }
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;
5694          }
6721        public final Long getRawResult() { return result; }
5695      }
5696  
5697 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5697 >    @SuppressWarnings("serial")
5698 >    static final class MapReduceValuesToLongTask<K,V>
5699          extends BulkTask<K,V,Long> {
5700 <        final ObjectToLong<? super V> transformer;
5701 <        final LongByLongToLong reducer;
5700 >        final ToLongFunction<? super V> transformer;
5701 >        final LongBinaryOperator reducer;
5702          final long basis;
5703          long result;
5704          MapReduceValuesToLongTask<K,V> rights, nextRight;
5705          MapReduceValuesToLongTask
5706 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5706 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5707               MapReduceValuesToLongTask<K,V> nextRight,
5708 <             ObjectToLong<? super V> transformer,
5708 >             ToLongFunction<? super V> transformer,
5709               long basis,
5710 <             LongByLongToLong reducer) {
5711 <            super(m, p, b); this.nextRight = nextRight;
5710 >             LongBinaryOperator reducer) {
5711 >            super(p, b, i, f, t); this.nextRight = nextRight;
5712              this.transformer = transformer;
5713              this.basis = basis; this.reducer = reducer;
5714          }
5715 <        @SuppressWarnings("unchecked") public final boolean exec() {
5716 <            final ObjectToLong<? super V> transformer =
5717 <                this.transformer;
5718 <            final LongByLongToLong reducer = this.reducer;
5719 <            if (transformer == null || reducer == null)
5720 <                return abortOnNullFunction();
5721 <            try {
5722 <                final long id = this.basis;
5723 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5724 <                    do {} while (!casPending(c = pending, c+1));
5715 >        public final Long getRawResult() { return result; }
5716 >        public final void compute() {
5717 >            final ToLongFunction<? super V> transformer;
5718 >            final LongBinaryOperator reducer;
5719 >            if ((transformer = this.transformer) != null &&
5720 >                (reducer = this.reducer) != null) {
5721 >                long r = this.basis;
5722 >                for (int i = baseIndex, f, h; batch > 0 &&
5723 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5724 >                    addToPendingCount(1);
5725                      (rights = new MapReduceValuesToLongTask<K,V>
5726 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5726 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5727 >                      rights, transformer, r, reducer)).fork();
5728                  }
5729 <                long r = id;
5730 <                Object v;
6756 <                while ((v = advance()) != null)
6757 <                    r = reducer.apply(r, transformer.apply((V)v));
5729 >                for (Node<K,V> p; (p = advance()) != null; )
5730 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5731                  result = r;
5732 <                for (MapReduceValuesToLongTask<K,V> t = this, s;;) {
5733 <                    int c; BulkTask<K,V,?> par;
5734 <                    if ((c = t.pending) == 0) {
5735 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5736 <                            t.result = reducer.apply(t.result, s.result);
5737 <                        }
5738 <                        if ((par = t.parent) == null ||
5739 <                            !(par instanceof MapReduceValuesToLongTask)) {
6767 <                            t.quietlyComplete();
6768 <                            break;
6769 <                        }
6770 <                        t = (MapReduceValuesToLongTask<K,V>)par;
5732 >                CountedCompleter<?> c;
5733 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5734 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5735 >                        t = (MapReduceValuesToLongTask<K,V>)c,
5736 >                        s = t.rights;
5737 >                    while (s != null) {
5738 >                        t.result = reducer.applyAsLong(t.result, s.result);
5739 >                        s = t.rights = s.nextRight;
5740                      }
6772                    else if (t.casPending(c, c - 1))
6773                        break;
5741                  }
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);
5742              }
6785            return false;
5743          }
6787        public final Long getRawResult() { return result; }
5744      }
5745  
5746 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5746 >    @SuppressWarnings("serial")
5747 >    static final class MapReduceEntriesToLongTask<K,V>
5748          extends BulkTask<K,V,Long> {
5749 <        final ObjectToLong<Map.Entry<K,V>> transformer;
5750 <        final LongByLongToLong reducer;
5749 >        final ToLongFunction<Map.Entry<K,V>> transformer;
5750 >        final LongBinaryOperator reducer;
5751          final long basis;
5752          long result;
5753          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5754          MapReduceEntriesToLongTask
5755 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5755 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5756               MapReduceEntriesToLongTask<K,V> nextRight,
5757 <             ObjectToLong<Map.Entry<K,V>> transformer,
5757 >             ToLongFunction<Map.Entry<K,V>> transformer,
5758               long basis,
5759 <             LongByLongToLong reducer) {
5760 <            super(m, p, b); this.nextRight = nextRight;
5759 >             LongBinaryOperator reducer) {
5760 >            super(p, b, i, f, t); this.nextRight = nextRight;
5761              this.transformer = transformer;
5762              this.basis = basis; this.reducer = reducer;
5763          }
5764 <        @SuppressWarnings("unchecked") public final boolean exec() {
5765 <            final ObjectToLong<Map.Entry<K,V>> transformer =
5766 <                this.transformer;
5767 <            final LongByLongToLong reducer = this.reducer;
5768 <            if (transformer == null || reducer == null)
5769 <                return abortOnNullFunction();
5770 <            try {
5771 <                final long id = this.basis;
5772 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5773 <                    do {} while (!casPending(c = pending, c+1));
5764 >        public final Long getRawResult() { return result; }
5765 >        public final void compute() {
5766 >            final ToLongFunction<Map.Entry<K,V>> transformer;
5767 >            final LongBinaryOperator reducer;
5768 >            if ((transformer = this.transformer) != null &&
5769 >                (reducer = this.reducer) != null) {
5770 >                long r = this.basis;
5771 >                for (int i = baseIndex, f, h; batch > 0 &&
5772 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5773 >                    addToPendingCount(1);
5774                      (rights = new MapReduceEntriesToLongTask<K,V>
5775 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5775 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5776 >                      rights, transformer, r, reducer)).fork();
5777                  }
5778 <                long r = id;
5779 <                Object v;
6822 <                while ((v = advance()) != null)
6823 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5778 >                for (Node<K,V> p; (p = advance()) != null; )
5779 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
5780                  result = r;
5781 <                for (MapReduceEntriesToLongTask<K,V> t = this, s;;) {
5782 <                    int c; BulkTask<K,V,?> par;
5783 <                    if ((c = t.pending) == 0) {
5784 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5785 <                            t.result = reducer.apply(t.result, s.result);
5786 <                        }
5787 <                        if ((par = t.parent) == null ||
5788 <                            !(par instanceof MapReduceEntriesToLongTask)) {
6833 <                            t.quietlyComplete();
6834 <                            break;
6835 <                        }
6836 <                        t = (MapReduceEntriesToLongTask<K,V>)par;
5781 >                CountedCompleter<?> c;
5782 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5783 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5784 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
5785 >                        s = t.rights;
5786 >                    while (s != null) {
5787 >                        t.result = reducer.applyAsLong(t.result, s.result);
5788 >                        s = t.rights = s.nextRight;
5789                      }
6838                    else if (t.casPending(c, c - 1))
6839                        break;
5790                  }
6841            } catch (Throwable ex) {
6842                return tryCompleteComputation(ex);
6843            }
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);
5791              }
6851            return false;
5792          }
6853        public final Long getRawResult() { return result; }
5793      }
5794  
5795 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
5795 >    @SuppressWarnings("serial")
5796 >    static final class MapReduceMappingsToLongTask<K,V>
5797          extends BulkTask<K,V,Long> {
5798 <        final ObjectByObjectToLong<? super K, ? super V> transformer;
5799 <        final LongByLongToLong reducer;
5798 >        final ToLongBiFunction<? super K, ? super V> transformer;
5799 >        final LongBinaryOperator reducer;
5800          final long basis;
5801          long result;
5802          MapReduceMappingsToLongTask<K,V> rights, nextRight;
5803          MapReduceMappingsToLongTask
5804 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5804 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5805               MapReduceMappingsToLongTask<K,V> nextRight,
5806 <             ObjectByObjectToLong<? super K, ? super V> transformer,
5806 >             ToLongBiFunction<? super K, ? super V> transformer,
5807               long basis,
5808 <             LongByLongToLong reducer) {
5809 <            super(m, p, b); this.nextRight = nextRight;
5808 >             LongBinaryOperator reducer) {
5809 >            super(p, b, i, f, t); this.nextRight = nextRight;
5810              this.transformer = transformer;
5811              this.basis = basis; this.reducer = reducer;
5812          }
5813 <        @SuppressWarnings("unchecked") public final boolean exec() {
5814 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
5815 <                this.transformer;
5816 <            final LongByLongToLong reducer = this.reducer;
5817 <            if (transformer == null || reducer == null)
5818 <                return abortOnNullFunction();
5819 <            try {
5820 <                final long id = this.basis;
5821 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5822 <                    do {} while (!casPending(c = pending, c+1));
5813 >        public final Long getRawResult() { return result; }
5814 >        public final void compute() {
5815 >            final ToLongBiFunction<? super K, ? super V> transformer;
5816 >            final LongBinaryOperator reducer;
5817 >            if ((transformer = this.transformer) != null &&
5818 >                (reducer = this.reducer) != null) {
5819 >                long r = this.basis;
5820 >                for (int i = baseIndex, f, h; batch > 0 &&
5821 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5822 >                    addToPendingCount(1);
5823                      (rights = new MapReduceMappingsToLongTask<K,V>
5824 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5824 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5825 >                      rights, transformer, r, reducer)).fork();
5826                  }
5827 <                long r = id;
5828 <                Object v;
6888 <                while ((v = advance()) != null)
6889 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5827 >                for (Node<K,V> p; (p = advance()) != null; )
5828 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
5829                  result = r;
5830 <                for (MapReduceMappingsToLongTask<K,V> t = this, s;;) {
5831 <                    int c; BulkTask<K,V,?> par;
5832 <                    if ((c = t.pending) == 0) {
5833 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5834 <                            t.result = reducer.apply(t.result, s.result);
5835 <                        }
5836 <                        if ((par = t.parent) == null ||
5837 <                            !(par instanceof MapReduceMappingsToLongTask)) {
6899 <                            t.quietlyComplete();
6900 <                            break;
6901 <                        }
6902 <                        t = (MapReduceMappingsToLongTask<K,V>)par;
5830 >                CountedCompleter<?> c;
5831 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5832 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5833 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
5834 >                        s = t.rights;
5835 >                    while (s != null) {
5836 >                        t.result = reducer.applyAsLong(t.result, s.result);
5837 >                        s = t.rights = s.nextRight;
5838                      }
6904                    else if (t.casPending(c, c - 1))
6905                        break;
5839                  }
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);
5840              }
6917            return false;
5841          }
6919        public final Long getRawResult() { return result; }
5842      }
5843  
5844 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
5844 >    @SuppressWarnings("serial")
5845 >    static final class MapReduceKeysToIntTask<K,V>
5846          extends BulkTask<K,V,Integer> {
5847 <        final ObjectToInt<? super K> transformer;
5848 <        final IntByIntToInt reducer;
5847 >        final ToIntFunction<? super K> transformer;
5848 >        final IntBinaryOperator reducer;
5849          final int basis;
5850          int result;
5851          MapReduceKeysToIntTask<K,V> rights, nextRight;
5852          MapReduceKeysToIntTask
5853 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5853 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5854               MapReduceKeysToIntTask<K,V> nextRight,
5855 <             ObjectToInt<? super K> transformer,
5855 >             ToIntFunction<? super K> transformer,
5856               int basis,
5857 <             IntByIntToInt reducer) {
5858 <            super(m, p, b); this.nextRight = nextRight;
5857 >             IntBinaryOperator reducer) {
5858 >            super(p, b, i, f, t); this.nextRight = nextRight;
5859              this.transformer = transformer;
5860              this.basis = basis; this.reducer = reducer;
5861          }
5862 <        @SuppressWarnings("unchecked") public final boolean exec() {
5863 <            final ObjectToInt<? super K> transformer =
5864 <                this.transformer;
5865 <            final IntByIntToInt reducer = this.reducer;
5866 <            if (transformer == null || reducer == null)
5867 <                return abortOnNullFunction();
5868 <            try {
5869 <                final int id = this.basis;
5870 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5871 <                    do {} while (!casPending(c = pending, c+1));
5862 >        public final Integer getRawResult() { return result; }
5863 >        public final void compute() {
5864 >            final ToIntFunction<? super K> transformer;
5865 >            final IntBinaryOperator reducer;
5866 >            if ((transformer = this.transformer) != null &&
5867 >                (reducer = this.reducer) != null) {
5868 >                int r = this.basis;
5869 >                for (int i = baseIndex, f, h; batch > 0 &&
5870 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5871 >                    addToPendingCount(1);
5872                      (rights = new MapReduceKeysToIntTask<K,V>
5873 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5873 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5874 >                      rights, transformer, r, reducer)).fork();
5875                  }
5876 <                int r = id;
5877 <                while (advance() != null)
6954 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5876 >                for (Node<K,V> p; (p = advance()) != null; )
5877 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
5878                  result = r;
5879 <                for (MapReduceKeysToIntTask<K,V> t = this, s;;) {
5880 <                    int c; BulkTask<K,V,?> par;
5881 <                    if ((c = t.pending) == 0) {
5882 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5883 <                            t.result = reducer.apply(t.result, s.result);
5884 <                        }
5885 <                        if ((par = t.parent) == null ||
5886 <                            !(par instanceof MapReduceKeysToIntTask)) {
6964 <                            t.quietlyComplete();
6965 <                            break;
6966 <                        }
6967 <                        t = (MapReduceKeysToIntTask<K,V>)par;
5879 >                CountedCompleter<?> c;
5880 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5881 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5882 >                        t = (MapReduceKeysToIntTask<K,V>)c,
5883 >                        s = t.rights;
5884 >                    while (s != null) {
5885 >                        t.result = reducer.applyAsInt(t.result, s.result);
5886 >                        s = t.rights = s.nextRight;
5887                      }
6969                    else if (t.casPending(c, c - 1))
6970                        break;
5888                  }
6972            } catch (Throwable ex) {
6973                return tryCompleteComputation(ex);
5889              }
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);
6981            }
6982            return false;
5890          }
6984        public final Integer getRawResult() { return result; }
5891      }
5892  
5893 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
5893 >    @SuppressWarnings("serial")
5894 >    static final class MapReduceValuesToIntTask<K,V>
5895          extends BulkTask<K,V,Integer> {
5896 <        final ObjectToInt<? super V> transformer;
5897 <        final IntByIntToInt reducer;
5896 >        final ToIntFunction<? super V> transformer;
5897 >        final IntBinaryOperator reducer;
5898          final int basis;
5899          int result;
5900          MapReduceValuesToIntTask<K,V> rights, nextRight;
5901          MapReduceValuesToIntTask
5902 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5902 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5903               MapReduceValuesToIntTask<K,V> nextRight,
5904 <             ObjectToInt<? super V> transformer,
5904 >             ToIntFunction<? super V> transformer,
5905               int basis,
5906 <             IntByIntToInt reducer) {
5907 <            super(m, p, b); this.nextRight = nextRight;
5906 >             IntBinaryOperator reducer) {
5907 >            super(p, b, i, f, t); this.nextRight = nextRight;
5908              this.transformer = transformer;
5909              this.basis = basis; this.reducer = reducer;
5910          }
5911 <        @SuppressWarnings("unchecked") public final boolean exec() {
5912 <            final ObjectToInt<? super V> transformer =
5913 <                this.transformer;
5914 <            final IntByIntToInt reducer = this.reducer;
5915 <            if (transformer == null || reducer == null)
5916 <                return abortOnNullFunction();
5917 <            try {
5918 <                final int id = this.basis;
5919 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5920 <                    do {} while (!casPending(c = pending, c+1));
5911 >        public final Integer getRawResult() { return result; }
5912 >        public final void compute() {
5913 >            final ToIntFunction<? super V> transformer;
5914 >            final IntBinaryOperator reducer;
5915 >            if ((transformer = this.transformer) != null &&
5916 >                (reducer = this.reducer) != null) {
5917 >                int r = this.basis;
5918 >                for (int i = baseIndex, f, h; batch > 0 &&
5919 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5920 >                    addToPendingCount(1);
5921                      (rights = new MapReduceValuesToIntTask<K,V>
5922 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5922 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5923 >                      rights, transformer, r, reducer)).fork();
5924                  }
5925 <                int r = id;
5926 <                Object v;
7019 <                while ((v = advance()) != null)
7020 <                    r = reducer.apply(r, transformer.apply((V)v));
5925 >                for (Node<K,V> p; (p = advance()) != null; )
5926 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
5927                  result = r;
5928 <                for (MapReduceValuesToIntTask<K,V> t = this, s;;) {
5929 <                    int c; BulkTask<K,V,?> par;
5930 <                    if ((c = t.pending) == 0) {
5931 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5932 <                            t.result = reducer.apply(t.result, s.result);
5933 <                        }
5934 <                        if ((par = t.parent) == null ||
5935 <                            !(par instanceof MapReduceValuesToIntTask)) {
7030 <                            t.quietlyComplete();
7031 <                            break;
7032 <                        }
7033 <                        t = (MapReduceValuesToIntTask<K,V>)par;
5928 >                CountedCompleter<?> c;
5929 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5930 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5931 >                        t = (MapReduceValuesToIntTask<K,V>)c,
5932 >                        s = t.rights;
5933 >                    while (s != null) {
5934 >                        t.result = reducer.applyAsInt(t.result, s.result);
5935 >                        s = t.rights = s.nextRight;
5936                      }
7035                    else if (t.casPending(c, c - 1))
7036                        break;
5937                  }
7038            } catch (Throwable ex) {
7039                return tryCompleteComputation(ex);
5938              }
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;
5939          }
7050        public final Integer getRawResult() { return result; }
5940      }
5941  
5942 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
5942 >    @SuppressWarnings("serial")
5943 >    static final class MapReduceEntriesToIntTask<K,V>
5944          extends BulkTask<K,V,Integer> {
5945 <        final ObjectToInt<Map.Entry<K,V>> transformer;
5946 <        final IntByIntToInt reducer;
5945 >        final ToIntFunction<Map.Entry<K,V>> transformer;
5946 >        final IntBinaryOperator reducer;
5947          final int basis;
5948          int result;
5949          MapReduceEntriesToIntTask<K,V> rights, nextRight;
5950          MapReduceEntriesToIntTask
5951 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5951 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5952               MapReduceEntriesToIntTask<K,V> nextRight,
5953 <             ObjectToInt<Map.Entry<K,V>> transformer,
5953 >             ToIntFunction<Map.Entry<K,V>> transformer,
5954               int basis,
5955 <             IntByIntToInt reducer) {
5956 <            super(m, p, b); this.nextRight = nextRight;
5955 >             IntBinaryOperator reducer) {
5956 >            super(p, b, i, f, t); this.nextRight = nextRight;
5957              this.transformer = transformer;
5958              this.basis = basis; this.reducer = reducer;
5959          }
5960 <        @SuppressWarnings("unchecked") public final boolean exec() {
5961 <            final ObjectToInt<Map.Entry<K,V>> transformer =
5962 <                this.transformer;
5963 <            final IntByIntToInt reducer = this.reducer;
5964 <            if (transformer == null || reducer == null)
5965 <                return abortOnNullFunction();
5966 <            try {
5967 <                final int id = this.basis;
5968 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5969 <                    do {} while (!casPending(c = pending, c+1));
5960 >        public final Integer getRawResult() { return result; }
5961 >        public final void compute() {
5962 >            final ToIntFunction<Map.Entry<K,V>> transformer;
5963 >            final IntBinaryOperator reducer;
5964 >            if ((transformer = this.transformer) != null &&
5965 >                (reducer = this.reducer) != null) {
5966 >                int r = this.basis;
5967 >                for (int i = baseIndex, f, h; batch > 0 &&
5968 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5969 >                    addToPendingCount(1);
5970                      (rights = new MapReduceEntriesToIntTask<K,V>
5971 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5971 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5972 >                      rights, transformer, r, reducer)).fork();
5973                  }
5974 <                int r = id;
5975 <                Object v;
7085 <                while ((v = advance()) != null)
7086 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5974 >                for (Node<K,V> p; (p = advance()) != null; )
5975 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
5976                  result = r;
5977 <                for (MapReduceEntriesToIntTask<K,V> t = this, s;;) {
5978 <                    int c; BulkTask<K,V,?> par;
5979 <                    if ((c = t.pending) == 0) {
5980 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5981 <                            t.result = reducer.apply(t.result, s.result);
5982 <                        }
5983 <                        if ((par = t.parent) == null ||
5984 <                            !(par instanceof MapReduceEntriesToIntTask)) {
7096 <                            t.quietlyComplete();
7097 <                            break;
7098 <                        }
7099 <                        t = (MapReduceEntriesToIntTask<K,V>)par;
5977 >                CountedCompleter<?> c;
5978 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5979 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5980 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
5981 >                        s = t.rights;
5982 >                    while (s != null) {
5983 >                        t.result = reducer.applyAsInt(t.result, s.result);
5984 >                        s = t.rights = s.nextRight;
5985                      }
7101                    else if (t.casPending(c, c - 1))
7102                        break;
5986                  }
7104            } catch (Throwable ex) {
7105                return tryCompleteComputation(ex);
7106            }
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);
5987              }
7114            return false;
5988          }
7116        public final Integer getRawResult() { return result; }
5989      }
5990  
5991 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
5991 >    @SuppressWarnings("serial")
5992 >    static final class MapReduceMappingsToIntTask<K,V>
5993          extends BulkTask<K,V,Integer> {
5994 <        final ObjectByObjectToInt<? super K, ? super V> transformer;
5995 <        final IntByIntToInt reducer;
5994 >        final ToIntBiFunction<? super K, ? super V> transformer;
5995 >        final IntBinaryOperator reducer;
5996          final int basis;
5997          int result;
5998          MapReduceMappingsToIntTask<K,V> rights, nextRight;
5999          MapReduceMappingsToIntTask
6000 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6001 <             MapReduceMappingsToIntTask<K,V> rights,
6002 <             ObjectByObjectToInt<? super K, ? super V> transformer,
6000 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6001 >             MapReduceMappingsToIntTask<K,V> nextRight,
6002 >             ToIntBiFunction<? super K, ? super V> transformer,
6003               int basis,
6004 <             IntByIntToInt reducer) {
6005 <            super(m, p, b); this.nextRight = nextRight;
6004 >             IntBinaryOperator reducer) {
6005 >            super(p, b, i, f, t); this.nextRight = nextRight;
6006              this.transformer = transformer;
6007              this.basis = basis; this.reducer = reducer;
6008          }
6009 <        @SuppressWarnings("unchecked") public final boolean exec() {
6010 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
6011 <                this.transformer;
6012 <            final IntByIntToInt reducer = this.reducer;
6013 <            if (transformer == null || reducer == null)
6014 <                return abortOnNullFunction();
6015 <            try {
6016 <                final int id = this.basis;
6017 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6018 <                    do {} while (!casPending(c = pending, c+1));
6009 >        public final Integer getRawResult() { return result; }
6010 >        public final void compute() {
6011 >            final ToIntBiFunction<? super K, ? super V> transformer;
6012 >            final IntBinaryOperator reducer;
6013 >            if ((transformer = this.transformer) != null &&
6014 >                (reducer = this.reducer) != null) {
6015 >                int r = this.basis;
6016 >                for (int i = baseIndex, f, h; batch > 0 &&
6017 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6018 >                    addToPendingCount(1);
6019                      (rights = new MapReduceMappingsToIntTask<K,V>
6020 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6020 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6021 >                      rights, transformer, r, reducer)).fork();
6022                  }
6023 <                int r = id;
6024 <                Object v;
7151 <                while ((v = advance()) != null)
7152 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6023 >                for (Node<K,V> p; (p = advance()) != null; )
6024 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6025                  result = r;
6026 <                for (MapReduceMappingsToIntTask<K,V> t = this, s;;) {
6027 <                    int c; BulkTask<K,V,?> par;
6028 <                    if ((c = t.pending) == 0) {
6029 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6030 <                            t.result = reducer.apply(t.result, s.result);
6031 <                        }
6032 <                        if ((par = t.parent) == null ||
6033 <                            !(par instanceof MapReduceMappingsToIntTask)) {
7162 <                            t.quietlyComplete();
7163 <                            break;
7164 <                        }
7165 <                        t = (MapReduceMappingsToIntTask<K,V>)par;
6026 >                CountedCompleter<?> c;
6027 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6028 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
6029 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6030 >                        s = t.rights;
6031 >                    while (s != null) {
6032 >                        t.result = reducer.applyAsInt(t.result, s.result);
6033 >                        s = t.rights = s.nextRight;
6034                      }
7167                    else if (t.casPending(c, c - 1))
7168                        break;
6035                  }
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);
6036              }
7180            return false;
6037          }
7182        public final Integer getRawResult() { return result; }
6038      }
6039  
6040      // Unsafe mechanics
6041 <    private static final sun.misc.Unsafe UNSAFE;
6042 <    private static final long counterOffset;
6043 <    private static final long sizeCtlOffset;
6041 >    private static final sun.misc.Unsafe U;
6042 >    private static final long SIZECTL;
6043 >    private static final long TRANSFERINDEX;
6044 >    private static final long TRANSFERORIGIN;
6045 >    private static final long BASECOUNT;
6046 >    private static final long CELLSBUSY;
6047 >    private static final long CELLVALUE;
6048      private static final long ABASE;
6049      private static final int ASHIFT;
6050  
6051      static {
7193        int ss;
6052          try {
6053 <            UNSAFE = sun.misc.Unsafe.getUnsafe();
6053 >            U = sun.misc.Unsafe.getUnsafe();
6054              Class<?> k = ConcurrentHashMap.class;
6055 <            counterOffset = UNSAFE.objectFieldOffset
7198 <                (k.getDeclaredField("counter"));
7199 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6055 >            SIZECTL = U.objectFieldOffset
6056                  (k.getDeclaredField("sizeCtl"));
6057 +            TRANSFERINDEX = U.objectFieldOffset
6058 +                (k.getDeclaredField("transferIndex"));
6059 +            TRANSFERORIGIN = U.objectFieldOffset
6060 +                (k.getDeclaredField("transferOrigin"));
6061 +            BASECOUNT = U.objectFieldOffset
6062 +                (k.getDeclaredField("baseCount"));
6063 +            CELLSBUSY = U.objectFieldOffset
6064 +                (k.getDeclaredField("cellsBusy"));
6065 +            Class<?> ck = CounterCell.class;
6066 +            CELLVALUE = U.objectFieldOffset
6067 +                (ck.getDeclaredField("value"));
6068              Class<?> sc = Node[].class;
6069 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6070 <            ss = UNSAFE.arrayIndexScale(sc);
6069 >            ABASE = U.arrayBaseOffset(sc);
6070 >            int scale = U.arrayIndexScale(sc);
6071 >            if ((scale & (scale - 1)) != 0)
6072 >                throw new Error("data type scale not a power of two");
6073 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6074          } catch (Exception e) {
6075              throw new Error(e);
6076          }
7207        if ((ss & (ss-1)) != 0)
7208            throw new Error("data type scale not a power of two");
7209        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6077      }
6078   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines