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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines