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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines