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.250 by jsr166, Sun Sep 1 05:22:49 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines