ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
(Generate patch)

Comparing jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java (file contents):
Revision 1.143 by jsr166, Fri Nov 9 03:30:03 2012 UTC vs.
Revision 1.282 by jsr166, Sat Sep 19 18:04:22 2015 UTC

# Line 5 | Line 5
5   */
6  
7   package java.util.concurrent;
8 import java.util.concurrent.atomic.LongAdder;
9 import java.util.concurrent.ForkJoinPool;
10 import java.util.concurrent.ForkJoinTask;
8  
9 < import java.util.Comparator;
9 > import java.io.ObjectStreamField;
10 > import java.io.Serializable;
11 > import java.lang.reflect.ParameterizedType;
12 > import java.lang.reflect.Type;
13 > import java.util.AbstractMap;
14   import java.util.Arrays;
14 import java.util.Map;
15 import java.util.Set;
15   import java.util.Collection;
16 < import java.util.AbstractMap;
18 < import java.util.AbstractSet;
19 < import java.util.AbstractCollection;
20 < import java.util.Hashtable;
16 > import java.util.Enumeration;
17   import java.util.HashMap;
18 + import java.util.Hashtable;
19   import java.util.Iterator;
20 < import java.util.Enumeration;
24 < import java.util.ConcurrentModificationException;
20 > import java.util.Map;
21   import java.util.NoSuchElementException;
22 < import java.util.concurrent.ConcurrentMap;
23 < import java.util.concurrent.ThreadLocalRandom;
28 < import java.util.concurrent.locks.LockSupport;
29 < import java.util.concurrent.locks.AbstractQueuedSynchronizer;
22 > import java.util.Set;
23 > import java.util.Spliterator;
24   import java.util.concurrent.atomic.AtomicReference;
25 <
26 < import java.io.Serializable;
25 > import java.util.concurrent.locks.LockSupport;
26 > import java.util.concurrent.locks.ReentrantLock;
27 > import java.util.function.BiConsumer;
28 > import java.util.function.BiFunction;
29 > import java.util.function.Consumer;
30 > import java.util.function.DoubleBinaryOperator;
31 > import java.util.function.Function;
32 > import java.util.function.IntBinaryOperator;
33 > import java.util.function.LongBinaryOperator;
34 > import java.util.function.Predicate;
35 > import java.util.function.ToDoubleBiFunction;
36 > import java.util.function.ToDoubleFunction;
37 > import java.util.function.ToIntBiFunction;
38 > import java.util.function.ToIntFunction;
39 > import java.util.function.ToLongBiFunction;
40 > import java.util.function.ToLongFunction;
41 > import java.util.stream.Stream;
42  
43   /**
44   * A hash table supporting full concurrency of retrievals and
# Line 43 | Line 52 | import java.io.Serializable;
52   * interoperable with {@code Hashtable} in programs that rely on its
53   * thread safety but not on its synchronization details.
54   *
55 < * <p> Retrieval operations (including {@code get}) generally do not
55 > * <p>Retrieval operations (including {@code get}) generally do not
56   * block, so may overlap with update operations (including {@code put}
57   * and {@code remove}). Retrievals reflect the results of the most
58   * recently <em>completed</em> update operations holding upon their
# Line 52 | Line 61 | import java.io.Serializable;
61   * that key reporting the updated value.)  For aggregate operations
62   * such as {@code putAll} and {@code clear}, concurrent retrievals may
63   * reflect insertion or removal of only some entries.  Similarly,
64 < * Iterators and Enumerations return elements reflecting the state of
65 < * the hash table at some point at or since the creation of the
64 > * Iterators, Spliterators and Enumerations return elements reflecting the
65 > * state of the hash table at some point at or since the creation of the
66   * iterator/enumeration.  They do <em>not</em> throw {@link
67 < * ConcurrentModificationException}.  However, iterators are designed
68 < * to be used by only one thread at a time.  Bear in mind that the
69 < * results of aggregate status methods including {@code size}, {@code
70 < * isEmpty}, and {@code containsValue} are typically useful only when
71 < * a map is not undergoing concurrent updates in other threads.
67 > * java.util.ConcurrentModificationException ConcurrentModificationException}.
68 > * However, iterators are designed to be used by only one thread at a time.
69 > * Bear in mind that the results of aggregate status methods including
70 > * {@code size}, {@code isEmpty}, and {@code containsValue} are typically
71 > * useful only when a map is not undergoing concurrent updates in other threads.
72   * Otherwise the results of these methods reflect transient states
73   * that may be adequate for monitoring or estimation purposes, but not
74   * for program control.
75   *
76 < * <p> The table is dynamically expanded when there are too many
76 > * <p>The table is dynamically expanded when there are too many
77   * collisions (i.e., keys that have distinct hash codes but fall into
78   * the same slot modulo the table size), with the expected average
79   * effect of maintaining roughly two bins per mapping (corresponding
# Line 83 | Line 92 | import java.io.Serializable;
92   * expected {@code concurrencyLevel} as an additional hint for
93   * internal sizing.  Note that using many keys with exactly the same
94   * {@code hashCode()} is a sure way to slow down performance of any
95 < * hash table.
95 > * hash table. To ameliorate impact, when keys are {@link Comparable},
96 > * this class may use comparison order among keys to help break ties.
97   *
98 < * <p> A {@link Set} projection of a ConcurrentHashMap may be created
98 > * <p>A {@link Set} projection of a ConcurrentHashMap may be created
99   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
100   * (using {@link #keySet(Object)} when only keys are of interest, and the
101   * mapped values are (perhaps transiently) not used or all take the
102   * same mapping value.
103   *
104 < * <p> A ConcurrentHashMap can be used as scalable frequency map (a
105 < * form of histogram or multiset) by using {@link LongAdder} values
106 < * and initializing via {@link #computeIfAbsent}. For example, to add
107 < * a count to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you
108 < * can use {@code freqs.computeIfAbsent(k -> new
109 < * LongAdder()).increment();}
104 > * <p>A ConcurrentHashMap can be used as a scalable frequency map (a
105 > * form of histogram or multiset) by using {@link
106 > * java.util.concurrent.atomic.LongAdder} values and initializing via
107 > * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count
108 > * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
109 > * {@code freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}
110   *
111   * <p>This class and its views and iterators implement all of the
112   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
113   * interfaces.
114   *
115 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
115 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
116   * does <em>not</em> allow {@code null} to be used as a key or value.
117   *
118 < * <p>ConcurrentHashMaps support parallel operations using the {@link
119 < * ForkJoinPool#commonPool}. (Tasks that may be used in other contexts
120 < * are available in class {@link ForkJoinTasks}). These operations are
121 < * designed to be safely, and often sensibly, applied even with maps
122 < * that are being concurrently updated by other threads; for example,
123 < * when computing a snapshot summary of the values in a shared
124 < * registry.  There are three kinds of operation, each with four
125 < * forms, accepting functions with Keys, Values, Entries, and (Key,
116 < * Value) arguments and/or return values. (The first three forms are
117 < * also available via the {@link #keySet()}, {@link #values()} and
118 < * {@link #entrySet()} views). Because the elements of a
118 > * <p>ConcurrentHashMaps support a set of sequential and parallel bulk
119 > * operations that, unlike most {@link Stream} methods, are designed
120 > * to be safely, and often sensibly, applied even with maps that are
121 > * being concurrently updated by other threads; for example, when
122 > * computing a snapshot summary of the values in a shared registry.
123 > * There are three kinds of operation, each with four forms, accepting
124 > * functions with keys, values, entries, and (key, value) pairs as
125 > * arguments and/or return values. Because the elements of a
126   * ConcurrentHashMap are not ordered in any particular way, and may be
127   * processed in different orders in different parallel executions, the
128   * correctness of supplied functions should not depend on any
129   * ordering, or on any other objects or values that may transiently
130   * change while computation is in progress; and except for forEach
131 < * actions, should ideally be side-effect-free.
131 > * actions, should ideally be side-effect-free. Bulk operations on
132 > * {@link java.util.Map.Entry} objects do not support method {@code
133 > * setValue}.
134   *
135   * <ul>
136 < * <li> forEach: Perform a given action on each element.
136 > * <li>forEach: Performs a given action on each element.
137   * A variant form applies a given transformation on each element
138 < * before performing the action.</li>
138 > * before performing the action.
139   *
140 < * <li> search: Return the first available non-null result of
140 > * <li>search: Returns the first available non-null result of
141   * applying a given function on each element; skipping further
142 < * search when a result is found.</li>
142 > * search when a result is found.
143   *
144 < * <li> reduce: Accumulate each element.  The supplied reduction
144 > * <li>reduce: Accumulates each element.  The supplied reduction
145   * function cannot rely on ordering (more formally, it should be
146   * both associative and commutative).  There are five variants:
147   *
148   * <ul>
149   *
150 < * <li> Plain reductions. (There is not a form of this method for
150 > * <li>Plain reductions. (There is not a form of this method for
151   * (key, value) function arguments since there is no corresponding
152 < * return type.)</li>
152 > * return type.)
153   *
154 < * <li> Mapped reductions that accumulate the results of a given
155 < * function applied to each element.</li>
154 > * <li>Mapped reductions that accumulate the results of a given
155 > * function applied to each element.
156   *
157 < * <li> Reductions to scalar doubles, longs, and ints, using a
158 < * given basis value.</li>
157 > * <li>Reductions to scalar doubles, longs, and ints, using a
158 > * given basis value.
159   *
151 * </li>
160   * </ul>
161   * </ul>
162   *
163 + * <p>These bulk operations accept a {@code parallelismThreshold}
164 + * argument. Methods proceed sequentially if the current map size is
165 + * estimated to be less than the given threshold. Using a value of
166 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
167 + * of {@code 1} results in maximal parallelism by partitioning into
168 + * enough subtasks to fully utilize the {@link
169 + * ForkJoinPool#commonPool()} that is used for all parallel
170 + * computations. Normally, you would initially choose one of these
171 + * extreme values, and then measure performance of using in-between
172 + * values that trade off overhead versus throughput.
173 + *
174   * <p>The concurrency properties of bulk operations follow
175   * from those of ConcurrentHashMap: Any non-null result returned
176   * from {@code get(key)} and related access methods bears a
# Line 187 | Line 206 | import java.io.Serializable;
206   * arguments can be supplied using {@code new
207   * AbstractMap.SimpleEntry(k,v)}.
208   *
209 < * <p> Bulk operations may complete abruptly, throwing an
209 > * <p>Bulk operations may complete abruptly, throwing an
210   * exception encountered in the application of a supplied
211   * function. Bear in mind when handling such exceptions that other
212   * concurrently executing functions could also have thrown
213   * exceptions, or would have done so if the first exception had
214   * not occurred.
215   *
216 < * <p>Parallel speedups for bulk operations compared to sequential
217 < * processing are common but not guaranteed.  Operations involving
218 < * brief functions on small maps may execute more slowly than
219 < * sequential loops if the underlying work to parallelize the
220 < * computation is more expensive than the computation itself.
221 < * Similarly, parallelization may not lead to much actual parallelism
222 < * if all processors are busy performing unrelated tasks.
216 > * <p>Speedups for parallel compared to sequential forms are common
217 > * but not guaranteed.  Parallel operations involving brief functions
218 > * on small maps may execute more slowly than sequential forms if the
219 > * underlying work to parallelize the computation is more expensive
220 > * than the computation itself.  Similarly, parallelization may not
221 > * lead to much actual parallelism if all processors are busy
222 > * performing unrelated tasks.
223   *
224 < * <p> All arguments to all task methods must be non-null.
206 < *
207 < * <p><em>jsr166e note: During transition, this class
208 < * uses nested functional interfaces with different names but the
209 < * same forms as those expected for JDK8.<em>
224 > * <p>All arguments to all task methods must be non-null.
225   *
226   * <p>This class is a member of the
227   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
# Line 217 | Line 232 | import java.io.Serializable;
232   * @param <K> the type of keys maintained by this map
233   * @param <V> the type of mapped values
234   */
235 < public class ConcurrentHashMap<K, V>
236 <    implements ConcurrentMap<K, V>, Serializable {
235 > public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
236 >    implements ConcurrentMap<K,V>, Serializable {
237      private static final long serialVersionUID = 7249069246763182397L;
238  
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
239      /*
240       * Overview:
241       *
# Line 301 | Line 246 | public class ConcurrentHashMap<K, V>
246       * the same or better than java.util.HashMap, and to support high
247       * initial insertion rates on an empty table by many threads.
248       *
249 <     * Each key-value mapping is held in a Node.  Because Node fields
250 <     * can contain special values, they are defined using plain Object
251 <     * types. Similarly in turn, all internal methods that use them
252 <     * work off Object types. And similarly, so do the internal
253 <     * methods of auxiliary iterator and view classes.  All public
254 <     * generic typed methods relay in/out of these internal methods,
255 <     * supplying null-checks and casts as needed. This also allows
256 <     * many of the public methods to be factored into a smaller number
257 <     * of internal methods (although sadly not so for the five
258 <     * variants of put-related operations). The validation-based
259 <     * approach explained below leads to a lot of code sprawl because
260 <     * retry-control precludes factoring into smaller methods.
249 >     * This map usually acts as a binned (bucketed) hash table.  Each
250 >     * key-value mapping is held in a Node.  Most nodes are instances
251 >     * of the basic Node class with hash, key, value, and next
252 >     * fields. However, various subclasses exist: TreeNodes are
253 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
254 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
255 >     * of bins during resizing. ReservationNodes are used as
256 >     * placeholders while establishing values in computeIfAbsent and
257 >     * related methods.  The types TreeBin, ForwardingNode, and
258 >     * ReservationNode do not hold normal user keys, values, or
259 >     * hashes, and are readily distinguishable during search etc
260 >     * because they have negative hash fields and null key and value
261 >     * fields. (These special nodes are either uncommon or transient,
262 >     * so the impact of carrying around some unused fields is
263 >     * insignificant.)
264       *
265       * The table is lazily initialized to a power-of-two size upon the
266       * first insertion.  Each bin in the table normally contains a
# Line 320 | Line 268 | public class ConcurrentHashMap<K, V>
268       * Table accesses require volatile/atomic reads, writes, and
269       * CASes.  Because there is no other way to arrange this without
270       * adding further indirections, we use intrinsics
271 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
272 <     * are always accurately traversable under volatile reads, so long
273 <     * as lookups check hash code and non-nullness of value before
274 <     * checking key equality.
275 <     *
276 <     * 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).
271 >     * (sun.misc.Unsafe) operations.
272 >     *
273 >     * We use the top (sign) bit of Node hash fields for control
274 >     * purposes -- it is available anyway because of addressing
275 >     * constraints.  Nodes with negative hash fields are specially
276 >     * handled or ignored in map methods.
277       *
278       * Insertion (via put or its variants) of the first node in an
279       * empty bin is performed by just CASing it to the bin.  This is
# Line 346 | Line 282 | public class ConcurrentHashMap<K, V>
282       * delete, and replace) require locks.  We do not want to waste
283       * the space required to associate a distinct lock object with
284       * each bin, so instead use the first node of a bin list itself as
285 <     * a lock. Blocking support for these locks relies on the builtin
286 <     * "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.
285 >     * a lock. Locking support for these locks relies on builtin
286 >     * "synchronized" monitors.
287       *
288       * Using the first node of a list as a lock does not by itself
289       * suffice though: When a node is locked, any update must first
290       * validate that it is still the first node after locking it, and
291       * retry if not. Because new nodes are always appended to lists,
292       * once a node is first in a bin, it remains first until deleted
293 <     * 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.
293 >     * or the bin becomes invalidated (upon resizing).
294       *
295       * The main disadvantage of per-bin locks is that other update
296       * operations on other nodes in a bin list protected by the same
# Line 394 | Line 323 | public class ConcurrentHashMap<K, V>
323       * sometimes deviate significantly from uniform randomness.  This
324       * includes the case when N > (1<<30), so some keys MUST collide.
325       * Similarly for dumb or hostile usages in which multiple keys are
326 <     * designed to have identical hash codes. Also, although we guard
327 <     * against the worst effects of this (see method spread), sets of
328 <     * hashes may differ only in bits that do not impact their bin
329 <     * index for a given power-of-two mask.  So we use a secondary
330 <     * strategy that applies when the number of nodes in a bin exceeds
331 <     * 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
326 >     * designed to have identical hash codes or ones that differs only
327 >     * in masked-out high bits. So we use a secondary strategy that
328 >     * applies when the number of nodes in a bin exceeds a
329 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
330 >     * specialized form of red-black trees), bounding search time to
331 >     * O(log N).  Each search step in a TreeBin is at least twice as
332       * slow as in a regular list, but given that N cannot exceed
333       * (1<<64) (before running out of addresses) this bounds search
334       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 413 | Line 339 | public class ConcurrentHashMap<K, V>
339       * iterators in the same way.
340       *
341       * The table is resized when occupancy exceeds a percentage
342 <     * threshold (nominally, 0.75, but see below).  Only a single
343 <     * thread performs the resize (using field "sizeCtl", to arrange
344 <     * exclusion), but the table otherwise remains usable for reads
345 <     * and updates. Resizing proceeds by transferring bins, one by
346 <     * one, from the table to the next table.  Because we are using
347 <     * power-of-two expansion, the elements from each bin must either
348 <     * stay at same index, or move with a power of two offset. We
349 <     * eliminate unnecessary node creation by catching cases where old
350 <     * nodes can be reused because their next fields won't change.  On
351 <     * average, only about one-sixth of them need cloning when a table
352 <     * doubles. The nodes they replace will be garbage collectable as
353 <     * soon as they are no longer referenced by any reader thread that
354 <     * may be in the midst of concurrently traversing table.  Upon
355 <     * transfer, the old table bin contains only a special forwarding
356 <     * node (with hash field "MOVED") that contains the next table as
357 <     * its key. On encountering a forwarding node, access and update
358 <     * operations restart, using the new table.
359 <     *
360 <     * Each bin transfer requires its bin lock. However, unlike other
361 <     * cases, a transfer can skip a bin if it fails to acquire its
362 <     * lock, and revisit it later (unless it is a TreeBin). Method
363 <     * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
364 <     * have been skipped because of failure to acquire a lock, and
365 <     * blocks only if none are available (i.e., only very rarely).
366 <     * The transfer operation must also ensure that all accessible
367 <     * bins in both the old and new table are usable by any traversal.
368 <     * When there are no lock acquisition failures, this is arranged
369 <     * simply by proceeding from the last bin (table.length - 1) up
370 <     * towards the first.  Upon seeing a forwarding node, traversals
371 <     * (see class Iter) arrange to move to the new table
372 <     * without revisiting nodes.  However, when any node is skipped
373 <     * during a transfer, all earlier table bins may have become
374 <     * visible, so are initialized with a reverse-forwarding node back
375 <     * to the old table until the new ones are established. (This
376 <     * sometimes requires transiently locking a forwarding node, which
377 <     * is possible under the above encoding.) These more expensive
378 <     * mechanics trigger only when necessary.
342 >     * threshold (nominally, 0.75, but see below).  Any thread
343 >     * noticing an overfull bin may assist in resizing after the
344 >     * initiating thread allocates and sets up the replacement array.
345 >     * However, rather than stalling, these other threads may proceed
346 >     * with insertions etc.  The use of TreeBins shields us from the
347 >     * worst case effects of overfilling while resizes are in
348 >     * progress.  Resizing proceeds by transferring bins, one by one,
349 >     * from the table to the next table. However, threads claim small
350 >     * blocks of indices to transfer (via field transferIndex) before
351 >     * doing so, reducing contention.  A generation stamp in field
352 >     * sizeCtl ensures that resizings do not overlap. Because we are
353 >     * using power-of-two expansion, the elements from each bin must
354 >     * either stay at same index, or move with a power of two
355 >     * offset. We eliminate unnecessary node creation by catching
356 >     * cases where old nodes can be reused because their next fields
357 >     * won't change.  On average, only about one-sixth of them need
358 >     * cloning when a table doubles. The nodes they replace will be
359 >     * garbage collectable as soon as they are no longer referenced by
360 >     * any reader thread that may be in the midst of concurrently
361 >     * traversing table.  Upon transfer, the old table bin contains
362 >     * only a special forwarding node (with hash field "MOVED") that
363 >     * contains the next table as its key. On encountering a
364 >     * forwarding node, access and update operations restart, using
365 >     * the new table.
366 >     *
367 >     * Each bin transfer requires its bin lock, which can stall
368 >     * waiting for locks while resizing. However, because other
369 >     * threads can join in and help resize rather than contend for
370 >     * locks, average aggregate waits become shorter as resizing
371 >     * progresses.  The transfer operation must also ensure that all
372 >     * accessible bins in both the old and new table are usable by any
373 >     * traversal.  This is arranged in part by proceeding from the
374 >     * last bin (table.length - 1) up towards the first.  Upon seeing
375 >     * a forwarding node, traversals (see class Traverser) arrange to
376 >     * move to the new table without revisiting nodes.  To ensure that
377 >     * no intervening nodes are skipped even when moved out of order,
378 >     * a stack (see class TableStack) is created on first encounter of
379 >     * a forwarding node during a traversal, to maintain its place if
380 >     * later processing the current table. The need for these
381 >     * save/restore mechanics is relatively rare, but when one
382 >     * forwarding node is encountered, typically many more will be.
383 >     * So Traversers use a simple caching scheme to avoid creating so
384 >     * many new TableStack nodes. (Thanks to Peter Levart for
385 >     * suggesting use of a stack here.)
386       *
387       * The traversal scheme also applies to partial traversals of
388       * ranges of bins (via an alternate Traverser constructor)
# Line 464 | Line 397 | public class ConcurrentHashMap<K, V>
397       * These cases attempt to override the initial capacity settings,
398       * but harmlessly fail to take effect in cases of races.
399       *
400 <     * The element count is maintained using a LongAdder, which avoids
401 <     * contention on updates but can encounter cache thrashing if read
402 <     * too frequently during concurrent access. To avoid reading so
403 <     * often, resizing is attempted either when a bin lock is
404 <     * contended, or upon adding to a bin already holding two or more
405 <     * nodes (checked before adding in the xIfAbsent methods, after
406 <     * adding in others). Under uniform hash distributions, the
407 <     * probability of this occurring at threshold is around 13%,
408 <     * meaning that only about 1 in 8 puts check threshold (and after
409 <     * resizing, many fewer do so). But this approximation has high
410 <     * variance for small table sizes, so we check on any collision
411 <     * for sizes <= 64. The bulk putAll operation further reduces
412 <     * contention by only committing count updates upon these size
413 <     * checks.
400 >     * The element count is maintained using a specialization of
401 >     * LongAdder. We need to incorporate a specialization rather than
402 >     * just use a LongAdder in order to access implicit
403 >     * contention-sensing that leads to creation of multiple
404 >     * CounterCells.  The counter mechanics avoid contention on
405 >     * updates but can encounter cache thrashing if read too
406 >     * frequently during concurrent access. To avoid reading so often,
407 >     * resizing under contention is attempted only upon adding to a
408 >     * bin already holding two or more nodes. Under uniform hash
409 >     * distributions, the probability of this occurring at threshold
410 >     * is around 13%, meaning that only about 1 in 8 puts check
411 >     * threshold (and after resizing, many fewer do so).
412 >     *
413 >     * TreeBins use a special form of comparison for search and
414 >     * related operations (which is the main reason we cannot use
415 >     * existing collections such as TreeMaps). TreeBins contain
416 >     * Comparable elements, but may contain others, as well as
417 >     * elements that are Comparable but not necessarily Comparable for
418 >     * the same T, so we cannot invoke compareTo among them. To handle
419 >     * this, the tree is ordered primarily by hash value, then by
420 >     * Comparable.compareTo order if applicable.  On lookup at a node,
421 >     * if elements are not comparable or compare as 0 then both left
422 >     * and right children may need to be searched in the case of tied
423 >     * hash values. (This corresponds to the full list search that
424 >     * would be necessary if all elements were non-Comparable and had
425 >     * tied hashes.) On insertion, to keep a total ordering (or as
426 >     * close as is required here) across rebalancings, we compare
427 >     * classes and identityHashCodes as tie-breakers. The red-black
428 >     * balancing code is updated from pre-jdk-collections
429 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
430 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
431 >     * Algorithms" (CLR).
432 >     *
433 >     * TreeBins also require an additional locking mechanism.  While
434 >     * list traversal is always possible by readers even during
435 >     * updates, tree traversal is not, mainly because of tree-rotations
436 >     * that may change the root node and/or its linkages.  TreeBins
437 >     * include a simple read-write lock mechanism parasitic on the
438 >     * main bin-synchronization strategy: Structural adjustments
439 >     * associated with an insertion or removal are already bin-locked
440 >     * (and so cannot conflict with other writers) but must wait for
441 >     * ongoing readers to finish. Since there can be only one such
442 >     * waiter, we use a simple scheme using a single "waiter" field to
443 >     * block writers.  However, readers need never block.  If the root
444 >     * lock is held, they proceed along the slow traversal path (via
445 >     * next-pointers) until the lock becomes available or the list is
446 >     * exhausted, whichever comes first. These cases are not fast, but
447 >     * maximize aggregate expected throughput.
448       *
449       * Maintaining API and serialization compatibility with previous
450       * versions of this class introduces several oddities. Mainly: We
451 <     * leave untouched but unused constructor arguments refering to
451 >     * leave untouched but unused constructor arguments referring to
452       * concurrencyLevel. We accept a loadFactor constructor argument,
453       * but apply it only to initial table capacity (which is the only
454       * time that we can guarantee to honor it.) We also declare an
455       * unused "Segment" class that is instantiated in minimal form
456       * only when serializing.
457 +     *
458 +     * Also, solely for compatibility with previous versions of this
459 +     * class, it extends AbstractMap, even though all of its methods
460 +     * are overridden, so it is just useless baggage.
461 +     *
462 +     * This file is organized to make things a little easier to follow
463 +     * while reading than they might otherwise: First the main static
464 +     * declarations and utilities, then fields, then main public
465 +     * methods (with a few factorings of multiple public methods into
466 +     * internal ones), then sizing methods, trees, traversers, and
467 +     * bulk operations.
468       */
469  
470      /* ---------------- Constants -------------- */
# Line 528 | Line 506 | public class ConcurrentHashMap<K, V>
506      private static final float LOAD_FACTOR = 0.75f;
507  
508      /**
509 <     * The buffer size for skipped bins during transfers. The
510 <     * value is arbitrary but should be large enough to avoid
511 <     * most locking stalls during resizes.
509 >     * The bin count threshold for using a tree rather than list for a
510 >     * bin.  Bins are converted to trees when adding an element to a
511 >     * bin with at least this many nodes. The value must be greater
512 >     * than 2, and should be at least 8 to mesh with assumptions in
513 >     * tree removal about conversion back to plain bins upon
514 >     * shrinkage.
515       */
516 <    private static final int TRANSFER_BUFFER_SIZE = 32;
516 >    static final int TREEIFY_THRESHOLD = 8;
517  
518      /**
519 <     * The bin count threshold for using a tree rather than list for a
520 <     * bin.  The value reflects the approximate break-even point for
521 <     * using tree-based operations.
519 >     * The bin count threshold for untreeifying a (split) bin during a
520 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
521 >     * most 6 to mesh with shrinkage detection under removal.
522       */
523 <    private static final int TREE_THRESHOLD = 8;
523 >    static final int UNTREEIFY_THRESHOLD = 6;
524  
525 <    /*
526 <     * Encodings for special uses of Node hash fields. See above for
527 <     * explanation.
525 >    /**
526 >     * The smallest table capacity for which bins may be treeified.
527 >     * (Otherwise the table is resized if too many nodes in a bin.)
528 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
529 >     * conflicts between resizing and treeification thresholds.
530       */
531 <    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 -------------- */
531 >    static final int MIN_TREEIFY_CAPACITY = 64;
532  
533      /**
534 <     * The array of bins. Lazily initialized upon first insertion.
535 <     * Size is always a power of two. Accessed directly by iterators.
534 >     * Minimum number of rebinnings per transfer step. Ranges are
535 >     * subdivided to allow multiple resizer threads.  This value
536 >     * serves as a lower bound to avoid resizers encountering
537 >     * excessive memory contention.  The value should be at least
538 >     * DEFAULT_CAPACITY.
539       */
540 <    transient volatile Node[] table;
540 >    private static final int MIN_TRANSFER_STRIDE = 16;
541  
542      /**
543 <     * The counter maintaining number of elements.
543 >     * The number of bits used for generation stamp in sizeCtl.
544 >     * Must be at least 6 for 32bit arrays.
545       */
546 <    private transient final LongAdder counter;
546 >    private static final int RESIZE_STAMP_BITS = 16;
547  
548      /**
549 <     * Table initialization and resizing control.  When negative, the
550 <     * 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.
549 >     * The maximum number of threads that can help resize.
550 >     * Must fit in 32 - RESIZE_STAMP_BITS bits.
551       */
552 <    private transient volatile int sizeCtl;
574 <
575 <    // views
576 <    private transient KeySetView<K,V> keySet;
577 <    private transient ValuesView<K,V> values;
578 <    private transient EntrySetView<K,V> entrySet;
579 <
580 <    /** For serialization compatibility. Null unless serialized; see below */
581 <    private Segment<K,V>[] segments;
552 >    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
553  
554 <    /* ---------------- Table element access -------------- */
554 >    /**
555 >     * The bit shift for recording size stamp in sizeCtl.
556 >     */
557 >    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
558  
559      /*
560 <     * 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.
560 >     * Encodings for Node hash fields. See above for explanation.
561       */
562 <
563 <    static final Node tabAt(Node[] tab, int i) { // used by Iter
564 <        return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
565 <    }
566 <
567 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
568 <        return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
569 <    }
570 <
571 <    private static final void setTabAt(Node[] tab, int i, Node v) {
572 <        UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
573 <    }
562 >    static final int MOVED     = -1; // hash for forwarding nodes
563 >    static final int TREEBIN   = -2; // hash for roots of trees
564 >    static final int RESERVED  = -3; // hash for transient reservations
565 >    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
566 >
567 >    /** Number of CPUS, to place bounds on some sizings */
568 >    static final int NCPU = Runtime.getRuntime().availableProcessors();
569 >
570 >    /** For serialization compatibility. */
571 >    private static final ObjectStreamField[] serialPersistentFields = {
572 >        new ObjectStreamField("segments", Segment[].class),
573 >        new ObjectStreamField("segmentMask", Integer.TYPE),
574 >        new ObjectStreamField("segmentShift", Integer.TYPE)
575 >    };
576  
577      /* ---------------- Nodes -------------- */
578  
579      /**
580 <     * Key-value entry. Note that this is never exported out as a
581 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
582 <     * field of MOVED are special, and do not contain user keys or
583 <     * values.  Otherwise, keys are never null, and null val fields
584 <     * indicate that a node is in the process of being deleted or
585 <     * created. For purposes of read-only access, a key may be read
586 <     * before a val, but can only be used after checking val to be
587 <     * non-null.
588 <     */
589 <    static class Node {
590 <        volatile int hash;
591 <        final Object key;
624 <        volatile Object val;
625 <        volatile Node next;
580 >     * Key-value entry.  This class is never exported out as a
581 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
582 >     * MapEntry below), but can be used for read-only traversals used
583 >     * in bulk tasks.  Subclasses of Node with a negative hash field
584 >     * are special, and contain null keys and values (but are never
585 >     * exported).  Otherwise, keys and vals are never null.
586 >     */
587 >    static class Node<K,V> implements Map.Entry<K,V> {
588 >        final int hash;
589 >        final K key;
590 >        volatile V val;
591 >        volatile Node<K,V> next;
592  
593 <        Node(int hash, Object key, Object val, Node next) {
593 >        Node(int hash, K key, V val, Node<K,V> next) {
594              this.hash = hash;
595              this.key = key;
596              this.val = val;
597              this.next = next;
598          }
599  
600 <        /** CompareAndSet the hash field */
601 <        final boolean casHash(int cmp, int val) {
602 <            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
603 <        }
604 <
639 <        /** The number of spins before blocking for a lock */
640 <        static final int MAX_SPINS =
641 <            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
642 <
643 <        /**
644 <         * Spins a while if LOCKED bit set and this node is the first
645 <         * of its bin, and then sets WAITING bits on hash field and
646 <         * blocks (once) if they are still set.  It is OK for this
647 <         * method to return even if lock is not available upon exit,
648 <         * which enables these simple single-wait mechanics.
649 <         *
650 <         * The corresponding signalling operation is performed within
651 <         * callers: Upon detecting that WAITING has been set when
652 <         * unlocking lock (via a failed CAS from non-waiting LOCKED
653 <         * state), unlockers acquire the sync lock and perform a
654 <         * notifyAll.
655 <         *
656 <         * The initial sanity check on tab and bounds is not currently
657 <         * necessary in the only usages of this method, but enables
658 <         * use in other future contexts.
659 <         */
660 <        final void tryAwaitLock(Node[] tab, int i) {
661 <            if (tab != null && i >= 0 && i < tab.length) { // sanity check
662 <                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
663 <                int spins = MAX_SPINS, h;
664 <                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
665 <                    if (spins >= 0) {
666 <                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
667 <                        if (r >= 0 && --spins == 0)
668 <                            Thread.yield();  // yield before block
669 <                    }
670 <                    else if (casHash(h, h | WAITING)) {
671 <                        synchronized (this) {
672 <                            if (tabAt(tab, i) == this &&
673 <                                (hash & WAITING) == WAITING) {
674 <                                try {
675 <                                    wait();
676 <                                } catch (InterruptedException ie) {
677 <                                    try {
678 <                                        Thread.currentThread().interrupt();
679 <                                    } catch (SecurityException ignore) {
680 <                                    }
681 <                                }
682 <                            }
683 <                            else
684 <                                notifyAll(); // possibly won race vs signaller
685 <                        }
686 <                        break;
687 <                    }
688 <                }
689 <            }
690 <        }
691 <
692 <        // Unsafe mechanics for casHash
693 <        private static final sun.misc.Unsafe UNSAFE;
694 <        private static final long hashOffset;
695 <
696 <        static {
697 <            try {
698 <                UNSAFE = sun.misc.Unsafe.getUnsafe();
699 <                Class<?> k = Node.class;
700 <                hashOffset = UNSAFE.objectFieldOffset
701 <                    (k.getDeclaredField("hash"));
702 <            } catch (Exception e) {
703 <                throw new Error(e);
704 <            }
705 <        }
706 <    }
707 <
708 <    /* ---------------- TreeBins -------------- */
709 <
710 <    /**
711 <     * Nodes for use in TreeBins
712 <     */
713 <    static final class TreeNode extends Node {
714 <        TreeNode parent;  // red-black tree links
715 <        TreeNode left;
716 <        TreeNode right;
717 <        TreeNode prev;    // needed to unlink next upon deletion
718 <        boolean red;
719 <
720 <        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
721 <            super(hash, key, val, next);
722 <            this.parent = parent;
723 <        }
724 <    }
725 <
726 <    /**
727 <     * A specialized form of red-black tree for use in bins
728 <     * whose size exceeds a threshold.
729 <     *
730 <     * TreeBins use a special form of comparison for search and
731 <     * related operations (which is the main reason we cannot use
732 <     * existing collections such as TreeMaps). TreeBins contain
733 <     * Comparable elements, but may contain others, as well as
734 <     * elements that are Comparable but not necessarily Comparable<T>
735 <     * for the same T, so we cannot invoke compareTo among them. To
736 <     * handle this, the tree is ordered primarily by hash value, then
737 <     * by getClass().getName() order, and then by Comparator order
738 <     * among elements of the same class.  On lookup at a node, if
739 <     * elements are not comparable or compare as 0, both left and
740 <     * right children may need to be searched in the case of tied hash
741 <     * values. (This corresponds to the full list search that would be
742 <     * necessary if all elements were non-Comparable and had tied
743 <     * hashes.)  The red-black balancing code is updated from
744 <     * pre-jdk-collections
745 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
746 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
747 <     * Algorithms" (CLR).
748 <     *
749 <     * TreeBins also maintain a separate locking discipline than
750 <     * regular bins. Because they are forwarded via special MOVED
751 <     * nodes at bin heads (which can never change once established),
752 <     * we cannot use those nodes as locks. Instead, TreeBin
753 <     * extends AbstractQueuedSynchronizer to support a simple form of
754 <     * read-write lock. For update operations and table validation,
755 <     * the exclusive form of lock behaves in the same way as bin-head
756 <     * locks. However, lookups use shared read-lock mechanics to allow
757 <     * multiple readers in the absence of writers.  Additionally,
758 <     * these lookups do not ever block: While the lock is not
759 <     * available, they proceed along the slow traversal path (via
760 <     * next-pointers) until the lock becomes available or the list is
761 <     * exhausted, whichever comes first. (These cases are not fast,
762 <     * but maximize aggregate expected throughput.)  The AQS mechanics
763 <     * for doing this are straightforward.  The lock state is held as
764 <     * AQS getState().  Read counts are negative; the write count (1)
765 <     * is positive.  There are no signalling preferences among readers
766 <     * and writers. Since we don't need to export full Lock API, we
767 <     * just override the minimal AQS methods and use them directly.
768 <     */
769 <    static final class TreeBin extends AbstractQueuedSynchronizer {
770 <        private static final long serialVersionUID = 2249069246763182397L;
771 <        transient TreeNode root;  // root of tree
772 <        transient TreeNode first; // head of next-pointer list
773 <
774 <        /* AQS overrides */
775 <        public final boolean isHeldExclusively() { return getState() > 0; }
776 <        public final boolean tryAcquire(int ignore) {
777 <            if (compareAndSetState(0, 1)) {
778 <                setExclusiveOwnerThread(Thread.currentThread());
779 <                return true;
780 <            }
781 <            return false;
782 <        }
783 <        public final boolean tryRelease(int ignore) {
784 <            setExclusiveOwnerThread(null);
785 <            setState(0);
786 <            return true;
787 <        }
788 <        public final int tryAcquireShared(int ignore) {
789 <            for (int c;;) {
790 <                if ((c = getState()) > 0)
791 <                    return -1;
792 <                if (compareAndSetState(c, c -1))
793 <                    return 1;
794 <            }
795 <        }
796 <        public final boolean tryReleaseShared(int ignore) {
797 <            int c;
798 <            do {} while (!compareAndSetState(c = getState(), c + 1));
799 <            return c == -1;
800 <        }
801 <
802 <        /** From CLR */
803 <        private void rotateLeft(TreeNode p) {
804 <            if (p != null) {
805 <                TreeNode r = p.right, pp, rl;
806 <                if ((rl = p.right = r.left) != null)
807 <                    rl.parent = p;
808 <                if ((pp = r.parent = p.parent) == null)
809 <                    root = r;
810 <                else if (pp.left == p)
811 <                    pp.left = r;
812 <                else
813 <                    pp.right = r;
814 <                r.left = p;
815 <                p.parent = r;
816 <            }
817 <        }
818 <
819 <        /** From CLR */
820 <        private void rotateRight(TreeNode p) {
821 <            if (p != null) {
822 <                TreeNode l = p.left, pp, lr;
823 <                if ((lr = p.left = l.right) != null)
824 <                    lr.parent = p;
825 <                if ((pp = l.parent = p.parent) == null)
826 <                    root = l;
827 <                else if (pp.right == p)
828 <                    pp.right = l;
829 <                else
830 <                    pp.left = l;
831 <                l.right = p;
832 <                p.parent = l;
833 <            }
600 >        public final K getKey()     { return key; }
601 >        public final V getValue()   { return val; }
602 >        public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
603 >        public final String toString() {
604 >            return Helpers.mapEntryToString(key, val);
605          }
606 <
607 <        /**
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;
606 >        public final V setValue(V value) {
607 >            throw new UnsupportedOperationException();
608          }
609  
610 <        /**
611 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
612 <         * read-lock to call getTreeNode, but during failure to get
613 <         * lock, searches along next links.
614 <         */
615 <        final Object getValue(int h, Object k) {
616 <            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;
610 >        public final boolean equals(Object o) {
611 >            Object k, v, u; Map.Entry<?,?> e;
612 >            return ((o instanceof Map.Entry) &&
613 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
614 >                    (v = e.getValue()) != null &&
615 >                    (k == key || k.equals(key)) &&
616 >                    (v == (u = val) || v.equals(u)));
617          }
618  
619          /**
620 <         * Finds or adds a node.
899 <         * @return null if added
620 >         * Virtualized support for map.get(); overridden in subclasses.
621           */
622 <        @SuppressWarnings("unchecked") final TreeNode putTreeNode
623 <            (int h, Object k, Object v) {
624 <            Class<?> c = k.getClass();
625 <            TreeNode pp = root, p = null;
626 <            int dir = 0;
627 <            while (pp != null) { // find existing node or leaf to insert at
628 <                int ph;  Object pk; Class<?> pc;
629 <                p = pp;
630 <                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;
622 >        Node<K,V> find(int h, Object k) {
623 >            Node<K,V> e = this;
624 >            if (k != null) {
625 >                do {
626 >                    K ek;
627 >                    if (e.hash == h &&
628 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
629 >                        return e;
630 >                } while ((e = e.next) != null);
631              }
632              return null;
633          }
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        }
634      }
635  
636 <    /* ---------------- Collision reduction methods -------------- */
636 >    /* ---------------- Static utilities -------------- */
637  
638      /**
639 <     * Spreads higher bits to lower, and also forces top 2 bits to 0.
640 <     * Because the table uses power-of-two masking, sets of hashes
641 <     * that vary only in bits above the current mask will always
642 <     * collide. (Among known examples are sets of Float keys holding
643 <     * consecutive whole numbers in small tables.)  To counter this,
644 <     * we apply a transform that spreads the impact of higher bits
639 >     * Spreads (XORs) higher bits of hash to lower and also forces top
640 >     * bit to 0. Because the table uses power-of-two masking, sets of
641 >     * hashes that vary only in bits above the current mask will
642 >     * always collide. (Among known examples are sets of Float keys
643 >     * holding consecutive whole numbers in small tables.)  So we
644 >     * apply a transform that spreads the impact of higher bits
645       * downward. There is a tradeoff between speed, utility, and
646       * quality of bit-spreading. Because many common sets of hashes
647 <     * are already reasonably distributed across bits (so don't benefit
648 <     * from spreading), and because we use trees to handle large sets
649 <     * of collisions in bins, we don't need excessively high quality.
647 >     * are already reasonably distributed (so don't benefit from
648 >     * spreading), and because we use trees to handle large sets of
649 >     * collisions in bins, we just XOR some shifted bits in the
650 >     * cheapest possible way to reduce systematic lossage, as well as
651 >     * to incorporate impact of the highest bits that would otherwise
652 >     * never be used in index calculations because of table bounds.
653       */
654 <    private static final int spread(int h) {
655 <        h ^= (h >>> 18) ^ (h >>> 12);
1188 <        return (h ^ (h >>> 10)) & HASH_BITS;
654 >    static final int spread(int h) {
655 >        return (h ^ (h >>> 16)) & HASH_BITS;
656      }
657  
658      /**
1192     * Replaces a list bin with a tree bin. Call only when locked.
1193     * Fails to replace if the given key is non-comparable or table
1194     * is, or needs, resizing.
1195     */
1196    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1197        if ((key instanceof Comparable) &&
1198            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
1199            TreeBin t = new TreeBin();
1200            for (Node e = tabAt(tab, index); e != null; e = e.next)
1201                t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
1202            setTabAt(tab, index, new Node(MOVED, t, null, null));
1203        }
1204    }
1205
1206    /* ---------------- Internal access and update methods -------------- */
1207
1208    /** Implementation for get and containsKey */
1209    private final Object internalGet(Object k) {
1210        int h = spread(k.hashCode());
1211        retry: for (Node[] tab = table; tab != null;) {
1212            Node e, p; Object ek, ev; int eh;      // locals to read fields once
1213            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1214                if ((eh = e.hash) == MOVED) {
1215                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1216                        return ((TreeBin)ek).getValue(h, k);
1217                    else {                        // restart with new table
1218                        tab = (Node[])ek;
1219                        continue retry;
1220                    }
1221                }
1222                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1223                         ((ek = e.key) == k || k.equals(ek)))
1224                    return ev;
1225            }
1226            break;
1227        }
1228        return null;
1229    }
1230
1231    /**
1232     * Implementation for the four public remove/replace methods:
1233     * Replaces node value with v, conditional upon match of cv if
1234     * non-null.  If resulting value is null, delete.
1235     */
1236    private final Object internalReplace(Object k, Object v, Object cv) {
1237        int h = spread(k.hashCode());
1238        Object oldVal = null;
1239        for (Node[] tab = table;;) {
1240            Node f; int i, fh; Object fk;
1241            if (tab == null ||
1242                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1243                break;
1244            else if ((fh = f.hash) == MOVED) {
1245                if ((fk = f.key) instanceof TreeBin) {
1246                    TreeBin t = (TreeBin)fk;
1247                    boolean validated = false;
1248                    boolean deleted = false;
1249                    t.acquire(0);
1250                    try {
1251                        if (tabAt(tab, i) == f) {
1252                            validated = true;
1253                            TreeNode p = t.getTreeNode(h, k, t.root);
1254                            if (p != null) {
1255                                Object pv = p.val;
1256                                if (cv == null || cv == pv || cv.equals(pv)) {
1257                                    oldVal = pv;
1258                                    if ((p.val = v) == null) {
1259                                        deleted = true;
1260                                        t.deleteTreeNode(p);
1261                                    }
1262                                }
1263                            }
1264                        }
1265                    } finally {
1266                        t.release(0);
1267                    }
1268                    if (validated) {
1269                        if (deleted)
1270                            counter.add(-1L);
1271                        break;
1272                    }
1273                }
1274                else
1275                    tab = (Node[])fk;
1276            }
1277            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
1278                break;                          // rules out possible existence
1279            else if ((fh & LOCKED) != 0) {
1280                checkForResize();               // try resizing if can't get lock
1281                f.tryAwaitLock(tab, i);
1282            }
1283            else if (f.casHash(fh, fh | LOCKED)) {
1284                boolean validated = false;
1285                boolean deleted = false;
1286                try {
1287                    if (tabAt(tab, i) == f) {
1288                        validated = true;
1289                        for (Node e = f, pred = null;;) {
1290                            Object ek, ev;
1291                            if ((e.hash & HASH_BITS) == h &&
1292                                ((ev = e.val) != null) &&
1293                                ((ek = e.key) == k || k.equals(ek))) {
1294                                if (cv == null || cv == ev || cv.equals(ev)) {
1295                                    oldVal = ev;
1296                                    if ((e.val = v) == null) {
1297                                        deleted = true;
1298                                        Node en = e.next;
1299                                        if (pred != null)
1300                                            pred.next = en;
1301                                        else
1302                                            setTabAt(tab, i, en);
1303                                    }
1304                                }
1305                                break;
1306                            }
1307                            pred = e;
1308                            if ((e = e.next) == null)
1309                                break;
1310                        }
1311                    }
1312                } finally {
1313                    if (!f.casHash(fh | LOCKED, fh)) {
1314                        f.hash = fh;
1315                        synchronized (f) { f.notifyAll(); };
1316                    }
1317                }
1318                if (validated) {
1319                    if (deleted)
1320                        counter.add(-1L);
1321                    break;
1322                }
1323            }
1324        }
1325        return oldVal;
1326    }
1327
1328    /*
1329     * Internal versions of the six insertion methods, each a
1330     * little more complicated than the last. All have
1331     * the same basic structure as the first (internalPut):
1332     *  1. If table uninitialized, create
1333     *  2. If bin empty, try to CAS new node
1334     *  3. If bin stale, use new table
1335     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1336     *  5. Lock and validate; if valid, scan and add or update
1337     *
1338     * The others interweave other checks and/or alternative actions:
1339     *  * Plain put checks for and performs resize after insertion.
1340     *  * putIfAbsent prescans for mapping without lock (and fails to add
1341     *    if present), which also makes pre-emptive resize checks worthwhile.
1342     *  * computeIfAbsent extends form used in putIfAbsent with additional
1343     *    mechanics to deal with, calls, potential exceptions and null
1344     *    returns from function call.
1345     *  * compute uses the same function-call mechanics, but without
1346     *    the prescans
1347     *  * merge acts as putIfAbsent in the absent case, but invokes the
1348     *    update function if present
1349     *  * putAll attempts to pre-allocate enough table space
1350     *    and more lazily performs count updates and checks.
1351     *
1352     * Someday when details settle down a bit more, it might be worth
1353     * some factoring to reduce sprawl.
1354     */
1355
1356    /** Implementation for put */
1357    private final Object internalPut(Object k, Object v) {
1358        int h = spread(k.hashCode());
1359        int count = 0;
1360        for (Node[] tab = table;;) {
1361            int i; Node f; int fh; Object fk;
1362            if (tab == null)
1363                tab = initTable();
1364            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1365                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1366                    break;                   // no lock when adding to empty bin
1367            }
1368            else if ((fh = f.hash) == MOVED) {
1369                if ((fk = f.key) instanceof TreeBin) {
1370                    TreeBin t = (TreeBin)fk;
1371                    Object oldVal = null;
1372                    t.acquire(0);
1373                    try {
1374                        if (tabAt(tab, i) == f) {
1375                            count = 2;
1376                            TreeNode p = t.putTreeNode(h, k, v);
1377                            if (p != null) {
1378                                oldVal = p.val;
1379                                p.val = v;
1380                            }
1381                        }
1382                    } finally {
1383                        t.release(0);
1384                    }
1385                    if (count != 0) {
1386                        if (oldVal != null)
1387                            return oldVal;
1388                        break;
1389                    }
1390                }
1391                else
1392                    tab = (Node[])fk;
1393            }
1394            else if ((fh & LOCKED) != 0) {
1395                checkForResize();
1396                f.tryAwaitLock(tab, i);
1397            }
1398            else if (f.casHash(fh, fh | LOCKED)) {
1399                Object oldVal = null;
1400                try {                        // needed in case equals() throws
1401                    if (tabAt(tab, i) == f) {
1402                        count = 1;
1403                        for (Node e = f;; ++count) {
1404                            Object ek, ev;
1405                            if ((e.hash & HASH_BITS) == h &&
1406                                (ev = e.val) != null &&
1407                                ((ek = e.key) == k || k.equals(ek))) {
1408                                oldVal = ev;
1409                                e.val = v;
1410                                break;
1411                            }
1412                            Node last = e;
1413                            if ((e = e.next) == null) {
1414                                last.next = new Node(h, k, v, null);
1415                                if (count >= TREE_THRESHOLD)
1416                                    replaceWithTreeBin(tab, i, k);
1417                                break;
1418                            }
1419                        }
1420                    }
1421                } finally {                  // unlock and signal if needed
1422                    if (!f.casHash(fh | LOCKED, fh)) {
1423                        f.hash = fh;
1424                        synchronized (f) { f.notifyAll(); };
1425                    }
1426                }
1427                if (count != 0) {
1428                    if (oldVal != null)
1429                        return oldVal;
1430                    if (tab.length <= 64)
1431                        count = 2;
1432                    break;
1433                }
1434            }
1435        }
1436        counter.add(1L);
1437        if (count > 1)
1438            checkForResize();
1439        return null;
1440    }
1441
1442    /** Implementation for putIfAbsent */
1443    private final Object internalPutIfAbsent(Object k, Object v) {
1444        int h = spread(k.hashCode());
1445        int count = 0;
1446        for (Node[] tab = table;;) {
1447            int i; Node f; int fh; Object fk, fv;
1448            if (tab == null)
1449                tab = initTable();
1450            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1451                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1452                    break;
1453            }
1454            else if ((fh = f.hash) == MOVED) {
1455                if ((fk = f.key) instanceof TreeBin) {
1456                    TreeBin t = (TreeBin)fk;
1457                    Object oldVal = null;
1458                    t.acquire(0);
1459                    try {
1460                        if (tabAt(tab, i) == f) {
1461                            count = 2;
1462                            TreeNode p = t.putTreeNode(h, k, v);
1463                            if (p != null)
1464                                oldVal = p.val;
1465                        }
1466                    } finally {
1467                        t.release(0);
1468                    }
1469                    if (count != 0) {
1470                        if (oldVal != null)
1471                            return oldVal;
1472                        break;
1473                    }
1474                }
1475                else
1476                    tab = (Node[])fk;
1477            }
1478            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1479                     ((fk = f.key) == k || k.equals(fk)))
1480                return fv;
1481            else {
1482                Node g = f.next;
1483                if (g != null) { // at least 2 nodes -- search and maybe resize
1484                    for (Node e = g;;) {
1485                        Object ek, ev;
1486                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1487                            ((ek = e.key) == k || k.equals(ek)))
1488                            return ev;
1489                        if ((e = e.next) == null) {
1490                            checkForResize();
1491                            break;
1492                        }
1493                    }
1494                }
1495                if (((fh = f.hash) & LOCKED) != 0) {
1496                    checkForResize();
1497                    f.tryAwaitLock(tab, i);
1498                }
1499                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1500                    Object oldVal = null;
1501                    try {
1502                        if (tabAt(tab, i) == f) {
1503                            count = 1;
1504                            for (Node e = f;; ++count) {
1505                                Object ek, ev;
1506                                if ((e.hash & HASH_BITS) == h &&
1507                                    (ev = e.val) != null &&
1508                                    ((ek = e.key) == k || k.equals(ek))) {
1509                                    oldVal = ev;
1510                                    break;
1511                                }
1512                                Node last = e;
1513                                if ((e = e.next) == null) {
1514                                    last.next = new Node(h, k, v, null);
1515                                    if (count >= TREE_THRESHOLD)
1516                                        replaceWithTreeBin(tab, i, k);
1517                                    break;
1518                                }
1519                            }
1520                        }
1521                    } finally {
1522                        if (!f.casHash(fh | LOCKED, fh)) {
1523                            f.hash = fh;
1524                            synchronized (f) { f.notifyAll(); };
1525                        }
1526                    }
1527                    if (count != 0) {
1528                        if (oldVal != null)
1529                            return oldVal;
1530                        if (tab.length <= 64)
1531                            count = 2;
1532                        break;
1533                    }
1534                }
1535            }
1536        }
1537        counter.add(1L);
1538        if (count > 1)
1539            checkForResize();
1540        return null;
1541    }
1542
1543    /** Implementation for computeIfAbsent */
1544    private final Object internalComputeIfAbsent(K k,
1545                                                 Fun<? super K, ?> mf) {
1546        int h = spread(k.hashCode());
1547        Object val = null;
1548        int count = 0;
1549        for (Node[] tab = table;;) {
1550            Node f; int i, fh; Object fk, fv;
1551            if (tab == null)
1552                tab = initTable();
1553            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1554                Node node = new Node(fh = h | LOCKED, k, null, null);
1555                if (casTabAt(tab, i, null, node)) {
1556                    count = 1;
1557                    try {
1558                        if ((val = mf.apply(k)) != null)
1559                            node.val = val;
1560                    } finally {
1561                        if (val == null)
1562                            setTabAt(tab, i, null);
1563                        if (!node.casHash(fh, h)) {
1564                            node.hash = h;
1565                            synchronized (node) { node.notifyAll(); };
1566                        }
1567                    }
1568                }
1569                if (count != 0)
1570                    break;
1571            }
1572            else if ((fh = f.hash) == MOVED) {
1573                if ((fk = f.key) instanceof TreeBin) {
1574                    TreeBin t = (TreeBin)fk;
1575                    boolean added = false;
1576                    t.acquire(0);
1577                    try {
1578                        if (tabAt(tab, i) == f) {
1579                            count = 1;
1580                            TreeNode p = t.getTreeNode(h, k, t.root);
1581                            if (p != null)
1582                                val = p.val;
1583                            else if ((val = mf.apply(k)) != null) {
1584                                added = true;
1585                                count = 2;
1586                                t.putTreeNode(h, k, val);
1587                            }
1588                        }
1589                    } finally {
1590                        t.release(0);
1591                    }
1592                    if (count != 0) {
1593                        if (!added)
1594                            return val;
1595                        break;
1596                    }
1597                }
1598                else
1599                    tab = (Node[])fk;
1600            }
1601            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1602                     ((fk = f.key) == k || k.equals(fk)))
1603                return fv;
1604            else {
1605                Node g = f.next;
1606                if (g != null) {
1607                    for (Node e = g;;) {
1608                        Object ek, ev;
1609                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1610                            ((ek = e.key) == k || k.equals(ek)))
1611                            return ev;
1612                        if ((e = e.next) == null) {
1613                            checkForResize();
1614                            break;
1615                        }
1616                    }
1617                }
1618                if (((fh = f.hash) & LOCKED) != 0) {
1619                    checkForResize();
1620                    f.tryAwaitLock(tab, i);
1621                }
1622                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1623                    boolean added = false;
1624                    try {
1625                        if (tabAt(tab, i) == f) {
1626                            count = 1;
1627                            for (Node e = f;; ++count) {
1628                                Object ek, ev;
1629                                if ((e.hash & HASH_BITS) == h &&
1630                                    (ev = e.val) != null &&
1631                                    ((ek = e.key) == k || k.equals(ek))) {
1632                                    val = ev;
1633                                    break;
1634                                }
1635                                Node last = e;
1636                                if ((e = e.next) == null) {
1637                                    if ((val = mf.apply(k)) != null) {
1638                                        added = true;
1639                                        last.next = new Node(h, k, val, null);
1640                                        if (count >= TREE_THRESHOLD)
1641                                            replaceWithTreeBin(tab, i, k);
1642                                    }
1643                                    break;
1644                                }
1645                            }
1646                        }
1647                    } finally {
1648                        if (!f.casHash(fh | LOCKED, fh)) {
1649                            f.hash = fh;
1650                            synchronized (f) { f.notifyAll(); };
1651                        }
1652                    }
1653                    if (count != 0) {
1654                        if (!added)
1655                            return val;
1656                        if (tab.length <= 64)
1657                            count = 2;
1658                        break;
1659                    }
1660                }
1661            }
1662        }
1663        if (val != null) {
1664            counter.add(1L);
1665            if (count > 1)
1666                checkForResize();
1667        }
1668        return val;
1669    }
1670
1671    /** Implementation for compute */
1672    @SuppressWarnings("unchecked") private final Object internalCompute
1673        (K k, boolean onlyIfPresent, BiFun<? super K, ? super V, ? extends V> mf) {
1674        int h = spread(k.hashCode());
1675        Object val = null;
1676        int delta = 0;
1677        int count = 0;
1678        for (Node[] tab = table;;) {
1679            Node f; int i, fh; Object fk;
1680            if (tab == null)
1681                tab = initTable();
1682            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1683                if (onlyIfPresent)
1684                    break;
1685                Node node = new Node(fh = h | LOCKED, k, null, null);
1686                if (casTabAt(tab, i, null, node)) {
1687                    try {
1688                        count = 1;
1689                        if ((val = mf.apply(k, null)) != null) {
1690                            node.val = val;
1691                            delta = 1;
1692                        }
1693                    } finally {
1694                        if (delta == 0)
1695                            setTabAt(tab, i, null);
1696                        if (!node.casHash(fh, h)) {
1697                            node.hash = h;
1698                            synchronized (node) { node.notifyAll(); };
1699                        }
1700                    }
1701                }
1702                if (count != 0)
1703                    break;
1704            }
1705            else if ((fh = f.hash) == MOVED) {
1706                if ((fk = f.key) instanceof TreeBin) {
1707                    TreeBin t = (TreeBin)fk;
1708                    t.acquire(0);
1709                    try {
1710                        if (tabAt(tab, i) == f) {
1711                            count = 1;
1712                            TreeNode p = t.getTreeNode(h, k, t.root);
1713                            Object pv = (p == null) ? null : p.val;
1714                            if ((val = mf.apply(k, (V)pv)) != null) {
1715                                if (p != null)
1716                                    p.val = val;
1717                                else {
1718                                    count = 2;
1719                                    delta = 1;
1720                                    t.putTreeNode(h, k, val);
1721                                }
1722                            }
1723                            else if (p != null) {
1724                                delta = -1;
1725                                t.deleteTreeNode(p);
1726                            }
1727                        }
1728                    } finally {
1729                        t.release(0);
1730                    }
1731                    if (count != 0)
1732                        break;
1733                }
1734                else
1735                    tab = (Node[])fk;
1736            }
1737            else if ((fh & LOCKED) != 0) {
1738                checkForResize();
1739                f.tryAwaitLock(tab, i);
1740            }
1741            else if (f.casHash(fh, fh | LOCKED)) {
1742                try {
1743                    if (tabAt(tab, i) == f) {
1744                        count = 1;
1745                        for (Node e = f, pred = null;; ++count) {
1746                            Object ek, ev;
1747                            if ((e.hash & HASH_BITS) == h &&
1748                                (ev = e.val) != null &&
1749                                ((ek = e.key) == k || k.equals(ek))) {
1750                                val = mf.apply(k, (V)ev);
1751                                if (val != null)
1752                                    e.val = val;
1753                                else {
1754                                    delta = -1;
1755                                    Node en = e.next;
1756                                    if (pred != null)
1757                                        pred.next = en;
1758                                    else
1759                                        setTabAt(tab, i, en);
1760                                }
1761                                break;
1762                            }
1763                            pred = e;
1764                            if ((e = e.next) == null) {
1765                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1766                                    pred.next = new Node(h, k, val, null);
1767                                    delta = 1;
1768                                    if (count >= TREE_THRESHOLD)
1769                                        replaceWithTreeBin(tab, i, k);
1770                                }
1771                                break;
1772                            }
1773                        }
1774                    }
1775                } finally {
1776                    if (!f.casHash(fh | LOCKED, fh)) {
1777                        f.hash = fh;
1778                        synchronized (f) { f.notifyAll(); };
1779                    }
1780                }
1781                if (count != 0) {
1782                    if (tab.length <= 64)
1783                        count = 2;
1784                    break;
1785                }
1786            }
1787        }
1788        if (delta != 0) {
1789            counter.add((long)delta);
1790            if (count > 1)
1791                checkForResize();
1792        }
1793        return val;
1794    }
1795
1796    /** Implementation for merge */
1797    @SuppressWarnings("unchecked") private final Object internalMerge
1798        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1799        int h = spread(k.hashCode());
1800        Object val = null;
1801        int delta = 0;
1802        int count = 0;
1803        for (Node[] tab = table;;) {
1804            int i; Node f; int fh; Object fk, fv;
1805            if (tab == null)
1806                tab = initTable();
1807            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1808                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1809                    delta = 1;
1810                    val = v;
1811                    break;
1812                }
1813            }
1814            else if ((fh = f.hash) == MOVED) {
1815                if ((fk = f.key) instanceof TreeBin) {
1816                    TreeBin t = (TreeBin)fk;
1817                    t.acquire(0);
1818                    try {
1819                        if (tabAt(tab, i) == f) {
1820                            count = 1;
1821                            TreeNode p = t.getTreeNode(h, k, t.root);
1822                            val = (p == null) ? v : mf.apply((V)p.val, v);
1823                            if (val != null) {
1824                                if (p != null)
1825                                    p.val = val;
1826                                else {
1827                                    count = 2;
1828                                    delta = 1;
1829                                    t.putTreeNode(h, k, val);
1830                                }
1831                            }
1832                            else if (p != null) {
1833                                delta = -1;
1834                                t.deleteTreeNode(p);
1835                            }
1836                        }
1837                    } finally {
1838                        t.release(0);
1839                    }
1840                    if (count != 0)
1841                        break;
1842                }
1843                else
1844                    tab = (Node[])fk;
1845            }
1846            else if ((fh & LOCKED) != 0) {
1847                checkForResize();
1848                f.tryAwaitLock(tab, i);
1849            }
1850            else if (f.casHash(fh, fh | LOCKED)) {
1851                try {
1852                    if (tabAt(tab, i) == f) {
1853                        count = 1;
1854                        for (Node e = f, pred = null;; ++count) {
1855                            Object ek, ev;
1856                            if ((e.hash & HASH_BITS) == h &&
1857                                (ev = e.val) != null &&
1858                                ((ek = e.key) == k || k.equals(ek))) {
1859                                val = mf.apply(v, (V)ev);
1860                                if (val != null)
1861                                    e.val = val;
1862                                else {
1863                                    delta = -1;
1864                                    Node en = e.next;
1865                                    if (pred != null)
1866                                        pred.next = en;
1867                                    else
1868                                        setTabAt(tab, i, en);
1869                                }
1870                                break;
1871                            }
1872                            pred = e;
1873                            if ((e = e.next) == null) {
1874                                val = v;
1875                                pred.next = new Node(h, k, val, null);
1876                                delta = 1;
1877                                if (count >= TREE_THRESHOLD)
1878                                    replaceWithTreeBin(tab, i, k);
1879                                break;
1880                            }
1881                        }
1882                    }
1883                } finally {
1884                    if (!f.casHash(fh | LOCKED, fh)) {
1885                        f.hash = fh;
1886                        synchronized (f) { f.notifyAll(); };
1887                    }
1888                }
1889                if (count != 0) {
1890                    if (tab.length <= 64)
1891                        count = 2;
1892                    break;
1893                }
1894            }
1895        }
1896        if (delta != 0) {
1897            counter.add((long)delta);
1898            if (count > 1)
1899                checkForResize();
1900        }
1901        return val;
1902    }
1903
1904    /** Implementation for putAll */
1905    private final void internalPutAll(Map<?, ?> m) {
1906        tryPresize(m.size());
1907        long delta = 0L;     // number of uncommitted additions
1908        boolean npe = false; // to throw exception on exit for nulls
1909        try {                // to clean up counts on other exceptions
1910            for (Map.Entry<?, ?> entry : m.entrySet()) {
1911                Object k, v;
1912                if (entry == null || (k = entry.getKey()) == null ||
1913                    (v = entry.getValue()) == null) {
1914                    npe = true;
1915                    break;
1916                }
1917                int h = spread(k.hashCode());
1918                for (Node[] tab = table;;) {
1919                    int i; Node f; int fh; Object fk;
1920                    if (tab == null)
1921                        tab = initTable();
1922                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1923                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1924                            ++delta;
1925                            break;
1926                        }
1927                    }
1928                    else if ((fh = f.hash) == MOVED) {
1929                        if ((fk = f.key) instanceof TreeBin) {
1930                            TreeBin t = (TreeBin)fk;
1931                            boolean validated = false;
1932                            t.acquire(0);
1933                            try {
1934                                if (tabAt(tab, i) == f) {
1935                                    validated = true;
1936                                    TreeNode p = t.getTreeNode(h, k, t.root);
1937                                    if (p != null)
1938                                        p.val = v;
1939                                    else {
1940                                        t.putTreeNode(h, k, v);
1941                                        ++delta;
1942                                    }
1943                                }
1944                            } finally {
1945                                t.release(0);
1946                            }
1947                            if (validated)
1948                                break;
1949                        }
1950                        else
1951                            tab = (Node[])fk;
1952                    }
1953                    else if ((fh & LOCKED) != 0) {
1954                        counter.add(delta);
1955                        delta = 0L;
1956                        checkForResize();
1957                        f.tryAwaitLock(tab, i);
1958                    }
1959                    else if (f.casHash(fh, fh | LOCKED)) {
1960                        int count = 0;
1961                        try {
1962                            if (tabAt(tab, i) == f) {
1963                                count = 1;
1964                                for (Node e = f;; ++count) {
1965                                    Object ek, ev;
1966                                    if ((e.hash & HASH_BITS) == h &&
1967                                        (ev = e.val) != null &&
1968                                        ((ek = e.key) == k || k.equals(ek))) {
1969                                        e.val = v;
1970                                        break;
1971                                    }
1972                                    Node last = e;
1973                                    if ((e = e.next) == null) {
1974                                        ++delta;
1975                                        last.next = new Node(h, k, v, null);
1976                                        if (count >= TREE_THRESHOLD)
1977                                            replaceWithTreeBin(tab, i, k);
1978                                        break;
1979                                    }
1980                                }
1981                            }
1982                        } finally {
1983                            if (!f.casHash(fh | LOCKED, fh)) {
1984                                f.hash = fh;
1985                                synchronized (f) { f.notifyAll(); };
1986                            }
1987                        }
1988                        if (count != 0) {
1989                            if (count > 1) {
1990                                counter.add(delta);
1991                                delta = 0L;
1992                                checkForResize();
1993                            }
1994                            break;
1995                        }
1996                    }
1997                }
1998            }
1999        } finally {
2000            if (delta != 0)
2001                counter.add(delta);
2002        }
2003        if (npe)
2004            throw new NullPointerException();
2005    }
2006
2007    /* ---------------- Table Initialization and Resizing -------------- */
2008
2009    /**
659       * Returns a power of two table size for the given desired capacity.
660       * See Hackers Delight, sec 3.2
661       */
# Line 2021 | Line 670 | public class ConcurrentHashMap<K, V>
670      }
671  
672      /**
673 <     * Initializes table, using the size recorded in sizeCtl.
673 >     * Returns x's Class if it is of the form "class C implements
674 >     * Comparable<C>", else null.
675       */
676 <    private final Node[] initTable() {
677 <        Node[] tab; int sc;
678 <        while ((tab = table) == null) {
679 <            if ((sc = sizeCtl) < 0)
680 <                Thread.yield(); // lost initialization race; just spin
681 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
682 <                try {
683 <                    if ((tab = table) == null) {
684 <                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
685 <                        tab = table = new Node[n];
686 <                        sc = n - (n >>> 2);
687 <                    }
688 <                } finally {
2039 <                    sizeCtl = sc;
676 >    static Class<?> comparableClassFor(Object x) {
677 >        if (x instanceof Comparable) {
678 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
679 >            if ((c = x.getClass()) == String.class) // bypass checks
680 >                return c;
681 >            if ((ts = c.getGenericInterfaces()) != null) {
682 >                for (int i = 0; i < ts.length; ++i) {
683 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
684 >                        ((p = (ParameterizedType)t).getRawType() ==
685 >                         Comparable.class) &&
686 >                        (as = p.getActualTypeArguments()) != null &&
687 >                        as.length == 1 && as[0] == c) // type arg is c
688 >                        return c;
689                  }
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;
690              }
691          }
692 +        return null;
693      }
694  
695      /**
696 <     * Tries to presize table to accommodate the given number of elements.
697 <     *
2073 <     * @param size number of elements (doesn't need to be perfectly accurate)
696 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
697 >     * class), else 0.
698       */
699 <    private final void tryPresize(int size) {
700 <        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
701 <            tableSizeFor(size + (size >>> 1) + 1);
702 <        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 <        }
699 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
700 >    static int compareComparables(Class<?> kc, Object k, Object x) {
701 >        return (x == null || x.getClass() != kc ? 0 :
702 >                ((Comparable)k).compareTo(x));
703      }
704  
705 +    /* ---------------- Table element access -------------- */
706 +
707      /*
708 <     * Moves and/or copies the nodes in each bin to new table. See
709 <     * above for explanation.
710 <     *
711 <     * @return the new table
712 <     */
713 <    private static final Node[] rebuild(Node[] tab) {
714 <        int n = tab.length;
715 <        Node[] nextTab = new Node[n << 1];
716 <        Node fwd = new Node(MOVED, nextTab, null, null);
717 <        int[] buffer = null;       // holds bins to revisit; null until needed
718 <        Node rev = null;           // reverse forwarder; null until needed
719 <        int nbuffered = 0;         // the number of bins in buffer list
720 <        int bufferIndex = 0;       // buffer index of current buffered bin
721 <        int bin = n - 1;           // current non-buffered bin or -1 if none
722 <
723 <        for (int i = bin;;) {      // start upwards sweep
724 <            int fh; Node f;
725 <            if ((f = tabAt(tab, i)) == null) {
726 <                if (bin >= 0) {    // Unbuffered; no lock needed (or available)
727 <                    if (!casTabAt(tab, i, f, fwd))
728 <                        continue;
729 <                }
730 <                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 <        }
708 >     * Volatile access methods are used for table elements as well as
709 >     * elements of in-progress next table while resizing.  All uses of
710 >     * the tab arguments must be null checked by callers.  All callers
711 >     * also paranoically precheck that tab's length is not zero (or an
712 >     * equivalent check), thus ensuring that any index argument taking
713 >     * the form of a hash value anded with (length - 1) is a valid
714 >     * index.  Note that, to be correct wrt arbitrary concurrency
715 >     * errors by users, these checks must operate on local variables,
716 >     * which accounts for some odd-looking inline assignments below.
717 >     * Note that calls to setTabAt always occur within locked regions,
718 >     * and so in principle require only release ordering, not
719 >     * full volatile semantics, but are currently coded as volatile
720 >     * writes to be conservative.
721 >     */
722 >
723 >    @SuppressWarnings("unchecked")
724 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
725 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
726 >    }
727 >
728 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
729 >                                        Node<K,V> c, Node<K,V> v) {
730 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
731      }
732  
733 <    /**
734 <     * 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);
733 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
734 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
735      }
736  
737 +    /* ---------------- Fields -------------- */
738 +
739      /**
740 <     * Splits a tree bin into lo and hi parts; installs in given table.
740 >     * The array of bins. Lazily initialized upon first insertion.
741 >     * Size is always a power of two. Accessed directly by iterators.
742       */
743 <    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 <    }
743 >    transient volatile Node<K,V>[] table;
744  
745      /**
746 <     * Implementation for clear. Steps through each bin, removing all
2286 <     * nodes.
746 >     * The next table to use; non-null only while resizing.
747       */
748 <    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 -------------- */
748 >    private transient volatile Node<K,V>[] nextTable;
749  
750      /**
751 <     * Encapsulates traversal for methods such as containsValue; also
752 <     * serves as a base class for other iterators and bulk tasks.
753 <     *
754 <     * At each step, the iterator snapshots the key ("nextKey") and
755 <     * 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
751 >     * Base counter value, used mainly when there is no contention,
752 >     * but also as a fallback during table initialization
753 >     * races. Updated via CAS.
754 >     */
755 >    private transient volatile long baseCount;
756  
757 <        /** Creates iterator for all entries in the table. */
758 <        Traverser(ConcurrentHashMap<K, V> map) {
759 <            this.map = map;
760 <        }
757 >    /**
758 >     * Table initialization and resizing control.  When negative, the
759 >     * table is being initialized or resized: -1 for initialization,
760 >     * else -(1 + the number of active resizing threads).  Otherwise,
761 >     * when table is null, holds the initial table size to use upon
762 >     * creation, or 0 for default. After initialization, holds the
763 >     * next element count value upon which to resize the table.
764 >     */
765 >    private transient volatile int sizeCtl;
766  
767 <        /** Creates iterator for split() methods */
768 <        Traverser(Traverser<K,V,?> it) {
769 <            ConcurrentHashMap<K, V> m; Node[] t;
770 <            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 <        }
767 >    /**
768 >     * The next table index (plus one) to split while resizing.
769 >     */
770 >    private transient volatile int transferIndex;
771  
772 <        /**
773 <         * Advances next; returns nextVal or null if terminated.
774 <         * See above for explanation.
775 <         */
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 <        }
772 >    /**
773 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
774 >     */
775 >    private transient volatile int cellsBusy;
776  
777 <        public final void remove() {
778 <            Object k = nextKey;
779 <            if (k == null && (advance() == null || (k = nextKey) == null))
780 <                throw new IllegalStateException();
2468 <            map.internalReplace(k, null, null);
2469 <        }
777 >    /**
778 >     * Table of counter cells. When non-null, size is a power of 2.
779 >     */
780 >    private transient volatile CounterCell[] counterCells;
781  
782 <        public final boolean hasNext() {
783 <            return nextVal != null || advance() != null;
784 <        }
782 >    // views
783 >    private transient KeySetView<K,V> keySet;
784 >    private transient ValuesView<K,V> values;
785 >    private transient EntrySetView<K,V> entrySet;
786  
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    }
787  
788      /* ---------------- Public operations -------------- */
789  
# Line 2484 | Line 791 | public class ConcurrentHashMap<K, V>
791       * Creates a new, empty map with the default initial table size (16).
792       */
793      public ConcurrentHashMap() {
2487        this.counter = new LongAdder();
794      }
795  
796      /**
# Line 2503 | Line 809 | public class ConcurrentHashMap<K, V>
809          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
810                     MAXIMUM_CAPACITY :
811                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2506        this.counter = new LongAdder();
812          this.sizeCtl = cap;
813      }
814  
# Line 2513 | Line 818 | public class ConcurrentHashMap<K, V>
818       * @param m the map
819       */
820      public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2516        this.counter = new LongAdder();
821          this.sizeCtl = DEFAULT_CAPACITY;
822 <        internalPutAll(m);
822 >        putAll(m);
823      }
824  
825      /**
# Line 2556 | Line 860 | public class ConcurrentHashMap<K, V>
860       * nonpositive
861       */
862      public ConcurrentHashMap(int initialCapacity,
863 <                               float loadFactor, int concurrencyLevel) {
863 >                             float loadFactor, int concurrencyLevel) {
864          if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
865              throw new IllegalArgumentException();
866          if (initialCapacity < concurrencyLevel)   // Use at least as many bins
# Line 2564 | Line 868 | public class ConcurrentHashMap<K, V>
868          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
869          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
870              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2567        this.counter = new LongAdder();
871          this.sizeCtl = cap;
872      }
873  
874 <    /**
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 <    }
874 >    // Original (since JDK1.2) Map methods
875  
876      /**
877       * {@inheritDoc}
878       */
879      public int size() {
880 <        long n = counter.sum();
880 >        long n = sumCount();
881          return ((n < 0L) ? 0 :
882                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
883                  (int)n);
884      }
885  
886      /**
887 <     * 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
887 >     * {@inheritDoc}
888       */
889 <    public long mappingCount() {
890 <        long n = counter.sum();
2625 <        return (n < 0L) ? 0L : n; // ignore transient negative values
889 >    public boolean isEmpty() {
890 >        return sumCount() <= 0L; // ignore transient negative values
891      }
892  
893      /**
# Line 2636 | Line 901 | public class ConcurrentHashMap<K, V>
901       *
902       * @throws NullPointerException if the specified key is null
903       */
904 <    @SuppressWarnings("unchecked") public V get(Object key) {
905 <        if (key == null)
906 <            throw new NullPointerException();
907 <        return (V)internalGet(key);
908 <    }
909 <
910 <    /**
911 <     * Returns the value to which the specified key is mapped,
912 <     * or the given defaultValue if this map contains no mapping for the key.
913 <     *
914 <     * @param key the key
915 <     * @param defaultValue the value to return if this map contains
916 <     * no mapping for the given key
917 <     * @return the mapping for the key, if present; else the defaultValue
918 <     * @throws NullPointerException if the specified key is null
919 <     */
920 <    @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) {
921 <        if (key == null)
2657 <            throw new NullPointerException();
2658 <        V v = (V) internalGet(key);
2659 <        return v == null ? defaultValue : v;
904 >    public V get(Object key) {
905 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
906 >        int h = spread(key.hashCode());
907 >        if ((tab = table) != null && (n = tab.length) > 0 &&
908 >            (e = tabAt(tab, (n - 1) & h)) != null) {
909 >            if ((eh = e.hash) == h) {
910 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
911 >                    return e.val;
912 >            }
913 >            else if (eh < 0)
914 >                return (p = e.find(h, key)) != null ? p.val : null;
915 >            while ((e = e.next) != null) {
916 >                if (e.hash == h &&
917 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
918 >                    return e.val;
919 >            }
920 >        }
921 >        return null;
922      }
923  
924      /**
925       * Tests if the specified object is a key in this table.
926       *
927 <     * @param  key   possible key
927 >     * @param  key possible key
928       * @return {@code true} if and only if the specified object
929       *         is a key in this table, as determined by the
930       *         {@code equals} method; {@code false} otherwise
931       * @throws NullPointerException if the specified key is null
932       */
933      public boolean containsKey(Object key) {
934 <        if (key == null)
2673 <            throw new NullPointerException();
2674 <        return internalGet(key) != null;
934 >        return get(key) != null;
935      }
936  
937      /**
# Line 2687 | Line 947 | public class ConcurrentHashMap<K, V>
947      public boolean containsValue(Object value) {
948          if (value == null)
949              throw new NullPointerException();
950 <        Object v;
951 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
952 <        while ((v = it.advance()) != null) {
953 <            if (v == value || value.equals(v))
954 <                return true;
950 >        Node<K,V>[] t;
951 >        if ((t = table) != null) {
952 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
953 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
954 >                V v;
955 >                if ((v = p.val) == value || (v != null && value.equals(v)))
956 >                    return true;
957 >            }
958          }
959          return false;
960      }
961  
962      /**
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    /**
963       * Maps the specified key to the specified value in this table.
964       * Neither the key nor the value can be null.
965       *
966 <     * <p> The value can be retrieved by calling the {@code get} method
966 >     * <p>The value can be retrieved by calling the {@code get} method
967       * with a key that is equal to the original key.
968       *
969       * @param key key with which the specified value is to be associated
# Line 2728 | Line 972 | public class ConcurrentHashMap<K, V>
972       *         {@code null} if there was no mapping for {@code key}
973       * @throws NullPointerException if the specified key or value is null
974       */
975 <    @SuppressWarnings("unchecked") public V put(K key, V value) {
976 <        if (key == null || value == null)
975 >    public V put(K key, V value) {
976 >        return putVal(key, value, false);
977 >    }
978 >
979 >    /** Implementation for put and putIfAbsent */
980 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
981 >        if (key == null || value == null) throw new NullPointerException();
982 >        int hash = spread(key.hashCode());
983 >        int binCount = 0;
984 >        for (Node<K,V>[] tab = table;;) {
985 >            Node<K,V> f; int n, i, fh;
986 >            if (tab == null || (n = tab.length) == 0)
987 >                tab = initTable();
988 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
989 >                if (casTabAt(tab, i, null,
990 >                             new Node<K,V>(hash, key, value, null)))
991 >                    break;                   // no lock when adding to empty bin
992 >            }
993 >            else if ((fh = f.hash) == MOVED)
994 >                tab = helpTransfer(tab, f);
995 >            else {
996 >                V oldVal = null;
997 >                synchronized (f) {
998 >                    if (tabAt(tab, i) == f) {
999 >                        if (fh >= 0) {
1000 >                            binCount = 1;
1001 >                            for (Node<K,V> e = f;; ++binCount) {
1002 >                                K ek;
1003 >                                if (e.hash == hash &&
1004 >                                    ((ek = e.key) == key ||
1005 >                                     (ek != null && key.equals(ek)))) {
1006 >                                    oldVal = e.val;
1007 >                                    if (!onlyIfAbsent)
1008 >                                        e.val = value;
1009 >                                    break;
1010 >                                }
1011 >                                Node<K,V> pred = e;
1012 >                                if ((e = e.next) == null) {
1013 >                                    pred.next = new Node<K,V>(hash, key,
1014 >                                                              value, null);
1015 >                                    break;
1016 >                                }
1017 >                            }
1018 >                        }
1019 >                        else if (f instanceof TreeBin) {
1020 >                            Node<K,V> p;
1021 >                            binCount = 2;
1022 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1023 >                                                           value)) != null) {
1024 >                                oldVal = p.val;
1025 >                                if (!onlyIfAbsent)
1026 >                                    p.val = value;
1027 >                            }
1028 >                        }
1029 >                        else if (f instanceof ReservationNode)
1030 >                            throw new IllegalStateException("Recursive update");
1031 >                    }
1032 >                }
1033 >                if (binCount != 0) {
1034 >                    if (binCount >= TREEIFY_THRESHOLD)
1035 >                        treeifyBin(tab, i);
1036 >                    if (oldVal != null)
1037 >                        return oldVal;
1038 >                    break;
1039 >                }
1040 >            }
1041 >        }
1042 >        addCount(1L, binCount);
1043 >        return null;
1044 >    }
1045 >
1046 >    /**
1047 >     * Copies all of the mappings from the specified map to this one.
1048 >     * These mappings replace any mappings that this map had for any of the
1049 >     * keys currently in the specified map.
1050 >     *
1051 >     * @param m mappings to be stored in this map
1052 >     */
1053 >    public void putAll(Map<? extends K, ? extends V> m) {
1054 >        tryPresize(m.size());
1055 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1056 >            putVal(e.getKey(), e.getValue(), false);
1057 >    }
1058 >
1059 >    /**
1060 >     * Removes the key (and its corresponding value) from this map.
1061 >     * This method does nothing if the key is not in the map.
1062 >     *
1063 >     * @param  key the key that needs to be removed
1064 >     * @return the previous value associated with {@code key}, or
1065 >     *         {@code null} if there was no mapping for {@code key}
1066 >     * @throws NullPointerException if the specified key is null
1067 >     */
1068 >    public V remove(Object key) {
1069 >        return replaceNode(key, null, null);
1070 >    }
1071 >
1072 >    /**
1073 >     * Implementation for the four public remove/replace methods:
1074 >     * Replaces node value with v, conditional upon match of cv if
1075 >     * non-null.  If resulting value is null, delete.
1076 >     */
1077 >    final V replaceNode(Object key, V value, Object cv) {
1078 >        int hash = spread(key.hashCode());
1079 >        for (Node<K,V>[] tab = table;;) {
1080 >            Node<K,V> f; int n, i, fh;
1081 >            if (tab == null || (n = tab.length) == 0 ||
1082 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1083 >                break;
1084 >            else if ((fh = f.hash) == MOVED)
1085 >                tab = helpTransfer(tab, f);
1086 >            else {
1087 >                V oldVal = null;
1088 >                boolean validated = false;
1089 >                synchronized (f) {
1090 >                    if (tabAt(tab, i) == f) {
1091 >                        if (fh >= 0) {
1092 >                            validated = true;
1093 >                            for (Node<K,V> e = f, pred = null;;) {
1094 >                                K ek;
1095 >                                if (e.hash == hash &&
1096 >                                    ((ek = e.key) == key ||
1097 >                                     (ek != null && key.equals(ek)))) {
1098 >                                    V ev = e.val;
1099 >                                    if (cv == null || cv == ev ||
1100 >                                        (ev != null && cv.equals(ev))) {
1101 >                                        oldVal = ev;
1102 >                                        if (value != null)
1103 >                                            e.val = value;
1104 >                                        else if (pred != null)
1105 >                                            pred.next = e.next;
1106 >                                        else
1107 >                                            setTabAt(tab, i, e.next);
1108 >                                    }
1109 >                                    break;
1110 >                                }
1111 >                                pred = e;
1112 >                                if ((e = e.next) == null)
1113 >                                    break;
1114 >                            }
1115 >                        }
1116 >                        else if (f instanceof TreeBin) {
1117 >                            validated = true;
1118 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1119 >                            TreeNode<K,V> r, p;
1120 >                            if ((r = t.root) != null &&
1121 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1122 >                                V pv = p.val;
1123 >                                if (cv == null || cv == pv ||
1124 >                                    (pv != null && cv.equals(pv))) {
1125 >                                    oldVal = pv;
1126 >                                    if (value != null)
1127 >                                        p.val = value;
1128 >                                    else if (t.removeTreeNode(p))
1129 >                                        setTabAt(tab, i, untreeify(t.first));
1130 >                                }
1131 >                            }
1132 >                        }
1133 >                        else if (f instanceof ReservationNode)
1134 >                            throw new IllegalStateException("Recursive update");
1135 >                    }
1136 >                }
1137 >                if (validated) {
1138 >                    if (oldVal != null) {
1139 >                        if (value == null)
1140 >                            addCount(-1L, -1);
1141 >                        return oldVal;
1142 >                    }
1143 >                    break;
1144 >                }
1145 >            }
1146 >        }
1147 >        return null;
1148 >    }
1149 >
1150 >    /**
1151 >     * Removes all of the mappings from this map.
1152 >     */
1153 >    public void clear() {
1154 >        long delta = 0L; // negative number of deletions
1155 >        int i = 0;
1156 >        Node<K,V>[] tab = table;
1157 >        while (tab != null && i < tab.length) {
1158 >            int fh;
1159 >            Node<K,V> f = tabAt(tab, i);
1160 >            if (f == null)
1161 >                ++i;
1162 >            else if ((fh = f.hash) == MOVED) {
1163 >                tab = helpTransfer(tab, f);
1164 >                i = 0; // restart
1165 >            }
1166 >            else {
1167 >                synchronized (f) {
1168 >                    if (tabAt(tab, i) == f) {
1169 >                        Node<K,V> p = (fh >= 0 ? f :
1170 >                                       (f instanceof TreeBin) ?
1171 >                                       ((TreeBin<K,V>)f).first : null);
1172 >                        while (p != null) {
1173 >                            --delta;
1174 >                            p = p.next;
1175 >                        }
1176 >                        setTabAt(tab, i++, null);
1177 >                    }
1178 >                }
1179 >            }
1180 >        }
1181 >        if (delta != 0L)
1182 >            addCount(delta, -1);
1183 >    }
1184 >
1185 >    /**
1186 >     * Returns a {@link Set} view of the keys contained in this map.
1187 >     * The set is backed by the map, so changes to the map are
1188 >     * reflected in the set, and vice-versa. The set supports element
1189 >     * removal, which removes the corresponding mapping from this map,
1190 >     * via the {@code Iterator.remove}, {@code Set.remove},
1191 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1192 >     * operations.  It does not support the {@code add} or
1193 >     * {@code addAll} operations.
1194 >     *
1195 >     * <p>The view's iterators and spliterators are
1196 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1197 >     *
1198 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1199 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1200 >     *
1201 >     * @return the set view
1202 >     */
1203 >    public KeySetView<K,V> keySet() {
1204 >        KeySetView<K,V> ks;
1205 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1206 >    }
1207 >
1208 >    /**
1209 >     * Returns a {@link Collection} view of the values contained in this map.
1210 >     * The collection is backed by the map, so changes to the map are
1211 >     * reflected in the collection, and vice-versa.  The collection
1212 >     * supports element removal, which removes the corresponding
1213 >     * mapping from this map, via the {@code Iterator.remove},
1214 >     * {@code Collection.remove}, {@code removeAll},
1215 >     * {@code retainAll}, and {@code clear} operations.  It does not
1216 >     * support the {@code add} or {@code addAll} operations.
1217 >     *
1218 >     * <p>The view's iterators and spliterators are
1219 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1220 >     *
1221 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}
1222 >     * and {@link Spliterator#NONNULL}.
1223 >     *
1224 >     * @return the collection view
1225 >     */
1226 >    public Collection<V> values() {
1227 >        ValuesView<K,V> vs;
1228 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1229 >    }
1230 >
1231 >    /**
1232 >     * Returns a {@link Set} view of the mappings contained in this map.
1233 >     * The set is backed by the map, so changes to the map are
1234 >     * reflected in the set, and vice-versa.  The set supports element
1235 >     * removal, which removes the corresponding mapping from the map,
1236 >     * via the {@code Iterator.remove}, {@code Set.remove},
1237 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1238 >     * operations.
1239 >     *
1240 >     * <p>The view's iterators and spliterators are
1241 >     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1242 >     *
1243 >     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1244 >     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1245 >     *
1246 >     * @return the set view
1247 >     */
1248 >    public Set<Map.Entry<K,V>> entrySet() {
1249 >        EntrySetView<K,V> es;
1250 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1251 >    }
1252 >
1253 >    /**
1254 >     * Returns the hash code value for this {@link Map}, i.e.,
1255 >     * the sum of, for each key-value pair in the map,
1256 >     * {@code key.hashCode() ^ value.hashCode()}.
1257 >     *
1258 >     * @return the hash code value for this map
1259 >     */
1260 >    public int hashCode() {
1261 >        int h = 0;
1262 >        Node<K,V>[] t;
1263 >        if ((t = table) != null) {
1264 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1265 >            for (Node<K,V> p; (p = it.advance()) != null; )
1266 >                h += p.key.hashCode() ^ p.val.hashCode();
1267 >        }
1268 >        return h;
1269 >    }
1270 >
1271 >    /**
1272 >     * Returns a string representation of this map.  The string
1273 >     * representation consists of a list of key-value mappings (in no
1274 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1275 >     * mappings are separated by the characters {@code ", "} (comma
1276 >     * and space).  Each key-value mapping is rendered as the key
1277 >     * followed by an equals sign ("{@code =}") followed by the
1278 >     * associated value.
1279 >     *
1280 >     * @return a string representation of this map
1281 >     */
1282 >    public String toString() {
1283 >        Node<K,V>[] t;
1284 >        int f = (t = table) == null ? 0 : t.length;
1285 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1286 >        StringBuilder sb = new StringBuilder();
1287 >        sb.append('{');
1288 >        Node<K,V> p;
1289 >        if ((p = it.advance()) != null) {
1290 >            for (;;) {
1291 >                K k = p.key;
1292 >                V v = p.val;
1293 >                sb.append(k == this ? "(this Map)" : k);
1294 >                sb.append('=');
1295 >                sb.append(v == this ? "(this Map)" : v);
1296 >                if ((p = it.advance()) == null)
1297 >                    break;
1298 >                sb.append(',').append(' ');
1299 >            }
1300 >        }
1301 >        return sb.append('}').toString();
1302 >    }
1303 >
1304 >    /**
1305 >     * Compares the specified object with this map for equality.
1306 >     * Returns {@code true} if the given object is a map with the same
1307 >     * mappings as this map.  This operation may return misleading
1308 >     * results if either map is concurrently modified during execution
1309 >     * of this method.
1310 >     *
1311 >     * @param o object to be compared for equality with this map
1312 >     * @return {@code true} if the specified object is equal to this map
1313 >     */
1314 >    public boolean equals(Object o) {
1315 >        if (o != this) {
1316 >            if (!(o instanceof Map))
1317 >                return false;
1318 >            Map<?,?> m = (Map<?,?>) o;
1319 >            Node<K,V>[] t;
1320 >            int f = (t = table) == null ? 0 : t.length;
1321 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1322 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1323 >                V val = p.val;
1324 >                Object v = m.get(p.key);
1325 >                if (v == null || (v != val && !v.equals(val)))
1326 >                    return false;
1327 >            }
1328 >            for (Map.Entry<?,?> e : m.entrySet()) {
1329 >                Object mk, mv, v;
1330 >                if ((mk = e.getKey()) == null ||
1331 >                    (mv = e.getValue()) == null ||
1332 >                    (v = get(mk)) == null ||
1333 >                    (mv != v && !mv.equals(v)))
1334 >                    return false;
1335 >            }
1336 >        }
1337 >        return true;
1338 >    }
1339 >
1340 >    /**
1341 >     * Stripped-down version of helper class used in previous version,
1342 >     * declared for the sake of serialization compatibility
1343 >     */
1344 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1345 >        private static final long serialVersionUID = 2249069246763182397L;
1346 >        final float loadFactor;
1347 >        Segment(float lf) { this.loadFactor = lf; }
1348 >    }
1349 >
1350 >    /**
1351 >     * Saves the state of the {@code ConcurrentHashMap} instance to a
1352 >     * stream (i.e., serializes it).
1353 >     * @param s the stream
1354 >     * @throws java.io.IOException if an I/O error occurs
1355 >     * @serialData
1356 >     * the key (Object) and value (Object)
1357 >     * for each key-value mapping, followed by a null pair.
1358 >     * The key-value mappings are emitted in no particular order.
1359 >     */
1360 >    private void writeObject(java.io.ObjectOutputStream s)
1361 >        throws java.io.IOException {
1362 >        // For serialization compatibility
1363 >        // Emulate segment calculation from previous version of this class
1364 >        int sshift = 0;
1365 >        int ssize = 1;
1366 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1367 >            ++sshift;
1368 >            ssize <<= 1;
1369 >        }
1370 >        int segmentShift = 32 - sshift;
1371 >        int segmentMask = ssize - 1;
1372 >        @SuppressWarnings("unchecked")
1373 >        Segment<K,V>[] segments = (Segment<K,V>[])
1374 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1375 >        for (int i = 0; i < segments.length; ++i)
1376 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1377 >        java.io.ObjectOutputStream.PutField streamFields = s.putFields();
1378 >        streamFields.put("segments", segments);
1379 >        streamFields.put("segmentShift", segmentShift);
1380 >        streamFields.put("segmentMask", segmentMask);
1381 >        s.writeFields();
1382 >
1383 >        Node<K,V>[] t;
1384 >        if ((t = table) != null) {
1385 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1386 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1387 >                s.writeObject(p.key);
1388 >                s.writeObject(p.val);
1389 >            }
1390 >        }
1391 >        s.writeObject(null);
1392 >        s.writeObject(null);
1393 >        segments = null; // throw away
1394 >    }
1395 >
1396 >    /**
1397 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1398 >     * @param s the stream
1399 >     * @throws ClassNotFoundException if the class of a serialized object
1400 >     *         could not be found
1401 >     * @throws java.io.IOException if an I/O error occurs
1402 >     */
1403 >    private void readObject(java.io.ObjectInputStream s)
1404 >        throws java.io.IOException, ClassNotFoundException {
1405 >        /*
1406 >         * To improve performance in typical cases, we create nodes
1407 >         * while reading, then place in table once size is known.
1408 >         * However, we must also validate uniqueness and deal with
1409 >         * overpopulated bins while doing so, which requires
1410 >         * specialized versions of putVal mechanics.
1411 >         */
1412 >        sizeCtl = -1; // force exclusion for table construction
1413 >        s.defaultReadObject();
1414 >        long size = 0L;
1415 >        Node<K,V> p = null;
1416 >        for (;;) {
1417 >            @SuppressWarnings("unchecked")
1418 >            K k = (K) s.readObject();
1419 >            @SuppressWarnings("unchecked")
1420 >            V v = (V) s.readObject();
1421 >            if (k != null && v != null) {
1422 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1423 >                ++size;
1424 >            }
1425 >            else
1426 >                break;
1427 >        }
1428 >        if (size == 0L)
1429 >            sizeCtl = 0;
1430 >        else {
1431 >            int n;
1432 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1433 >                n = MAXIMUM_CAPACITY;
1434 >            else {
1435 >                int sz = (int)size;
1436 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1437 >            }
1438 >            @SuppressWarnings("unchecked")
1439 >            Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1440 >            int mask = n - 1;
1441 >            long added = 0L;
1442 >            while (p != null) {
1443 >                boolean insertAtFront;
1444 >                Node<K,V> next = p.next, first;
1445 >                int h = p.hash, j = h & mask;
1446 >                if ((first = tabAt(tab, j)) == null)
1447 >                    insertAtFront = true;
1448 >                else {
1449 >                    K k = p.key;
1450 >                    if (first.hash < 0) {
1451 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1452 >                        if (t.putTreeVal(h, k, p.val) == null)
1453 >                            ++added;
1454 >                        insertAtFront = false;
1455 >                    }
1456 >                    else {
1457 >                        int binCount = 0;
1458 >                        insertAtFront = true;
1459 >                        Node<K,V> q; K qk;
1460 >                        for (q = first; q != null; q = q.next) {
1461 >                            if (q.hash == h &&
1462 >                                ((qk = q.key) == k ||
1463 >                                 (qk != null && k.equals(qk)))) {
1464 >                                insertAtFront = false;
1465 >                                break;
1466 >                            }
1467 >                            ++binCount;
1468 >                        }
1469 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1470 >                            insertAtFront = false;
1471 >                            ++added;
1472 >                            p.next = first;
1473 >                            TreeNode<K,V> hd = null, tl = null;
1474 >                            for (q = p; q != null; q = q.next) {
1475 >                                TreeNode<K,V> t = new TreeNode<K,V>
1476 >                                    (q.hash, q.key, q.val, null, null);
1477 >                                if ((t.prev = tl) == null)
1478 >                                    hd = t;
1479 >                                else
1480 >                                    tl.next = t;
1481 >                                tl = t;
1482 >                            }
1483 >                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1484 >                        }
1485 >                    }
1486 >                }
1487 >                if (insertAtFront) {
1488 >                    ++added;
1489 >                    p.next = first;
1490 >                    setTabAt(tab, j, p);
1491 >                }
1492 >                p = next;
1493 >            }
1494 >            table = tab;
1495 >            sizeCtl = n - (n >>> 2);
1496 >            baseCount = added;
1497 >        }
1498 >    }
1499 >
1500 >    // ConcurrentMap methods
1501 >
1502 >    /**
1503 >     * {@inheritDoc}
1504 >     *
1505 >     * @return the previous value associated with the specified key,
1506 >     *         or {@code null} if there was no mapping for the key
1507 >     * @throws NullPointerException if the specified key or value is null
1508 >     */
1509 >    public V putIfAbsent(K key, V value) {
1510 >        return putVal(key, value, true);
1511 >    }
1512 >
1513 >    /**
1514 >     * {@inheritDoc}
1515 >     *
1516 >     * @throws NullPointerException if the specified key is null
1517 >     */
1518 >    public boolean remove(Object key, Object value) {
1519 >        if (key == null)
1520              throw new NullPointerException();
1521 <        return (V)internalPut(key, value);
1521 >        return value != null && replaceNode(key, null, value) != null;
1522 >    }
1523 >
1524 >    /**
1525 >     * {@inheritDoc}
1526 >     *
1527 >     * @throws NullPointerException if any of the arguments are null
1528 >     */
1529 >    public boolean replace(K key, V oldValue, V newValue) {
1530 >        if (key == null || oldValue == null || newValue == null)
1531 >            throw new NullPointerException();
1532 >        return replaceNode(key, newValue, oldValue) != null;
1533      }
1534  
1535      /**
# Line 2741 | Line 1539 | public class ConcurrentHashMap<K, V>
1539       *         or {@code null} if there was no mapping for the key
1540       * @throws NullPointerException if the specified key or value is null
1541       */
1542 <    @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) {
1542 >    public V replace(K key, V value) {
1543          if (key == null || value == null)
1544              throw new NullPointerException();
1545 <        return (V)internalPutIfAbsent(key, value);
1545 >        return replaceNode(key, value, null);
1546      }
1547  
1548 +    // Overrides of JDK8+ Map extension method defaults
1549 +
1550      /**
1551 <     * Copies all of the mappings from the specified map to this one.
1552 <     * These mappings replace any mappings that this map had for any of the
1553 <     * keys currently in the specified map.
1551 >     * Returns the value to which the specified key is mapped, or the
1552 >     * given default value if this map contains no mapping for the
1553 >     * key.
1554       *
1555 <     * @param m mappings to be stored in this map
1555 >     * @param key the key whose associated value is to be returned
1556 >     * @param defaultValue the value to return if this map contains
1557 >     * no mapping for the given key
1558 >     * @return the mapping for the key, if present; else the default value
1559 >     * @throws NullPointerException if the specified key is null
1560       */
1561 <    public void putAll(Map<? extends K, ? extends V> m) {
1562 <        internalPutAll(m);
1561 >    public V getOrDefault(Object key, V defaultValue) {
1562 >        V v;
1563 >        return (v = get(key)) == null ? defaultValue : v;
1564 >    }
1565 >
1566 >    public void forEach(BiConsumer<? super K, ? super V> action) {
1567 >        if (action == null) throw new NullPointerException();
1568 >        Node<K,V>[] t;
1569 >        if ((t = table) != null) {
1570 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1571 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1572 >                action.accept(p.key, p.val);
1573 >            }
1574 >        }
1575 >    }
1576 >
1577 >    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1578 >        if (function == null) throw new NullPointerException();
1579 >        Node<K,V>[] t;
1580 >        if ((t = table) != null) {
1581 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1582 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1583 >                V oldValue = p.val;
1584 >                for (K key = p.key;;) {
1585 >                    V newValue = function.apply(key, oldValue);
1586 >                    if (newValue == null)
1587 >                        throw new NullPointerException();
1588 >                    if (replaceNode(key, newValue, oldValue) != null ||
1589 >                        (oldValue = get(key)) == null)
1590 >                        break;
1591 >                }
1592 >            }
1593 >        }
1594 >    }
1595 >
1596 >    /**
1597 >     * Helper method for EntrySetView.removeIf
1598 >     */
1599 >    boolean removeEntryIf(Predicate<? super Entry<K,V>> function) {
1600 >        if (function == null) throw new NullPointerException();
1601 >        Node<K,V>[] t;
1602 >        boolean removed = false;
1603 >        if ((t = table) != null) {
1604 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1605 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1606 >                K k = p.key;
1607 >                V v = p.val;
1608 >                Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v);
1609 >                if (function.test(e) && replaceNode(k, null, v) != null)
1610 >                    removed = true;
1611 >            }
1612 >        }
1613 >        return removed;
1614 >    }
1615 >
1616 >    /**
1617 >     * Helper method for ValuesView.removeIf
1618 >     */
1619 >    boolean removeValueIf(Predicate<? super V> function) {
1620 >        if (function == null) throw new NullPointerException();
1621 >        Node<K,V>[] t;
1622 >        boolean removed = false;
1623 >        if ((t = table) != null) {
1624 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1625 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1626 >                K k = p.key;
1627 >                V v = p.val;
1628 >                if (function.test(v) && replaceNode(k, null, v) != null)
1629 >                    removed = true;
1630 >            }
1631 >        }
1632 >        return removed;
1633      }
1634  
1635      /**
1636       * If the specified key is not already associated with a value,
1637 <     * computes its value using the given mappingFunction and enters
1638 <     * it into the map unless null.  This is equivalent to
1639 <     * <pre> {@code
1640 <     * if (map.containsKey(key))
1641 <     *   return map.get(key);
1642 <     * value = mappingFunction.apply(key);
1643 <     * 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>
1637 >     * attempts to compute its value using the given mapping function
1638 >     * and enters it into this map unless {@code null}.  The entire
1639 >     * method invocation is performed atomically, so the function is
1640 >     * applied at most once per key.  Some attempted update operations
1641 >     * on this map by other threads may be blocked while computation
1642 >     * is in progress, so the computation should be short and simple,
1643 >     * and must not attempt to update any other mappings of this map.
1644       *
1645       * @param key key with which the specified value is to be associated
1646       * @param mappingFunction the function to compute a value
# Line 2797 | Line 1654 | public class ConcurrentHashMap<K, V>
1654       * @throws RuntimeException or Error if the mappingFunction does so,
1655       *         in which case the mapping is left unestablished
1656       */
1657 <    @SuppressWarnings("unchecked") public V computeIfAbsent
2801 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
1657 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1658          if (key == null || mappingFunction == null)
1659              throw new NullPointerException();
1660 <        return (V)internalComputeIfAbsent(key, mappingFunction);
1660 >        int h = spread(key.hashCode());
1661 >        V val = null;
1662 >        int binCount = 0;
1663 >        for (Node<K,V>[] tab = table;;) {
1664 >            Node<K,V> f; int n, i, fh;
1665 >            if (tab == null || (n = tab.length) == 0)
1666 >                tab = initTable();
1667 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1668 >                Node<K,V> r = new ReservationNode<K,V>();
1669 >                synchronized (r) {
1670 >                    if (casTabAt(tab, i, null, r)) {
1671 >                        binCount = 1;
1672 >                        Node<K,V> node = null;
1673 >                        try {
1674 >                            if ((val = mappingFunction.apply(key)) != null)
1675 >                                node = new Node<K,V>(h, key, val, null);
1676 >                        } finally {
1677 >                            setTabAt(tab, i, node);
1678 >                        }
1679 >                    }
1680 >                }
1681 >                if (binCount != 0)
1682 >                    break;
1683 >            }
1684 >            else if ((fh = f.hash) == MOVED)
1685 >                tab = helpTransfer(tab, f);
1686 >            else {
1687 >                boolean added = false;
1688 >                synchronized (f) {
1689 >                    if (tabAt(tab, i) == f) {
1690 >                        if (fh >= 0) {
1691 >                            binCount = 1;
1692 >                            for (Node<K,V> e = f;; ++binCount) {
1693 >                                K ek;
1694 >                                if (e.hash == h &&
1695 >                                    ((ek = e.key) == key ||
1696 >                                     (ek != null && key.equals(ek)))) {
1697 >                                    val = e.val;
1698 >                                    break;
1699 >                                }
1700 >                                Node<K,V> pred = e;
1701 >                                if ((e = e.next) == null) {
1702 >                                    if ((val = mappingFunction.apply(key)) != null) {
1703 >                                        if (pred.next != null)
1704 >                                            throw new IllegalStateException("Recursive update");
1705 >                                        added = true;
1706 >                                        pred.next = new Node<K,V>(h, key, val, null);
1707 >                                    }
1708 >                                    break;
1709 >                                }
1710 >                            }
1711 >                        }
1712 >                        else if (f instanceof TreeBin) {
1713 >                            binCount = 2;
1714 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1715 >                            TreeNode<K,V> r, p;
1716 >                            if ((r = t.root) != null &&
1717 >                                (p = r.findTreeNode(h, key, null)) != null)
1718 >                                val = p.val;
1719 >                            else if ((val = mappingFunction.apply(key)) != null) {
1720 >                                added = true;
1721 >                                t.putTreeVal(h, key, val);
1722 >                            }
1723 >                        }
1724 >                        else if (f instanceof ReservationNode)
1725 >                            throw new IllegalStateException("Recursive update");
1726 >                    }
1727 >                }
1728 >                if (binCount != 0) {
1729 >                    if (binCount >= TREEIFY_THRESHOLD)
1730 >                        treeifyBin(tab, i);
1731 >                    if (!added)
1732 >                        return val;
1733 >                    break;
1734 >                }
1735 >            }
1736 >        }
1737 >        if (val != null)
1738 >            addCount(1L, binCount);
1739 >        return val;
1740      }
1741  
1742      /**
1743 <     * If the given key is present, computes a new mapping value given a key and
1744 <     * its current mapped value. This is equivalent to
1745 <     *  <pre> {@code
1746 <     *   if (map.containsKey(key)) {
1747 <     *     value = remappingFunction.apply(key, map.get(key));
1748 <     *     if (value != null)
1749 <     *       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:
1743 >     * If the value for the specified key is present, attempts to
1744 >     * compute a new mapping given the key and its current mapped
1745 >     * value.  The entire method invocation is performed atomically.
1746 >     * Some attempted update operations on this map by other threads
1747 >     * may be blocked while computation is in progress, so the
1748 >     * computation should be short and simple, and must not attempt to
1749 >     * update any other mappings of this map.
1750       *
1751 <     * @param key key with which the specified value is to be associated
1751 >     * @param key key with which a value may be associated
1752       * @param remappingFunction the function to compute a value
1753       * @return the new value associated with the specified key, or null if none
1754       * @throws NullPointerException if the specified key or remappingFunction
# Line 2838 | Line 1759 | public class ConcurrentHashMap<K, V>
1759       * @throws RuntimeException or Error if the remappingFunction does so,
1760       *         in which case the mapping is unchanged
1761       */
1762 <    @SuppressWarnings("unchecked") public V computeIfPresent
2842 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1762 >    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1763          if (key == null || remappingFunction == null)
1764              throw new NullPointerException();
1765 <        return (V)internalCompute(key, true, remappingFunction);
1765 >        int h = spread(key.hashCode());
1766 >        V val = null;
1767 >        int delta = 0;
1768 >        int binCount = 0;
1769 >        for (Node<K,V>[] tab = table;;) {
1770 >            Node<K,V> f; int n, i, fh;
1771 >            if (tab == null || (n = tab.length) == 0)
1772 >                tab = initTable();
1773 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1774 >                break;
1775 >            else if ((fh = f.hash) == MOVED)
1776 >                tab = helpTransfer(tab, f);
1777 >            else {
1778 >                synchronized (f) {
1779 >                    if (tabAt(tab, i) == f) {
1780 >                        if (fh >= 0) {
1781 >                            binCount = 1;
1782 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1783 >                                K ek;
1784 >                                if (e.hash == h &&
1785 >                                    ((ek = e.key) == key ||
1786 >                                     (ek != null && key.equals(ek)))) {
1787 >                                    val = remappingFunction.apply(key, e.val);
1788 >                                    if (val != null)
1789 >                                        e.val = val;
1790 >                                    else {
1791 >                                        delta = -1;
1792 >                                        Node<K,V> en = e.next;
1793 >                                        if (pred != null)
1794 >                                            pred.next = en;
1795 >                                        else
1796 >                                            setTabAt(tab, i, en);
1797 >                                    }
1798 >                                    break;
1799 >                                }
1800 >                                pred = e;
1801 >                                if ((e = e.next) == null)
1802 >                                    break;
1803 >                            }
1804 >                        }
1805 >                        else if (f instanceof TreeBin) {
1806 >                            binCount = 2;
1807 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1808 >                            TreeNode<K,V> r, p;
1809 >                            if ((r = t.root) != null &&
1810 >                                (p = r.findTreeNode(h, key, null)) != null) {
1811 >                                val = remappingFunction.apply(key, p.val);
1812 >                                if (val != null)
1813 >                                    p.val = val;
1814 >                                else {
1815 >                                    delta = -1;
1816 >                                    if (t.removeTreeNode(p))
1817 >                                        setTabAt(tab, i, untreeify(t.first));
1818 >                                }
1819 >                            }
1820 >                        }
1821 >                        else if (f instanceof ReservationNode)
1822 >                            throw new IllegalStateException("Recursive update");
1823 >                    }
1824 >                }
1825 >                if (binCount != 0)
1826 >                    break;
1827 >            }
1828 >        }
1829 >        if (delta != 0)
1830 >            addCount((long)delta, binCount);
1831 >        return val;
1832      }
1833  
1834      /**
1835 <     * Computes a new mapping value given a key and
1836 <     * its current mapped value (or {@code null} if there is no current
1837 <     * mapping). This is equivalent to
1838 <     *  <pre> {@code
1839 <     *   value = remappingFunction.apply(key, map.get(key));
1840 <     *   if (value != null)
1841 <     *     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>
1835 >     * Attempts to compute a mapping for the specified key and its
1836 >     * current mapped value (or {@code null} if there is no current
1837 >     * mapping). The entire method invocation is performed atomically.
1838 >     * Some attempted update operations on this map by other threads
1839 >     * may be blocked while computation is in progress, so the
1840 >     * computation should be short and simple, and must not attempt to
1841 >     * update any other mappings of this Map.
1842       *
1843       * @param key key with which the specified value is to be associated
1844       * @param remappingFunction the function to compute a value
# Line 2885 | Line 1851 | public class ConcurrentHashMap<K, V>
1851       * @throws RuntimeException or Error if the remappingFunction does so,
1852       *         in which case the mapping is unchanged
1853       */
1854 <    @SuppressWarnings("unchecked") public V compute
1855 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1854 >    public V compute(K key,
1855 >                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1856          if (key == null || remappingFunction == null)
1857              throw new NullPointerException();
1858 <        return (V)internalCompute(key, false, remappingFunction);
1858 >        int h = spread(key.hashCode());
1859 >        V val = null;
1860 >        int delta = 0;
1861 >        int binCount = 0;
1862 >        for (Node<K,V>[] tab = table;;) {
1863 >            Node<K,V> f; int n, i, fh;
1864 >            if (tab == null || (n = tab.length) == 0)
1865 >                tab = initTable();
1866 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1867 >                Node<K,V> r = new ReservationNode<K,V>();
1868 >                synchronized (r) {
1869 >                    if (casTabAt(tab, i, null, r)) {
1870 >                        binCount = 1;
1871 >                        Node<K,V> node = null;
1872 >                        try {
1873 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1874 >                                delta = 1;
1875 >                                node = new Node<K,V>(h, key, val, null);
1876 >                            }
1877 >                        } finally {
1878 >                            setTabAt(tab, i, node);
1879 >                        }
1880 >                    }
1881 >                }
1882 >                if (binCount != 0)
1883 >                    break;
1884 >            }
1885 >            else if ((fh = f.hash) == MOVED)
1886 >                tab = helpTransfer(tab, f);
1887 >            else {
1888 >                synchronized (f) {
1889 >                    if (tabAt(tab, i) == f) {
1890 >                        if (fh >= 0) {
1891 >                            binCount = 1;
1892 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1893 >                                K ek;
1894 >                                if (e.hash == h &&
1895 >                                    ((ek = e.key) == key ||
1896 >                                     (ek != null && key.equals(ek)))) {
1897 >                                    val = remappingFunction.apply(key, e.val);
1898 >                                    if (val != null)
1899 >                                        e.val = val;
1900 >                                    else {
1901 >                                        delta = -1;
1902 >                                        Node<K,V> en = e.next;
1903 >                                        if (pred != null)
1904 >                                            pred.next = en;
1905 >                                        else
1906 >                                            setTabAt(tab, i, en);
1907 >                                    }
1908 >                                    break;
1909 >                                }
1910 >                                pred = e;
1911 >                                if ((e = e.next) == null) {
1912 >                                    val = remappingFunction.apply(key, null);
1913 >                                    if (val != null) {
1914 >                                        if (pred.next != null)
1915 >                                            throw new IllegalStateException("Recursive update");
1916 >                                        delta = 1;
1917 >                                        pred.next =
1918 >                                            new Node<K,V>(h, key, val, null);
1919 >                                    }
1920 >                                    break;
1921 >                                }
1922 >                            }
1923 >                        }
1924 >                        else if (f instanceof TreeBin) {
1925 >                            binCount = 1;
1926 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1927 >                            TreeNode<K,V> r, p;
1928 >                            if ((r = t.root) != null)
1929 >                                p = r.findTreeNode(h, key, null);
1930 >                            else
1931 >                                p = null;
1932 >                            V pv = (p == null) ? null : p.val;
1933 >                            val = remappingFunction.apply(key, pv);
1934 >                            if (val != null) {
1935 >                                if (p != null)
1936 >                                    p.val = val;
1937 >                                else {
1938 >                                    delta = 1;
1939 >                                    t.putTreeVal(h, key, val);
1940 >                                }
1941 >                            }
1942 >                            else if (p != null) {
1943 >                                delta = -1;
1944 >                                if (t.removeTreeNode(p))
1945 >                                    setTabAt(tab, i, untreeify(t.first));
1946 >                            }
1947 >                        }
1948 >                        else if (f instanceof ReservationNode)
1949 >                            throw new IllegalStateException("Recursive update");
1950 >                    }
1951 >                }
1952 >                if (binCount != 0) {
1953 >                    if (binCount >= TREEIFY_THRESHOLD)
1954 >                        treeifyBin(tab, i);
1955 >                    break;
1956 >                }
1957 >            }
1958 >        }
1959 >        if (delta != 0)
1960 >            addCount((long)delta, binCount);
1961 >        return val;
1962      }
1963  
1964      /**
1965 <     * If the specified key is not already associated
1966 <     * with a value, associate it with the given value.
1967 <     * Otherwise, replace the value with the results of
1968 <     * the given remapping function. This is equivalent to:
1969 <     *  <pre> {@code
1970 <     *   if (!map.containsKey(key))
1971 <     *     map.put(value);
1972 <     *   else {
1973 <     *     newValue = remappingFunction.apply(map.get(key), value);
1974 <     *     if (value != null)
1975 <     *       map.put(key, value);
1976 <     *     else
1977 <     *       map.remove(key);
1978 <     *   }
1979 <     * }</pre>
1980 <     * except that the action is performed atomically.  If the
1981 <     * function returns {@code null}, the mapping is removed.  If the
1982 <     * 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.
1965 >     * If the specified key is not already associated with a
1966 >     * (non-null) value, associates it with the given value.
1967 >     * Otherwise, replaces the value with the results of the given
1968 >     * remapping function, or removes if {@code null}. The entire
1969 >     * method invocation is performed atomically.  Some attempted
1970 >     * update operations on this map by other threads may be blocked
1971 >     * while computation is in progress, so the computation should be
1972 >     * short and simple, and must not attempt to update any other
1973 >     * mappings of this Map.
1974 >     *
1975 >     * @param key key with which the specified value is to be associated
1976 >     * @param value the value to use if absent
1977 >     * @param remappingFunction the function to recompute a value if present
1978 >     * @return the new value associated with the specified key, or null if none
1979 >     * @throws NullPointerException if the specified key or the
1980 >     *         remappingFunction is null
1981 >     * @throws RuntimeException or Error if the remappingFunction does so,
1982 >     *         in which case the mapping is unchanged
1983       */
1984 <    @SuppressWarnings("unchecked") public V merge
2921 <        (K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1984 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1985          if (key == null || value == null || remappingFunction == null)
1986              throw new NullPointerException();
1987 <        return (V)internalMerge(key, value, remappingFunction);
1987 >        int h = spread(key.hashCode());
1988 >        V val = null;
1989 >        int delta = 0;
1990 >        int binCount = 0;
1991 >        for (Node<K,V>[] tab = table;;) {
1992 >            Node<K,V> f; int n, i, fh;
1993 >            if (tab == null || (n = tab.length) == 0)
1994 >                tab = initTable();
1995 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1996 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1997 >                    delta = 1;
1998 >                    val = value;
1999 >                    break;
2000 >                }
2001 >            }
2002 >            else if ((fh = f.hash) == MOVED)
2003 >                tab = helpTransfer(tab, f);
2004 >            else {
2005 >                synchronized (f) {
2006 >                    if (tabAt(tab, i) == f) {
2007 >                        if (fh >= 0) {
2008 >                            binCount = 1;
2009 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
2010 >                                K ek;
2011 >                                if (e.hash == h &&
2012 >                                    ((ek = e.key) == key ||
2013 >                                     (ek != null && key.equals(ek)))) {
2014 >                                    val = remappingFunction.apply(e.val, value);
2015 >                                    if (val != null)
2016 >                                        e.val = val;
2017 >                                    else {
2018 >                                        delta = -1;
2019 >                                        Node<K,V> en = e.next;
2020 >                                        if (pred != null)
2021 >                                            pred.next = en;
2022 >                                        else
2023 >                                            setTabAt(tab, i, en);
2024 >                                    }
2025 >                                    break;
2026 >                                }
2027 >                                pred = e;
2028 >                                if ((e = e.next) == null) {
2029 >                                    delta = 1;
2030 >                                    val = value;
2031 >                                    pred.next =
2032 >                                        new Node<K,V>(h, key, val, null);
2033 >                                    break;
2034 >                                }
2035 >                            }
2036 >                        }
2037 >                        else if (f instanceof TreeBin) {
2038 >                            binCount = 2;
2039 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2040 >                            TreeNode<K,V> r = t.root;
2041 >                            TreeNode<K,V> p = (r == null) ? null :
2042 >                                r.findTreeNode(h, key, null);
2043 >                            val = (p == null) ? value :
2044 >                                remappingFunction.apply(p.val, value);
2045 >                            if (val != null) {
2046 >                                if (p != null)
2047 >                                    p.val = val;
2048 >                                else {
2049 >                                    delta = 1;
2050 >                                    t.putTreeVal(h, key, val);
2051 >                                }
2052 >                            }
2053 >                            else if (p != null) {
2054 >                                delta = -1;
2055 >                                if (t.removeTreeNode(p))
2056 >                                    setTabAt(tab, i, untreeify(t.first));
2057 >                            }
2058 >                        }
2059 >                        else if (f instanceof ReservationNode)
2060 >                            throw new IllegalStateException("Recursive update");
2061 >                    }
2062 >                }
2063 >                if (binCount != 0) {
2064 >                    if (binCount >= TREEIFY_THRESHOLD)
2065 >                        treeifyBin(tab, i);
2066 >                    break;
2067 >                }
2068 >            }
2069 >        }
2070 >        if (delta != 0)
2071 >            addCount((long)delta, binCount);
2072 >        return val;
2073      }
2074  
2075 +    // Hashtable legacy methods
2076 +
2077      /**
2078 <     * Removes the key (and its corresponding value) from this map.
2929 <     * This method does nothing if the key is not in the map.
2078 >     * Tests if some key maps into the specified value in this table.
2079       *
2080 <     * @param  key the key that needs to be removed
2081 <     * @return the previous value associated with {@code key}, or
2082 <     *         {@code null} if there was no mapping for {@code key}
2083 <     * @throws NullPointerException if the specified key is null
2080 >     * <p>Note that this method is identical in functionality to
2081 >     * {@link #containsValue(Object)}, and exists solely to ensure
2082 >     * full compatibility with class {@link java.util.Hashtable},
2083 >     * which supported this method prior to introduction of the
2084 >     * Java Collections Framework.
2085 >     *
2086 >     * @param  value a value to search for
2087 >     * @return {@code true} if and only if some key maps to the
2088 >     *         {@code value} argument in this table as
2089 >     *         determined by the {@code equals} method;
2090 >     *         {@code false} otherwise
2091 >     * @throws NullPointerException if the specified value is null
2092       */
2093 <    @SuppressWarnings("unchecked") public V remove(Object key) {
2094 <        if (key == null)
2938 <            throw new NullPointerException();
2939 <        return (V)internalReplace(key, null, null);
2093 >    public boolean contains(Object value) {
2094 >        return containsValue(value);
2095      }
2096  
2097      /**
2098 <     * {@inheritDoc}
2098 >     * Returns an enumeration of the keys in this table.
2099       *
2100 <     * @throws NullPointerException if the specified key is null
2100 >     * @return an enumeration of the keys in this table
2101 >     * @see #keySet()
2102       */
2103 <    public boolean remove(Object key, Object value) {
2104 <        if (key == null)
2105 <            throw new NullPointerException();
2106 <        if (value == null)
2951 <            return false;
2952 <        return internalReplace(key, null, value) != null;
2103 >    public Enumeration<K> keys() {
2104 >        Node<K,V>[] t;
2105 >        int f = (t = table) == null ? 0 : t.length;
2106 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2107      }
2108  
2109      /**
2110 <     * {@inheritDoc}
2110 >     * Returns an enumeration of the values in this table.
2111       *
2112 <     * @throws NullPointerException if any of the arguments are null
2112 >     * @return an enumeration of the values in this table
2113 >     * @see #values()
2114       */
2115 <    public boolean replace(K key, V oldValue, V newValue) {
2116 <        if (key == null || oldValue == null || newValue == null)
2117 <            throw new NullPointerException();
2118 <        return internalReplace(key, newValue, oldValue) != null;
2115 >    public Enumeration<V> elements() {
2116 >        Node<K,V>[] t;
2117 >        int f = (t = table) == null ? 0 : t.length;
2118 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2119      }
2120  
2121 +    // ConcurrentHashMap-only methods
2122 +
2123      /**
2124 <     * {@inheritDoc}
2124 >     * Returns the number of mappings. This method should be used
2125 >     * instead of {@link #size} because a ConcurrentHashMap may
2126 >     * contain more mappings than can be represented as an int. The
2127 >     * value returned is an estimate; the actual count may differ if
2128 >     * there are concurrent insertions or removals.
2129       *
2130 <     * @return the previous value associated with the specified key,
2131 <     *         or {@code null} if there was no mapping for the key
2971 <     * @throws NullPointerException if the specified key or value is null
2130 >     * @return the number of mappings
2131 >     * @since 1.8
2132       */
2133 <    @SuppressWarnings("unchecked") public V replace(K key, V value) {
2134 <        if (key == null || value == null)
2135 <            throw new NullPointerException();
2976 <        return (V)internalReplace(key, value, null);
2133 >    public long mappingCount() {
2134 >        long n = sumCount();
2135 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2136      }
2137  
2138      /**
2139 <     * Removes all of the mappings from this map.
2139 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2140 >     * from the given type to {@code Boolean.TRUE}.
2141 >     *
2142 >     * @param <K> the element type of the returned set
2143 >     * @return the new set
2144 >     * @since 1.8
2145       */
2146 <    public void clear() {
2147 <        internalClear();
2146 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2147 >        return new KeySetView<K,Boolean>
2148 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2149      }
2150  
2151      /**
2152 <     * Returns a {@link Set} view of the keys contained in this map.
2153 <     * The set is backed by the map, so changes to the map are
2989 <     * reflected in the set, and vice-versa.
2152 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2153 >     * from the given type to {@code Boolean.TRUE}.
2154       *
2155 <     * @return the set view
2155 >     * @param initialCapacity The implementation performs internal
2156 >     * sizing to accommodate this many elements.
2157 >     * @param <K> the element type of the returned set
2158 >     * @return the new set
2159 >     * @throws IllegalArgumentException if the initial capacity of
2160 >     * elements is negative
2161 >     * @since 1.8
2162       */
2163 <    public KeySetView<K,V> keySet() {
2164 <        KeySetView<K,V> ks = keySet;
2165 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2163 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2164 >        return new KeySetView<K,Boolean>
2165 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2166      }
2167  
2168      /**
2169       * Returns a {@link Set} view of the keys in this map, using the
2170       * given common mapped value for any additions (i.e., {@link
2171 <     * Collection#add} and {@link Collection#addAll}). This is of
2172 <     * course only appropriate if it is acceptable to use the same
2173 <     * value for all additions from this view.
2171 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2172 >     * This is of course only appropriate if it is acceptable to use
2173 >     * the same value for all additions from this view.
2174       *
2175 <     * @param mappedValue the mapped value to use for any
3006 <     * additions.
2175 >     * @param mappedValue the mapped value to use for any additions
2176       * @return the set view
2177       * @throws NullPointerException if the mappedValue is null
2178       */
# Line 3013 | Line 2182 | public class ConcurrentHashMap<K, V>
2182          return new KeySetView<K,V>(this, mappedValue);
2183      }
2184  
2185 +    /* ---------------- Special Nodes -------------- */
2186 +
2187      /**
2188 <     * 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.
2188 >     * A node inserted at head of bins during transfer operations.
2189       */
2190 <    public ValuesView<K,V> values() {
2191 <        ValuesView<K,V> vs = values;
2192 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2190 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2191 >        final Node<K,V>[] nextTable;
2192 >        ForwardingNode(Node<K,V>[] tab) {
2193 >            super(MOVED, null, null, null);
2194 >            this.nextTable = tab;
2195 >        }
2196 >
2197 >        Node<K,V> find(int h, Object k) {
2198 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2199 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2200 >                Node<K,V> e; int n;
2201 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2202 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2203 >                    return null;
2204 >                for (;;) {
2205 >                    int eh; K ek;
2206 >                    if ((eh = e.hash) == h &&
2207 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2208 >                        return e;
2209 >                    if (eh < 0) {
2210 >                        if (e instanceof ForwardingNode) {
2211 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2212 >                            continue outer;
2213 >                        }
2214 >                        else
2215 >                            return e.find(h, k);
2216 >                    }
2217 >                    if ((e = e.next) == null)
2218 >                        return null;
2219 >                }
2220 >            }
2221 >        }
2222      }
2223  
2224      /**
2225 <     * 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.
2225 >     * A place-holder node used in computeIfAbsent and compute
2226       */
2227 <    public Set<Map.Entry<K,V>> entrySet() {
2228 <        EntrySetView<K,V> es = entrySet;
2229 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2227 >    static final class ReservationNode<K,V> extends Node<K,V> {
2228 >        ReservationNode() {
2229 >            super(RESERVED, null, null, null);
2230 >        }
2231 >
2232 >        Node<K,V> find(int h, Object k) {
2233 >            return null;
2234 >        }
2235      }
2236  
2237 +    /* ---------------- Table Initialization and Resizing -------------- */
2238 +
2239      /**
2240 <     * Returns an enumeration of the keys in this table.
2241 <     *
3050 <     * @return an enumeration of the keys in this table
3051 <     * @see #keySet()
2240 >     * Returns the stamp bits for resizing a table of size n.
2241 >     * Must be negative when shifted left by RESIZE_STAMP_SHIFT.
2242       */
2243 <    public Enumeration<K> keys() {
2244 <        return new KeyIterator<K,V>(this);
2243 >    static final int resizeStamp(int n) {
2244 >        return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
2245      }
2246  
2247      /**
2248 <     * Returns an enumeration of the values in this table.
3059 <     *
3060 <     * @return an enumeration of the values in this table
3061 <     * @see #values()
2248 >     * Initializes table, using the size recorded in sizeCtl.
2249       */
2250 <    public Enumeration<V> elements() {
2251 <        return new ValueIterator<K,V>(this);
2250 >    private final Node<K,V>[] initTable() {
2251 >        Node<K,V>[] tab; int sc;
2252 >        while ((tab = table) == null || tab.length == 0) {
2253 >            if ((sc = sizeCtl) < 0)
2254 >                Thread.yield(); // lost initialization race; just spin
2255 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2256 >                try {
2257 >                    if ((tab = table) == null || tab.length == 0) {
2258 >                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2259 >                        @SuppressWarnings("unchecked")
2260 >                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2261 >                        table = tab = nt;
2262 >                        sc = n - (n >>> 2);
2263 >                    }
2264 >                } finally {
2265 >                    sizeCtl = sc;
2266 >                }
2267 >                break;
2268 >            }
2269 >        }
2270 >        return tab;
2271      }
2272  
2273      /**
2274 <     * Returns a partitionable iterator of the keys in this map.
2275 <     *
2276 <     * @return a partitionable iterator of the keys in this map
2274 >     * Adds to count, and if table is too small and not already
2275 >     * resizing, initiates transfer. If already resizing, helps
2276 >     * perform transfer if work is available.  Rechecks occupancy
2277 >     * after a transfer to see if another resize is already needed
2278 >     * because resizings are lagging additions.
2279 >     *
2280 >     * @param x the count to add
2281 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
2282 >     */
2283 >    private final void addCount(long x, int check) {
2284 >        CounterCell[] as; long b, s;
2285 >        if ((as = counterCells) != null ||
2286 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2287 >            CounterCell a; long v; int m;
2288 >            boolean uncontended = true;
2289 >            if (as == null || (m = as.length - 1) < 0 ||
2290 >                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
2291 >                !(uncontended =
2292 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2293 >                fullAddCount(x, uncontended);
2294 >                return;
2295 >            }
2296 >            if (check <= 1)
2297 >                return;
2298 >            s = sumCount();
2299 >        }
2300 >        if (check >= 0) {
2301 >            Node<K,V>[] tab, nt; int n, sc;
2302 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2303 >                   (n = tab.length) < MAXIMUM_CAPACITY) {
2304 >                int rs = resizeStamp(n);
2305 >                if (sc < 0) {
2306 >                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2307 >                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
2308 >                        transferIndex <= 0)
2309 >                        break;
2310 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
2311 >                        transfer(tab, nt);
2312 >                }
2313 >                else if (U.compareAndSwapInt(this, SIZECTL, sc,
2314 >                                             (rs << RESIZE_STAMP_SHIFT) + 2))
2315 >                    transfer(tab, null);
2316 >                s = sumCount();
2317 >            }
2318 >        }
2319 >    }
2320 >
2321 >    /**
2322 >     * Helps transfer if a resize is in progress.
2323       */
2324 <    public Spliterator<K> keySpliterator() {
2325 <        return new KeyIterator<K,V>(this);
2324 >    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2325 >        Node<K,V>[] nextTab; int sc;
2326 >        if (tab != null && (f instanceof ForwardingNode) &&
2327 >            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2328 >            int rs = resizeStamp(tab.length);
2329 >            while (nextTab == nextTable && table == tab &&
2330 >                   (sc = sizeCtl) < 0) {
2331 >                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2332 >                    sc == rs + MAX_RESIZERS || transferIndex <= 0)
2333 >                    break;
2334 >                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
2335 >                    transfer(tab, nextTab);
2336 >                    break;
2337 >                }
2338 >            }
2339 >            return nextTab;
2340 >        }
2341 >        return table;
2342      }
2343  
2344      /**
2345 <     * Returns a partitionable iterator of the values in this map.
2345 >     * Tries to presize table to accommodate the given number of elements.
2346       *
2347 <     * @return a partitionable iterator of the values in this map
2347 >     * @param size number of elements (doesn't need to be perfectly accurate)
2348       */
2349 <    public Spliterator<V> valueSpliterator() {
2350 <        return new ValueIterator<K,V>(this);
2349 >    private final void tryPresize(int size) {
2350 >        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2351 >            tableSizeFor(size + (size >>> 1) + 1);
2352 >        int sc;
2353 >        while ((sc = sizeCtl) >= 0) {
2354 >            Node<K,V>[] tab = table; int n;
2355 >            if (tab == null || (n = tab.length) == 0) {
2356 >                n = (sc > c) ? sc : c;
2357 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2358 >                    try {
2359 >                        if (table == tab) {
2360 >                            @SuppressWarnings("unchecked")
2361 >                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2362 >                            table = nt;
2363 >                            sc = n - (n >>> 2);
2364 >                        }
2365 >                    } finally {
2366 >                        sizeCtl = sc;
2367 >                    }
2368 >                }
2369 >            }
2370 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
2371 >                break;
2372 >            else if (tab == table) {
2373 >                int rs = resizeStamp(n);
2374 >                if (U.compareAndSwapInt(this, SIZECTL, sc,
2375 >                                        (rs << RESIZE_STAMP_SHIFT) + 2))
2376 >                    transfer(tab, null);
2377 >            }
2378 >        }
2379      }
2380  
2381      /**
2382 <     * Returns a partitionable iterator of the entries in this map.
2383 <     *
3088 <     * @return a partitionable iterator of the entries in this map
2382 >     * Moves and/or copies the nodes in each bin to new table. See
2383 >     * above for explanation.
2384       */
2385 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
2386 <        return new EntryIterator<K,V>(this);
2385 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2386 >        int n = tab.length, stride;
2387 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2388 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
2389 >        if (nextTab == null) {            // initiating
2390 >            try {
2391 >                @SuppressWarnings("unchecked")
2392 >                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
2393 >                nextTab = nt;
2394 >            } catch (Throwable ex) {      // try to cope with OOME
2395 >                sizeCtl = Integer.MAX_VALUE;
2396 >                return;
2397 >            }
2398 >            nextTable = nextTab;
2399 >            transferIndex = n;
2400 >        }
2401 >        int nextn = nextTab.length;
2402 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2403 >        boolean advance = true;
2404 >        boolean finishing = false; // to ensure sweep before committing nextTab
2405 >        for (int i = 0, bound = 0;;) {
2406 >            Node<K,V> f; int fh;
2407 >            while (advance) {
2408 >                int nextIndex, nextBound;
2409 >                if (--i >= bound || finishing)
2410 >                    advance = false;
2411 >                else if ((nextIndex = transferIndex) <= 0) {
2412 >                    i = -1;
2413 >                    advance = false;
2414 >                }
2415 >                else if (U.compareAndSwapInt
2416 >                         (this, TRANSFERINDEX, nextIndex,
2417 >                          nextBound = (nextIndex > stride ?
2418 >                                       nextIndex - stride : 0))) {
2419 >                    bound = nextBound;
2420 >                    i = nextIndex - 1;
2421 >                    advance = false;
2422 >                }
2423 >            }
2424 >            if (i < 0 || i >= n || i + n >= nextn) {
2425 >                int sc;
2426 >                if (finishing) {
2427 >                    nextTable = null;
2428 >                    table = nextTab;
2429 >                    sizeCtl = (n << 1) - (n >>> 1);
2430 >                    return;
2431 >                }
2432 >                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
2433 >                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
2434 >                        return;
2435 >                    finishing = advance = true;
2436 >                    i = n; // recheck before commit
2437 >                }
2438 >            }
2439 >            else if ((f = tabAt(tab, i)) == null)
2440 >                advance = casTabAt(tab, i, null, fwd);
2441 >            else if ((fh = f.hash) == MOVED)
2442 >                advance = true; // already processed
2443 >            else {
2444 >                synchronized (f) {
2445 >                    if (tabAt(tab, i) == f) {
2446 >                        Node<K,V> ln, hn;
2447 >                        if (fh >= 0) {
2448 >                            int runBit = fh & n;
2449 >                            Node<K,V> lastRun = f;
2450 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2451 >                                int b = p.hash & n;
2452 >                                if (b != runBit) {
2453 >                                    runBit = b;
2454 >                                    lastRun = p;
2455 >                                }
2456 >                            }
2457 >                            if (runBit == 0) {
2458 >                                ln = lastRun;
2459 >                                hn = null;
2460 >                            }
2461 >                            else {
2462 >                                hn = lastRun;
2463 >                                ln = null;
2464 >                            }
2465 >                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2466 >                                int ph = p.hash; K pk = p.key; V pv = p.val;
2467 >                                if ((ph & n) == 0)
2468 >                                    ln = new Node<K,V>(ph, pk, pv, ln);
2469 >                                else
2470 >                                    hn = new Node<K,V>(ph, pk, pv, hn);
2471 >                            }
2472 >                            setTabAt(nextTab, i, ln);
2473 >                            setTabAt(nextTab, i + n, hn);
2474 >                            setTabAt(tab, i, fwd);
2475 >                            advance = true;
2476 >                        }
2477 >                        else if (f instanceof TreeBin) {
2478 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2479 >                            TreeNode<K,V> lo = null, loTail = null;
2480 >                            TreeNode<K,V> hi = null, hiTail = null;
2481 >                            int lc = 0, hc = 0;
2482 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2483 >                                int h = e.hash;
2484 >                                TreeNode<K,V> p = new TreeNode<K,V>
2485 >                                    (h, e.key, e.val, null, null);
2486 >                                if ((h & n) == 0) {
2487 >                                    if ((p.prev = loTail) == null)
2488 >                                        lo = p;
2489 >                                    else
2490 >                                        loTail.next = p;
2491 >                                    loTail = p;
2492 >                                    ++lc;
2493 >                                }
2494 >                                else {
2495 >                                    if ((p.prev = hiTail) == null)
2496 >                                        hi = p;
2497 >                                    else
2498 >                                        hiTail.next = p;
2499 >                                    hiTail = p;
2500 >                                    ++hc;
2501 >                                }
2502 >                            }
2503 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2504 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2505 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2506 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2507 >                            setTabAt(nextTab, i, ln);
2508 >                            setTabAt(nextTab, i + n, hn);
2509 >                            setTabAt(tab, i, fwd);
2510 >                            advance = true;
2511 >                        }
2512 >                    }
2513 >                }
2514 >            }
2515 >        }
2516      }
2517  
2518 +    /* ---------------- Counter support -------------- */
2519 +
2520      /**
2521 <     * Returns the hash code value for this {@link Map}, i.e.,
2522 <     * 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
2521 >     * A padded cell for distributing counts.  Adapted from LongAdder
2522 >     * and Striped64.  See their internal docs for explanation.
2523       */
2524 <    public int hashCode() {
2525 <        int h = 0;
2526 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2527 <        Object v;
2528 <        while ((v = it.advance()) != null) {
2529 <            h += it.nextKey.hashCode() ^ v.hashCode();
2524 >    @sun.misc.Contended static final class CounterCell {
2525 >        volatile long value;
2526 >        CounterCell(long x) { value = x; }
2527 >    }
2528 >
2529 >    final long sumCount() {
2530 >        CounterCell[] as = counterCells; CounterCell a;
2531 >        long sum = baseCount;
2532 >        if (as != null) {
2533 >            for (int i = 0; i < as.length; ++i) {
2534 >                if ((a = as[i]) != null)
2535 >                    sum += a.value;
2536 >            }
2537          }
2538 <        return h;
2538 >        return sum;
2539      }
2540  
2541 +    // See LongAdder version for explanation
2542 +    private final void fullAddCount(long x, boolean wasUncontended) {
2543 +        int h;
2544 +        if ((h = ThreadLocalRandom.getProbe()) == 0) {
2545 +            ThreadLocalRandom.localInit();      // force initialization
2546 +            h = ThreadLocalRandom.getProbe();
2547 +            wasUncontended = true;
2548 +        }
2549 +        boolean collide = false;                // True if last slot nonempty
2550 +        for (;;) {
2551 +            CounterCell[] as; CounterCell a; int n; long v;
2552 +            if ((as = counterCells) != null && (n = as.length) > 0) {
2553 +                if ((a = as[(n - 1) & h]) == null) {
2554 +                    if (cellsBusy == 0) {            // Try to attach new Cell
2555 +                        CounterCell r = new CounterCell(x); // Optimistic create
2556 +                        if (cellsBusy == 0 &&
2557 +                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2558 +                            boolean created = false;
2559 +                            try {               // Recheck under lock
2560 +                                CounterCell[] rs; int m, j;
2561 +                                if ((rs = counterCells) != null &&
2562 +                                    (m = rs.length) > 0 &&
2563 +                                    rs[j = (m - 1) & h] == null) {
2564 +                                    rs[j] = r;
2565 +                                    created = true;
2566 +                                }
2567 +                            } finally {
2568 +                                cellsBusy = 0;
2569 +                            }
2570 +                            if (created)
2571 +                                break;
2572 +                            continue;           // Slot is now non-empty
2573 +                        }
2574 +                    }
2575 +                    collide = false;
2576 +                }
2577 +                else if (!wasUncontended)       // CAS already known to fail
2578 +                    wasUncontended = true;      // Continue after rehash
2579 +                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2580 +                    break;
2581 +                else if (counterCells != as || n >= NCPU)
2582 +                    collide = false;            // At max size or stale
2583 +                else if (!collide)
2584 +                    collide = true;
2585 +                else if (cellsBusy == 0 &&
2586 +                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2587 +                    try {
2588 +                        if (counterCells == as) {// Expand table unless stale
2589 +                            CounterCell[] rs = new CounterCell[n << 1];
2590 +                            for (int i = 0; i < n; ++i)
2591 +                                rs[i] = as[i];
2592 +                            counterCells = rs;
2593 +                        }
2594 +                    } finally {
2595 +                        cellsBusy = 0;
2596 +                    }
2597 +                    collide = false;
2598 +                    continue;                   // Retry with expanded table
2599 +                }
2600 +                h = ThreadLocalRandom.advanceProbe(h);
2601 +            }
2602 +            else if (cellsBusy == 0 && counterCells == as &&
2603 +                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2604 +                boolean init = false;
2605 +                try {                           // Initialize table
2606 +                    if (counterCells == as) {
2607 +                        CounterCell[] rs = new CounterCell[2];
2608 +                        rs[h & 1] = new CounterCell(x);
2609 +                        counterCells = rs;
2610 +                        init = true;
2611 +                    }
2612 +                } finally {
2613 +                    cellsBusy = 0;
2614 +                }
2615 +                if (init)
2616 +                    break;
2617 +            }
2618 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2619 +                break;                          // Fall back on using base
2620 +        }
2621 +    }
2622 +
2623 +    /* ---------------- Conversion from/to TreeBins -------------- */
2624 +
2625      /**
2626 <     * Returns a string representation of this map.  The string
2627 <     * representation consists of a list of key-value mappings (in no
2628 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
2629 <     * mappings are separated by the characters {@code ", "} (comma
2630 <     * and space).  Each key-value mapping is rendered as the key
2631 <     * followed by an equals sign ("{@code =}") followed by the
2632 <     * associated value.
2633 <     *
2634 <     * @return a string representation of this map
2626 >     * Replaces all linked nodes in bin at given index unless table is
2627 >     * too small, in which case resizes instead.
2628 >     */
2629 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2630 >        Node<K,V> b; int n;
2631 >        if (tab != null) {
2632 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
2633 >                tryPresize(n << 1);
2634 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2635 >                synchronized (b) {
2636 >                    if (tabAt(tab, index) == b) {
2637 >                        TreeNode<K,V> hd = null, tl = null;
2638 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2639 >                            TreeNode<K,V> p =
2640 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2641 >                                                  null, null);
2642 >                            if ((p.prev = tl) == null)
2643 >                                hd = p;
2644 >                            else
2645 >                                tl.next = p;
2646 >                            tl = p;
2647 >                        }
2648 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2649 >                    }
2650 >                }
2651 >            }
2652 >        }
2653 >    }
2654 >
2655 >    /**
2656 >     * Returns a list on non-TreeNodes replacing those in given list.
2657       */
2658 <    public String toString() {
2659 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2660 <        StringBuilder sb = new StringBuilder();
2661 <        sb.append('{');
2662 <        Object v;
2663 <        if ((v = it.advance()) != null) {
2664 <            for (;;) {
2665 <                Object k = it.nextKey;
2666 <                sb.append(k == this ? "(this Map)" : k);
2667 <                sb.append('=');
2668 <                sb.append(v == this ? "(this Map)" : v);
2669 <                if ((v = it.advance()) == null)
2658 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2659 >        Node<K,V> hd = null, tl = null;
2660 >        for (Node<K,V> q = b; q != null; q = q.next) {
2661 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2662 >            if (tl == null)
2663 >                hd = p;
2664 >            else
2665 >                tl.next = p;
2666 >            tl = p;
2667 >        }
2668 >        return hd;
2669 >    }
2670 >
2671 >    /* ---------------- TreeNodes -------------- */
2672 >
2673 >    /**
2674 >     * Nodes for use in TreeBins
2675 >     */
2676 >    static final class TreeNode<K,V> extends Node<K,V> {
2677 >        TreeNode<K,V> parent;  // red-black tree links
2678 >        TreeNode<K,V> left;
2679 >        TreeNode<K,V> right;
2680 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2681 >        boolean red;
2682 >
2683 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2684 >                 TreeNode<K,V> parent) {
2685 >            super(hash, key, val, next);
2686 >            this.parent = parent;
2687 >        }
2688 >
2689 >        Node<K,V> find(int h, Object k) {
2690 >            return findTreeNode(h, k, null);
2691 >        }
2692 >
2693 >        /**
2694 >         * Returns the TreeNode (or null if not found) for the given key
2695 >         * starting at given root.
2696 >         */
2697 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2698 >            if (k != null) {
2699 >                TreeNode<K,V> p = this;
2700 >                do {
2701 >                    int ph, dir; K pk; TreeNode<K,V> q;
2702 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2703 >                    if ((ph = p.hash) > h)
2704 >                        p = pl;
2705 >                    else if (ph < h)
2706 >                        p = pr;
2707 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2708 >                        return p;
2709 >                    else if (pl == null)
2710 >                        p = pr;
2711 >                    else if (pr == null)
2712 >                        p = pl;
2713 >                    else if ((kc != null ||
2714 >                              (kc = comparableClassFor(k)) != null) &&
2715 >                             (dir = compareComparables(kc, k, pk)) != 0)
2716 >                        p = (dir < 0) ? pl : pr;
2717 >                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
2718 >                        return q;
2719 >                    else
2720 >                        p = pl;
2721 >                } while (p != null);
2722 >            }
2723 >            return null;
2724 >        }
2725 >    }
2726 >
2727 >    /* ---------------- TreeBins -------------- */
2728 >
2729 >    /**
2730 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2731 >     * keys or values, but instead point to list of TreeNodes and
2732 >     * their root. They also maintain a parasitic read-write lock
2733 >     * forcing writers (who hold bin lock) to wait for readers (who do
2734 >     * not) to complete before tree restructuring operations.
2735 >     */
2736 >    static final class TreeBin<K,V> extends Node<K,V> {
2737 >        TreeNode<K,V> root;
2738 >        volatile TreeNode<K,V> first;
2739 >        volatile Thread waiter;
2740 >        volatile int lockState;
2741 >        // values for lockState
2742 >        static final int WRITER = 1; // set while holding write lock
2743 >        static final int WAITER = 2; // set when waiting for write lock
2744 >        static final int READER = 4; // increment value for setting read lock
2745 >
2746 >        /**
2747 >         * Tie-breaking utility for ordering insertions when equal
2748 >         * hashCodes and non-comparable. We don't require a total
2749 >         * order, just a consistent insertion rule to maintain
2750 >         * equivalence across rebalancings. Tie-breaking further than
2751 >         * necessary simplifies testing a bit.
2752 >         */
2753 >        static int tieBreakOrder(Object a, Object b) {
2754 >            int d;
2755 >            if (a == null || b == null ||
2756 >                (d = a.getClass().getName().
2757 >                 compareTo(b.getClass().getName())) == 0)
2758 >                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2759 >                     -1 : 1);
2760 >            return d;
2761 >        }
2762 >
2763 >        /**
2764 >         * Creates bin with initial set of nodes headed by b.
2765 >         */
2766 >        TreeBin(TreeNode<K,V> b) {
2767 >            super(TREEBIN, null, null, null);
2768 >            this.first = b;
2769 >            TreeNode<K,V> r = null;
2770 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2771 >                next = (TreeNode<K,V>)x.next;
2772 >                x.left = x.right = null;
2773 >                if (r == null) {
2774 >                    x.parent = null;
2775 >                    x.red = false;
2776 >                    r = x;
2777 >                }
2778 >                else {
2779 >                    K k = x.key;
2780 >                    int h = x.hash;
2781 >                    Class<?> kc = null;
2782 >                    for (TreeNode<K,V> p = r;;) {
2783 >                        int dir, ph;
2784 >                        K pk = p.key;
2785 >                        if ((ph = p.hash) > h)
2786 >                            dir = -1;
2787 >                        else if (ph < h)
2788 >                            dir = 1;
2789 >                        else if ((kc == null &&
2790 >                                  (kc = comparableClassFor(k)) == null) ||
2791 >                                 (dir = compareComparables(kc, k, pk)) == 0)
2792 >                            dir = tieBreakOrder(k, pk);
2793 >                        TreeNode<K,V> xp = p;
2794 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2795 >                            x.parent = xp;
2796 >                            if (dir <= 0)
2797 >                                xp.left = x;
2798 >                            else
2799 >                                xp.right = x;
2800 >                            r = balanceInsertion(r, x);
2801 >                            break;
2802 >                        }
2803 >                    }
2804 >                }
2805 >            }
2806 >            this.root = r;
2807 >            assert checkInvariants(root);
2808 >        }
2809 >
2810 >        /**
2811 >         * Acquires write lock for tree restructuring.
2812 >         */
2813 >        private final void lockRoot() {
2814 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2815 >                contendedLock(); // offload to separate method
2816 >        }
2817 >
2818 >        /**
2819 >         * Releases write lock for tree restructuring.
2820 >         */
2821 >        private final void unlockRoot() {
2822 >            lockState = 0;
2823 >        }
2824 >
2825 >        /**
2826 >         * Possibly blocks awaiting root lock.
2827 >         */
2828 >        private final void contendedLock() {
2829 >            boolean waiting = false;
2830 >            for (int s;;) {
2831 >                if (((s = lockState) & ~WAITER) == 0) {
2832 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2833 >                        if (waiting)
2834 >                            waiter = null;
2835 >                        return;
2836 >                    }
2837 >                }
2838 >                else if ((s & WAITER) == 0) {
2839 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2840 >                        waiting = true;
2841 >                        waiter = Thread.currentThread();
2842 >                    }
2843 >                }
2844 >                else if (waiting)
2845 >                    LockSupport.park(this);
2846 >            }
2847 >        }
2848 >
2849 >        /**
2850 >         * Returns matching node or null if none. Tries to search
2851 >         * using tree comparisons from root, but continues linear
2852 >         * search when lock not available.
2853 >         */
2854 >        final Node<K,V> find(int h, Object k) {
2855 >            if (k != null) {
2856 >                for (Node<K,V> e = first; e != null; ) {
2857 >                    int s; K ek;
2858 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2859 >                        if (e.hash == h &&
2860 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2861 >                            return e;
2862 >                        e = e.next;
2863 >                    }
2864 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2865 >                                                 s + READER)) {
2866 >                        TreeNode<K,V> r, p;
2867 >                        try {
2868 >                            p = ((r = root) == null ? null :
2869 >                                 r.findTreeNode(h, k, null));
2870 >                        } finally {
2871 >                            Thread w;
2872 >                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2873 >                                (READER|WAITER) && (w = waiter) != null)
2874 >                                LockSupport.unpark(w);
2875 >                        }
2876 >                        return p;
2877 >                    }
2878 >                }
2879 >            }
2880 >            return null;
2881 >        }
2882 >
2883 >        /**
2884 >         * Finds or adds a node.
2885 >         * @return null if added
2886 >         */
2887 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2888 >            Class<?> kc = null;
2889 >            boolean searched = false;
2890 >            for (TreeNode<K,V> p = root;;) {
2891 >                int dir, ph; K pk;
2892 >                if (p == null) {
2893 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2894                      break;
2895 <                sb.append(',').append(' ');
2895 >                }
2896 >                else if ((ph = p.hash) > h)
2897 >                    dir = -1;
2898 >                else if (ph < h)
2899 >                    dir = 1;
2900 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2901 >                    return p;
2902 >                else if ((kc == null &&
2903 >                          (kc = comparableClassFor(k)) == null) ||
2904 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2905 >                    if (!searched) {
2906 >                        TreeNode<K,V> q, ch;
2907 >                        searched = true;
2908 >                        if (((ch = p.left) != null &&
2909 >                             (q = ch.findTreeNode(h, k, kc)) != null) ||
2910 >                            ((ch = p.right) != null &&
2911 >                             (q = ch.findTreeNode(h, k, kc)) != null))
2912 >                            return q;
2913 >                    }
2914 >                    dir = tieBreakOrder(k, pk);
2915 >                }
2916 >
2917 >                TreeNode<K,V> xp = p;
2918 >                if ((p = (dir <= 0) ? p.left : p.right) == null) {
2919 >                    TreeNode<K,V> x, f = first;
2920 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2921 >                    if (f != null)
2922 >                        f.prev = x;
2923 >                    if (dir <= 0)
2924 >                        xp.left = x;
2925 >                    else
2926 >                        xp.right = x;
2927 >                    if (!xp.red)
2928 >                        x.red = true;
2929 >                    else {
2930 >                        lockRoot();
2931 >                        try {
2932 >                            root = balanceInsertion(root, x);
2933 >                        } finally {
2934 >                            unlockRoot();
2935 >                        }
2936 >                    }
2937 >                    break;
2938 >                }
2939 >            }
2940 >            assert checkInvariants(root);
2941 >            return null;
2942 >        }
2943 >
2944 >        /**
2945 >         * Removes the given node, that must be present before this
2946 >         * call.  This is messier than typical red-black deletion code
2947 >         * because we cannot swap the contents of an interior node
2948 >         * with a leaf successor that is pinned by "next" pointers
2949 >         * that are accessible independently of lock. So instead we
2950 >         * swap the tree linkages.
2951 >         *
2952 >         * @return true if now too small, so should be untreeified
2953 >         */
2954 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2955 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2956 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2957 >            TreeNode<K,V> r, rl;
2958 >            if (pred == null)
2959 >                first = next;
2960 >            else
2961 >                pred.next = next;
2962 >            if (next != null)
2963 >                next.prev = pred;
2964 >            if (first == null) {
2965 >                root = null;
2966 >                return true;
2967 >            }
2968 >            if ((r = root) == null || r.right == null || // too small
2969 >                (rl = r.left) == null || rl.left == null)
2970 >                return true;
2971 >            lockRoot();
2972 >            try {
2973 >                TreeNode<K,V> replacement;
2974 >                TreeNode<K,V> pl = p.left;
2975 >                TreeNode<K,V> pr = p.right;
2976 >                if (pl != null && pr != null) {
2977 >                    TreeNode<K,V> s = pr, sl;
2978 >                    while ((sl = s.left) != null) // find successor
2979 >                        s = sl;
2980 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2981 >                    TreeNode<K,V> sr = s.right;
2982 >                    TreeNode<K,V> pp = p.parent;
2983 >                    if (s == pr) { // p was s's direct parent
2984 >                        p.parent = s;
2985 >                        s.right = p;
2986 >                    }
2987 >                    else {
2988 >                        TreeNode<K,V> sp = s.parent;
2989 >                        if ((p.parent = sp) != null) {
2990 >                            if (s == sp.left)
2991 >                                sp.left = p;
2992 >                            else
2993 >                                sp.right = p;
2994 >                        }
2995 >                        if ((s.right = pr) != null)
2996 >                            pr.parent = s;
2997 >                    }
2998 >                    p.left = null;
2999 >                    if ((p.right = sr) != null)
3000 >                        sr.parent = p;
3001 >                    if ((s.left = pl) != null)
3002 >                        pl.parent = s;
3003 >                    if ((s.parent = pp) == null)
3004 >                        r = s;
3005 >                    else if (p == pp.left)
3006 >                        pp.left = s;
3007 >                    else
3008 >                        pp.right = s;
3009 >                    if (sr != null)
3010 >                        replacement = sr;
3011 >                    else
3012 >                        replacement = p;
3013 >                }
3014 >                else if (pl != null)
3015 >                    replacement = pl;
3016 >                else if (pr != null)
3017 >                    replacement = pr;
3018 >                else
3019 >                    replacement = p;
3020 >                if (replacement != p) {
3021 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
3022 >                    if (pp == null)
3023 >                        r = replacement;
3024 >                    else if (p == pp.left)
3025 >                        pp.left = replacement;
3026 >                    else
3027 >                        pp.right = replacement;
3028 >                    p.left = p.right = p.parent = null;
3029 >                }
3030 >
3031 >                root = (p.red) ? r : balanceDeletion(r, replacement);
3032 >
3033 >                if (p == replacement) {  // detach pointers
3034 >                    TreeNode<K,V> pp;
3035 >                    if ((pp = p.parent) != null) {
3036 >                        if (p == pp.left)
3037 >                            pp.left = null;
3038 >                        else if (p == pp.right)
3039 >                            pp.right = null;
3040 >                        p.parent = null;
3041 >                    }
3042 >                }
3043 >            } finally {
3044 >                unlockRoot();
3045 >            }
3046 >            assert checkInvariants(root);
3047 >            return false;
3048 >        }
3049 >
3050 >        /* ------------------------------------------------------------ */
3051 >        // Red-black tree methods, all adapted from CLR
3052 >
3053 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
3054 >                                              TreeNode<K,V> p) {
3055 >            TreeNode<K,V> r, pp, rl;
3056 >            if (p != null && (r = p.right) != null) {
3057 >                if ((rl = p.right = r.left) != null)
3058 >                    rl.parent = p;
3059 >                if ((pp = r.parent = p.parent) == null)
3060 >                    (root = r).red = false;
3061 >                else if (pp.left == p)
3062 >                    pp.left = r;
3063 >                else
3064 >                    pp.right = r;
3065 >                r.left = p;
3066 >                p.parent = r;
3067 >            }
3068 >            return root;
3069 >        }
3070 >
3071 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
3072 >                                               TreeNode<K,V> p) {
3073 >            TreeNode<K,V> l, pp, lr;
3074 >            if (p != null && (l = p.left) != null) {
3075 >                if ((lr = p.left = l.right) != null)
3076 >                    lr.parent = p;
3077 >                if ((pp = l.parent = p.parent) == null)
3078 >                    (root = l).red = false;
3079 >                else if (pp.right == p)
3080 >                    pp.right = l;
3081 >                else
3082 >                    pp.left = l;
3083 >                l.right = p;
3084 >                p.parent = l;
3085 >            }
3086 >            return root;
3087 >        }
3088 >
3089 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
3090 >                                                    TreeNode<K,V> x) {
3091 >            x.red = true;
3092 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
3093 >                if ((xp = x.parent) == null) {
3094 >                    x.red = false;
3095 >                    return x;
3096 >                }
3097 >                else if (!xp.red || (xpp = xp.parent) == null)
3098 >                    return root;
3099 >                if (xp == (xppl = xpp.left)) {
3100 >                    if ((xppr = xpp.right) != null && xppr.red) {
3101 >                        xppr.red = false;
3102 >                        xp.red = false;
3103 >                        xpp.red = true;
3104 >                        x = xpp;
3105 >                    }
3106 >                    else {
3107 >                        if (x == xp.right) {
3108 >                            root = rotateLeft(root, x = xp);
3109 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3110 >                        }
3111 >                        if (xp != null) {
3112 >                            xp.red = false;
3113 >                            if (xpp != null) {
3114 >                                xpp.red = true;
3115 >                                root = rotateRight(root, xpp);
3116 >                            }
3117 >                        }
3118 >                    }
3119 >                }
3120 >                else {
3121 >                    if (xppl != null && xppl.red) {
3122 >                        xppl.red = false;
3123 >                        xp.red = false;
3124 >                        xpp.red = true;
3125 >                        x = xpp;
3126 >                    }
3127 >                    else {
3128 >                        if (x == xp.left) {
3129 >                            root = rotateRight(root, x = xp);
3130 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3131 >                        }
3132 >                        if (xp != null) {
3133 >                            xp.red = false;
3134 >                            if (xpp != null) {
3135 >                                xpp.red = true;
3136 >                                root = rotateLeft(root, xpp);
3137 >                            }
3138 >                        }
3139 >                    }
3140 >                }
3141 >            }
3142 >        }
3143 >
3144 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3145 >                                                   TreeNode<K,V> x) {
3146 >            for (TreeNode<K,V> xp, xpl, xpr;;) {
3147 >                if (x == null || x == root)
3148 >                    return root;
3149 >                else if ((xp = x.parent) == null) {
3150 >                    x.red = false;
3151 >                    return x;
3152 >                }
3153 >                else if (x.red) {
3154 >                    x.red = false;
3155 >                    return root;
3156 >                }
3157 >                else if ((xpl = xp.left) == x) {
3158 >                    if ((xpr = xp.right) != null && xpr.red) {
3159 >                        xpr.red = false;
3160 >                        xp.red = true;
3161 >                        root = rotateLeft(root, xp);
3162 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3163 >                    }
3164 >                    if (xpr == null)
3165 >                        x = xp;
3166 >                    else {
3167 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3168 >                        if ((sr == null || !sr.red) &&
3169 >                            (sl == null || !sl.red)) {
3170 >                            xpr.red = true;
3171 >                            x = xp;
3172 >                        }
3173 >                        else {
3174 >                            if (sr == null || !sr.red) {
3175 >                                if (sl != null)
3176 >                                    sl.red = false;
3177 >                                xpr.red = true;
3178 >                                root = rotateRight(root, xpr);
3179 >                                xpr = (xp = x.parent) == null ?
3180 >                                    null : xp.right;
3181 >                            }
3182 >                            if (xpr != null) {
3183 >                                xpr.red = (xp == null) ? false : xp.red;
3184 >                                if ((sr = xpr.right) != null)
3185 >                                    sr.red = false;
3186 >                            }
3187 >                            if (xp != null) {
3188 >                                xp.red = false;
3189 >                                root = rotateLeft(root, xp);
3190 >                            }
3191 >                            x = root;
3192 >                        }
3193 >                    }
3194 >                }
3195 >                else { // symmetric
3196 >                    if (xpl != null && xpl.red) {
3197 >                        xpl.red = false;
3198 >                        xp.red = true;
3199 >                        root = rotateRight(root, xp);
3200 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3201 >                    }
3202 >                    if (xpl == null)
3203 >                        x = xp;
3204 >                    else {
3205 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3206 >                        if ((sl == null || !sl.red) &&
3207 >                            (sr == null || !sr.red)) {
3208 >                            xpl.red = true;
3209 >                            x = xp;
3210 >                        }
3211 >                        else {
3212 >                            if (sl == null || !sl.red) {
3213 >                                if (sr != null)
3214 >                                    sr.red = false;
3215 >                                xpl.red = true;
3216 >                                root = rotateLeft(root, xpl);
3217 >                                xpl = (xp = x.parent) == null ?
3218 >                                    null : xp.left;
3219 >                            }
3220 >                            if (xpl != null) {
3221 >                                xpl.red = (xp == null) ? false : xp.red;
3222 >                                if ((sl = xpl.left) != null)
3223 >                                    sl.red = false;
3224 >                            }
3225 >                            if (xp != null) {
3226 >                                xp.red = false;
3227 >                                root = rotateRight(root, xp);
3228 >                            }
3229 >                            x = root;
3230 >                        }
3231 >                    }
3232 >                }
3233 >            }
3234 >        }
3235 >
3236 >        /**
3237 >         * Recursive invariant check
3238 >         */
3239 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3240 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3241 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3242 >            if (tb != null && tb.next != t)
3243 >                return false;
3244 >            if (tn != null && tn.prev != t)
3245 >                return false;
3246 >            if (tp != null && t != tp.left && t != tp.right)
3247 >                return false;
3248 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3249 >                return false;
3250 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3251 >                return false;
3252 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3253 >                return false;
3254 >            if (tl != null && !checkInvariants(tl))
3255 >                return false;
3256 >            if (tr != null && !checkInvariants(tr))
3257 >                return false;
3258 >            return true;
3259 >        }
3260 >
3261 >        private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
3262 >        private static final long LOCKSTATE;
3263 >        static {
3264 >            try {
3265 >                LOCKSTATE = U.objectFieldOffset
3266 >                    (TreeBin.class.getDeclaredField("lockState"));
3267 >            } catch (ReflectiveOperationException e) {
3268 >                throw new Error(e);
3269              }
3270          }
3138        return sb.append('}').toString();
3271      }
3272  
3273 +    /* ----------------Table Traversal -------------- */
3274 +
3275      /**
3276 <     * Compares the specified object with this map for equality.
3277 <     * Returns {@code true} if the given object is a map with the same
3278 <     * mappings as this map.  This operation may return misleading
3279 <     * results if either map is concurrently modified during execution
3280 <     * of this method.
3276 >     * Records the table, its length, and current traversal index for a
3277 >     * traverser that must process a region of a forwarded table before
3278 >     * proceeding with current table.
3279 >     */
3280 >    static final class TableStack<K,V> {
3281 >        int length;
3282 >        int index;
3283 >        Node<K,V>[] tab;
3284 >        TableStack<K,V> next;
3285 >    }
3286 >
3287 >    /**
3288 >     * Encapsulates traversal for methods such as containsValue; also
3289 >     * serves as a base class for other iterators and spliterators.
3290       *
3291 <     * @param o object to be compared for equality with this map
3292 <     * @return {@code true} if the specified object is equal to this map
3291 >     * Method advance visits once each still-valid node that was
3292 >     * reachable upon iterator construction. It might miss some that
3293 >     * were added to a bin after the bin was visited, which is OK wrt
3294 >     * consistency guarantees. Maintaining this property in the face
3295 >     * of possible ongoing resizes requires a fair amount of
3296 >     * bookkeeping state that is difficult to optimize away amidst
3297 >     * volatile accesses.  Even so, traversal maintains reasonable
3298 >     * throughput.
3299 >     *
3300 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3301 >     * However, if the table has been resized, then all future steps
3302 >     * must traverse both the bin at the current index as well as at
3303 >     * (index + baseSize); and so on for further resizings. To
3304 >     * paranoically cope with potential sharing by users of iterators
3305 >     * across threads, iteration terminates if a bounds checks fails
3306 >     * for a table read.
3307       */
3308 <    public boolean equals(Object o) {
3309 <        if (o != this) {
3310 <            if (!(o instanceof Map))
3311 <                return false;
3312 <            Map<?,?> m = (Map<?,?>) o;
3313 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3314 <            Object val;
3315 <            while ((val = it.advance()) != null) {
3316 <                Object v = m.get(it.nextKey);
3317 <                if (v == null || (v != val && !v.equals(val)))
3318 <                    return false;
3308 >    static class Traverser<K,V> {
3309 >        Node<K,V>[] tab;        // current table; updated if resized
3310 >        Node<K,V> next;         // the next entry to use
3311 >        TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3312 >        int index;              // index of bin to use next
3313 >        int baseIndex;          // current index of initial table
3314 >        int baseLimit;          // index bound for initial table
3315 >        final int baseSize;     // initial table size
3316 >
3317 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3318 >            this.tab = tab;
3319 >            this.baseSize = size;
3320 >            this.baseIndex = this.index = index;
3321 >            this.baseLimit = limit;
3322 >            this.next = null;
3323 >        }
3324 >
3325 >        /**
3326 >         * Advances if possible, returning next valid node, or null if none.
3327 >         */
3328 >        final Node<K,V> advance() {
3329 >            Node<K,V> e;
3330 >            if ((e = next) != null)
3331 >                e = e.next;
3332 >            for (;;) {
3333 >                Node<K,V>[] t; int i, n;  // must use locals in checks
3334 >                if (e != null)
3335 >                    return next = e;
3336 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3337 >                    (n = t.length) <= (i = index) || i < 0)
3338 >                    return next = null;
3339 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
3340 >                    if (e instanceof ForwardingNode) {
3341 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3342 >                        e = null;
3343 >                        pushState(t, i, n);
3344 >                        continue;
3345 >                    }
3346 >                    else if (e instanceof TreeBin)
3347 >                        e = ((TreeBin<K,V>)e).first;
3348 >                    else
3349 >                        e = null;
3350 >                }
3351 >                if (stack != null)
3352 >                    recoverState(n);
3353 >                else if ((index = i + baseSize) >= n)
3354 >                    index = ++baseIndex; // visit upper slots if present
3355              }
3356 <            for (Map.Entry<?,?> e : m.entrySet()) {
3357 <                Object mk, mv, v;
3358 <                if ((mk = e.getKey()) == null ||
3359 <                    (mv = e.getValue()) == null ||
3360 <                    (v = internalGet(mk)) == null ||
3361 <                    (mv != v && !mv.equals(v)))
3362 <                    return false;
3356 >        }
3357 >
3358 >        /**
3359 >         * Saves traversal state upon encountering a forwarding node.
3360 >         */
3361 >        private void pushState(Node<K,V>[] t, int i, int n) {
3362 >            TableStack<K,V> s = spare;  // reuse if possible
3363 >            if (s != null)
3364 >                spare = s.next;
3365 >            else
3366 >                s = new TableStack<K,V>();
3367 >            s.tab = t;
3368 >            s.length = n;
3369 >            s.index = i;
3370 >            s.next = stack;
3371 >            stack = s;
3372 >        }
3373 >
3374 >        /**
3375 >         * Possibly pops traversal state.
3376 >         *
3377 >         * @param n length of current table
3378 >         */
3379 >        private void recoverState(int n) {
3380 >            TableStack<K,V> s; int len;
3381 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
3382 >                n = len;
3383 >                index = s.index;
3384 >                tab = s.tab;
3385 >                s.tab = null;
3386 >                TableStack<K,V> next = s.next;
3387 >                s.next = spare; // save for reuse
3388 >                stack = next;
3389 >                spare = s;
3390              }
3391 +            if (s == null && (index += baseSize) >= n)
3392 +                index = ++baseIndex;
3393          }
3172        return true;
3394      }
3395  
3396 <    /* ----------------Iterators -------------- */
3397 <
3398 <    @SuppressWarnings("serial") static final class KeyIterator<K,V> extends Traverser<K,V,Object>
3399 <        implements Spliterator<K>, Enumeration<K> {
3400 <        KeyIterator(ConcurrentHashMap<K, V> map) { super(map); }
3401 <        KeyIterator(Traverser<K,V,Object> it) {
3402 <            super(it);
3396 >    /**
3397 >     * Base of key, value, and entry Iterators. Adds fields to
3398 >     * Traverser to support iterator.remove.
3399 >     */
3400 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3401 >        final ConcurrentHashMap<K,V> map;
3402 >        Node<K,V> lastReturned;
3403 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3404 >                    ConcurrentHashMap<K,V> map) {
3405 >            super(tab, size, index, limit);
3406 >            this.map = map;
3407 >            advance();
3408          }
3409 <        public KeyIterator<K,V> split() {
3410 <            if (nextKey != null)
3409 >
3410 >        public final boolean hasNext() { return next != null; }
3411 >        public final boolean hasMoreElements() { return next != null; }
3412 >
3413 >        public final void remove() {
3414 >            Node<K,V> p;
3415 >            if ((p = lastReturned) == null)
3416                  throw new IllegalStateException();
3417 <            return new KeyIterator<K,V>(this);
3417 >            lastReturned = null;
3418 >            map.replaceNode(p.key, null, null);
3419 >        }
3420 >    }
3421 >
3422 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3423 >        implements Iterator<K>, Enumeration<K> {
3424 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3425 >                    ConcurrentHashMap<K,V> map) {
3426 >            super(tab, index, size, limit, map);
3427          }
3428 <        @SuppressWarnings("unchecked") public final K next() {
3429 <            if (nextVal == null && advance() == null)
3428 >
3429 >        public final K next() {
3430 >            Node<K,V> p;
3431 >            if ((p = next) == null)
3432                  throw new NoSuchElementException();
3433 <            Object k = nextKey;
3434 <            nextVal = null;
3435 <            return (K) k;
3433 >            K k = p.key;
3434 >            lastReturned = p;
3435 >            advance();
3436 >            return k;
3437          }
3438  
3439          public final K nextElement() { return next(); }
3440      }
3441  
3442 <    @SuppressWarnings("serial") static final class ValueIterator<K,V> extends Traverser<K,V,Object>
3443 <        implements Spliterator<V>, Enumeration<V> {
3444 <        ValueIterator(ConcurrentHashMap<K, V> map) { super(map); }
3445 <        ValueIterator(Traverser<K,V,Object> it) {
3446 <            super(it);
3204 <        }
3205 <        public ValueIterator<K,V> split() {
3206 <            if (nextKey != null)
3207 <                throw new IllegalStateException();
3208 <            return new ValueIterator<K,V>(this);
3442 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3443 >        implements Iterator<V>, Enumeration<V> {
3444 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3445 >                      ConcurrentHashMap<K,V> map) {
3446 >            super(tab, index, size, limit, map);
3447          }
3448  
3449 <        @SuppressWarnings("unchecked") public final V next() {
3450 <            Object v;
3451 <            if ((v = nextVal) == null && (v = advance()) == null)
3449 >        public final V next() {
3450 >            Node<K,V> p;
3451 >            if ((p = next) == null)
3452                  throw new NoSuchElementException();
3453 <            nextVal = null;
3454 <            return (V) v;
3453 >            V v = p.val;
3454 >            lastReturned = p;
3455 >            advance();
3456 >            return v;
3457          }
3458  
3459          public final V nextElement() { return next(); }
3460      }
3461  
3462 <    @SuppressWarnings("serial") static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3463 <        implements Spliterator<Map.Entry<K,V>> {
3464 <        EntryIterator(ConcurrentHashMap<K, V> map) { super(map); }
3465 <        EntryIterator(Traverser<K,V,Object> it) {
3466 <            super(it);
3227 <        }
3228 <        public EntryIterator<K,V> split() {
3229 <            if (nextKey != null)
3230 <                throw new IllegalStateException();
3231 <            return new EntryIterator<K,V>(this);
3462 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3463 >        implements Iterator<Map.Entry<K,V>> {
3464 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3465 >                      ConcurrentHashMap<K,V> map) {
3466 >            super(tab, index, size, limit, map);
3467          }
3468  
3469 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3470 <            Object v;
3471 <            if ((v = nextVal) == null && (v = advance()) == null)
3469 >        public final Map.Entry<K,V> next() {
3470 >            Node<K,V> p;
3471 >            if ((p = next) == null)
3472                  throw new NoSuchElementException();
3473 <            Object k = nextKey;
3474 <            nextVal = null;
3475 <            return new MapEntry<K,V>((K)k, (V)v, map);
3473 >            K k = p.key;
3474 >            V v = p.val;
3475 >            lastReturned = p;
3476 >            advance();
3477 >            return new MapEntry<K,V>(k, v, map);
3478          }
3479      }
3480  
3481      /**
3482 <     * Exported Entry for iterators
3482 >     * Exported Entry for EntryIterator
3483       */
3484 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3484 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3485          final K key; // non-null
3486          V val;       // non-null
3487 <        final ConcurrentHashMap<K, V> map;
3488 <        MapEntry(K key, V val, ConcurrentHashMap<K, V> map) {
3487 >        final ConcurrentHashMap<K,V> map;
3488 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3489              this.key = key;
3490              this.val = val;
3491              this.map = map;
3492          }
3493 <        public final K getKey()       { return key; }
3494 <        public final V getValue()     { return val; }
3495 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3496 <        public final String toString(){ return key + "=" + val; }
3493 >        public K getKey()        { return key; }
3494 >        public V getValue()      { return val; }
3495 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3496 >        public String toString() {
3497 >            return Helpers.mapEntryToString(key, val);
3498 >        }
3499  
3500 <        public final boolean equals(Object o) {
3500 >        public boolean equals(Object o) {
3501              Object k, v; Map.Entry<?,?> e;
3502              return ((o instanceof Map.Entry) &&
3503                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3272 | Line 3511 | public class ConcurrentHashMap<K, V>
3511           * value to return is somewhat arbitrary here. Since we do not
3512           * necessarily track asynchronous changes, the most recent
3513           * "previous" value could be different from what we return (or
3514 <         * could even have been removed in which case the put will
3514 >         * could even have been removed, in which case the put will
3515           * re-establish). We do not and cannot guarantee more.
3516           */
3517 <        public final V setValue(V value) {
3517 >        public V setValue(V value) {
3518              if (value == null) throw new NullPointerException();
3519              V v = val;
3520              val = value;
# Line 3284 | Line 3523 | public class ConcurrentHashMap<K, V>
3523          }
3524      }
3525  
3526 <    /* ---------------- Serialization Support -------------- */
3526 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3527 >        implements Spliterator<K> {
3528 >        long est;               // size estimate
3529 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3530 >                       long est) {
3531 >            super(tab, size, index, limit);
3532 >            this.est = est;
3533 >        }
3534 >
3535 >        public Spliterator<K> trySplit() {
3536 >            int i, f, h;
3537 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3538 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3539 >                                        f, est >>>= 1);
3540 >        }
3541  
3542 <    /**
3543 <     * Stripped-down version of helper class used in previous version,
3544 <     * declared for the sake of serialization compatibility
3545 <     */
3546 <    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 <    }
3542 >        public void forEachRemaining(Consumer<? super K> action) {
3543 >            if (action == null) throw new NullPointerException();
3544 >            for (Node<K,V> p; (p = advance()) != null;)
3545 >                action.accept(p.key);
3546 >        }
3547  
3548 <    /**
3549 <     * Saves the state of the {@code ConcurrentHashMap} instance to a
3550 <     * stream (i.e., serializes it).
3551 <     * @param s the stream
3552 <     * @serialData
3553 <     * the key (Object) and value (Object)
3554 <     * for each key-value mapping, followed by a null pair.
3555 <     * The key-value mappings are emitted in no particular order.
3556 <     */
3557 <    @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s)
3558 <        throws java.io.IOException {
3559 <        if (segments == null) { // for serialization compatibility
3560 <            segments = (Segment<K,V>[])
3561 <                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);
3548 >        public boolean tryAdvance(Consumer<? super K> action) {
3549 >            if (action == null) throw new NullPointerException();
3550 >            Node<K,V> p;
3551 >            if ((p = advance()) == null)
3552 >                return false;
3553 >            action.accept(p.key);
3554 >            return true;
3555 >        }
3556 >
3557 >        public long estimateSize() { return est; }
3558 >
3559 >        public int characteristics() {
3560 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3561 >                Spliterator.NONNULL;
3562          }
3323        s.writeObject(null);
3324        s.writeObject(null);
3325        segments = null; // throw away
3563      }
3564  
3565 <    /**
3566 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3567 <     * @param s the stream
3568 <     */
3569 <    @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
3570 <        throws java.io.IOException, ClassNotFoundException {
3571 <        s.defaultReadObject();
3572 <        this.segments = null; // unneeded
3336 <        // initialize transient final field
3337 <        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
3565 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3566 >        implements Spliterator<V> {
3567 >        long est;               // size estimate
3568 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3569 >                         long est) {
3570 >            super(tab, size, index, limit);
3571 >            this.est = est;
3572 >        }
3573  
3574 <        // Create all nodes, then place in table once size is known
3575 <        long size = 0L;
3576 <        Node p = null;
3577 <        for (;;) {
3578 <            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;
3574 >        public Spliterator<V> trySplit() {
3575 >            int i, f, h;
3576 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3577 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3578 >                                          f, est >>>= 1);
3579          }
3580 <        if (p != null) {
3581 <            boolean init = false;
3582 <            int n;
3583 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3584 <                n = MAXIMUM_CAPACITY;
3585 <            else {
3586 <                int sz = (int)size;
3587 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3588 <            }
3589 <            int sc = sizeCtl;
3590 <            boolean collide = false;
3591 <            if (n > sc &&
3592 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3593 <                try {
3594 <                    if (table == null) {
3595 <                        init = true;
3596 <                        Node[] tab = new Node[n];
3597 <                        int mask = n - 1;
3598 <                        while (p != null) {
3599 <                            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 <            }
3580 >
3581 >        public void forEachRemaining(Consumer<? super V> action) {
3582 >            if (action == null) throw new NullPointerException();
3583 >            for (Node<K,V> p; (p = advance()) != null;)
3584 >                action.accept(p.val);
3585 >        }
3586 >
3587 >        public boolean tryAdvance(Consumer<? super V> action) {
3588 >            if (action == null) throw new NullPointerException();
3589 >            Node<K,V> p;
3590 >            if ((p = advance()) == null)
3591 >                return false;
3592 >            action.accept(p.val);
3593 >            return true;
3594 >        }
3595 >
3596 >        public long estimateSize() { return est; }
3597 >
3598 >        public int characteristics() {
3599 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3600          }
3601      }
3602  
3603 +    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3604 +        implements Spliterator<Map.Entry<K,V>> {
3605 +        final ConcurrentHashMap<K,V> map; // To export MapEntry
3606 +        long est;               // size estimate
3607 +        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3608 +                         long est, ConcurrentHashMap<K,V> map) {
3609 +            super(tab, size, index, limit);
3610 +            this.map = map;
3611 +            this.est = est;
3612 +        }
3613  
3614 <    // -------------------------------------------------------
3614 >        public Spliterator<Map.Entry<K,V>> trySplit() {
3615 >            int i, f, h;
3616 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3617 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3618 >                                          f, est >>>= 1, map);
3619 >        }
3620  
3621 <    // Sams
3622 <    /** Interface describing a void action of one argument */
3623 <    public interface Action<A> { void apply(A a); }
3624 <    /** Interface describing a void action of two arguments */
3625 <    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); }
3621 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3622 >            if (action == null) throw new NullPointerException();
3623 >            for (Node<K,V> p; (p = advance()) != null; )
3624 >                action.accept(new MapEntry<K,V>(p.key, p.val, map));
3625 >        }
3626  
3627 +        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3628 +            if (action == null) throw new NullPointerException();
3629 +            Node<K,V> p;
3630 +            if ((p = advance()) == null)
3631 +                return false;
3632 +            action.accept(new MapEntry<K,V>(p.key, p.val, map));
3633 +            return true;
3634 +        }
3635  
3636 <    // -------------------------------------------------------
3636 >        public long estimateSize() { return est; }
3637 >
3638 >        public int characteristics() {
3639 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3640 >                Spliterator.NONNULL;
3641 >        }
3642 >    }
3643 >
3644 >    // Parallel bulk operations
3645 >
3646 >    /**
3647 >     * Computes initial batch value for bulk tasks. The returned value
3648 >     * is approximately exp2 of the number of times (minus one) to
3649 >     * split task by two before executing leaf action. This value is
3650 >     * faster to compute and more convenient to use as a guide to
3651 >     * splitting than is the depth, since it is used while dividing by
3652 >     * two anyway.
3653 >     */
3654 >    final int batchFor(long b) {
3655 >        long n;
3656 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3657 >            return 0;
3658 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3659 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3660 >    }
3661  
3662      /**
3663       * Performs the given action for each (key, value).
3664       *
3665 +     * @param parallelismThreshold the (estimated) number of elements
3666 +     * needed for this operation to be executed in parallel
3667       * @param action the action
3668 +     * @since 1.8
3669       */
3670 <    public void forEach(BiAction<K,V> action) {
3671 <        ForkJoinTasks.forEach
3672 <            (this, action).invoke();
3670 >    public void forEach(long parallelismThreshold,
3671 >                        BiConsumer<? super K,? super V> action) {
3672 >        if (action == null) throw new NullPointerException();
3673 >        new ForEachMappingTask<K,V>
3674 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3675 >             action).invoke();
3676      }
3677  
3678      /**
3679       * Performs the given action for each non-null transformation
3680       * of each (key, value).
3681       *
3682 +     * @param parallelismThreshold the (estimated) number of elements
3683 +     * needed for this operation to be executed in parallel
3684       * @param transformer a function returning the transformation
3685 <     * for an element, or null of there is no transformation (in
3686 <     * which case the action is not applied).
3685 >     * for an element, or null if there is no transformation (in
3686 >     * which case the action is not applied)
3687       * @param action the action
3688 +     * @param <U> the return type of the transformer
3689 +     * @since 1.8
3690       */
3691 <    public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3692 <                            Action<U> action) {
3693 <        ForkJoinTasks.forEach
3694 <            (this, transformer, action).invoke();
3691 >    public <U> void forEach(long parallelismThreshold,
3692 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3693 >                            Consumer<? super U> action) {
3694 >        if (transformer == null || action == null)
3695 >            throw new NullPointerException();
3696 >        new ForEachTransformedMappingTask<K,V,U>
3697 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3698 >             transformer, action).invoke();
3699      }
3700  
3701      /**
# Line 3481 | Line 3705 | public class ConcurrentHashMap<K, V>
3705       * results of any other parallel invocations of the search
3706       * function are ignored.
3707       *
3708 +     * @param parallelismThreshold the (estimated) number of elements
3709 +     * needed for this operation to be executed in parallel
3710       * @param searchFunction a function returning a non-null
3711       * result on success, else null
3712 +     * @param <U> the return type of the search function
3713       * @return a non-null result from applying the given search
3714       * function on each (key, value), or null if none
3715 +     * @since 1.8
3716       */
3717 <    public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3718 <        return ForkJoinTasks.search
3719 <            (this, searchFunction).invoke();
3717 >    public <U> U search(long parallelismThreshold,
3718 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3719 >        if (searchFunction == null) throw new NullPointerException();
3720 >        return new SearchMappingsTask<K,V,U>
3721 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3722 >             searchFunction, new AtomicReference<U>()).invoke();
3723      }
3724  
3725      /**
# Line 3496 | Line 3727 | public class ConcurrentHashMap<K, V>
3727       * of all (key, value) pairs using the given reducer to
3728       * combine values, or null if none.
3729       *
3730 +     * @param parallelismThreshold the (estimated) number of elements
3731 +     * needed for this operation to be executed in parallel
3732       * @param transformer a function returning the transformation
3733 <     * for an element, or null of there is no transformation (in
3734 <     * which case it is not combined).
3733 >     * for an element, or null if there is no transformation (in
3734 >     * which case it is not combined)
3735       * @param reducer a commutative associative combining function
3736 +     * @param <U> the return type of the transformer
3737       * @return the result of accumulating the given transformation
3738       * of all (key, value) pairs
3739 +     * @since 1.8
3740       */
3741 <    public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3742 <                        BiFun<? super U, ? super U, ? extends U> reducer) {
3743 <        return ForkJoinTasks.reduce
3744 <            (this, transformer, reducer).invoke();
3741 >    public <U> U reduce(long parallelismThreshold,
3742 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3743 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3744 >        if (transformer == null || reducer == null)
3745 >            throw new NullPointerException();
3746 >        return new MapReduceMappingsTask<K,V,U>
3747 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3748 >             null, transformer, reducer).invoke();
3749      }
3750  
3751      /**
# Line 3514 | Line 3753 | public class ConcurrentHashMap<K, V>
3753       * of all (key, value) pairs using the given reducer to
3754       * combine values, and the given basis as an identity value.
3755       *
3756 +     * @param parallelismThreshold the (estimated) number of elements
3757 +     * needed for this operation to be executed in parallel
3758       * @param transformer a function returning the transformation
3759       * for an element
3760       * @param basis the identity (initial default value) for the reduction
3761       * @param reducer a commutative associative combining function
3762       * @return the result of accumulating the given transformation
3763       * of all (key, value) pairs
3764 +     * @since 1.8
3765       */
3766 <    public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
3766 >    public double reduceToDouble(long parallelismThreshold,
3767 >                                 ToDoubleBiFunction<? super K, ? super V> transformer,
3768                                   double basis,
3769 <                                 DoubleByDoubleToDouble reducer) {
3770 <        return ForkJoinTasks.reduceToDouble
3771 <            (this, transformer, basis, reducer).invoke();
3769 >                                 DoubleBinaryOperator reducer) {
3770 >        if (transformer == null || reducer == null)
3771 >            throw new NullPointerException();
3772 >        return new MapReduceMappingsToDoubleTask<K,V>
3773 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3774 >             null, transformer, basis, reducer).invoke();
3775      }
3776  
3777      /**
# Line 3533 | Line 3779 | public class ConcurrentHashMap<K, V>
3779       * of all (key, value) pairs using the given reducer to
3780       * combine values, and the given basis as an identity value.
3781       *
3782 +     * @param parallelismThreshold the (estimated) number of elements
3783 +     * needed for this operation to be executed in parallel
3784       * @param transformer a function returning the transformation
3785       * for an element
3786       * @param basis the identity (initial default value) for the reduction
3787       * @param reducer a commutative associative combining function
3788       * @return the result of accumulating the given transformation
3789       * of all (key, value) pairs
3790 +     * @since 1.8
3791       */
3792 <    public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
3792 >    public long reduceToLong(long parallelismThreshold,
3793 >                             ToLongBiFunction<? super K, ? super V> transformer,
3794                               long basis,
3795 <                             LongByLongToLong reducer) {
3796 <        return ForkJoinTasks.reduceToLong
3797 <            (this, transformer, basis, reducer).invoke();
3795 >                             LongBinaryOperator reducer) {
3796 >        if (transformer == null || reducer == null)
3797 >            throw new NullPointerException();
3798 >        return new MapReduceMappingsToLongTask<K,V>
3799 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3800 >             null, transformer, basis, reducer).invoke();
3801      }
3802  
3803      /**
# Line 3552 | Line 3805 | public class ConcurrentHashMap<K, V>
3805       * of all (key, value) pairs using the given reducer to
3806       * combine values, and the given basis as an identity value.
3807       *
3808 +     * @param parallelismThreshold the (estimated) number of elements
3809 +     * needed for this operation to be executed in parallel
3810       * @param transformer a function returning the transformation
3811       * for an element
3812       * @param basis the identity (initial default value) for the reduction
3813       * @param reducer a commutative associative combining function
3814       * @return the result of accumulating the given transformation
3815       * of all (key, value) pairs
3816 +     * @since 1.8
3817       */
3818 <    public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
3818 >    public int reduceToInt(long parallelismThreshold,
3819 >                           ToIntBiFunction<? super K, ? super V> transformer,
3820                             int basis,
3821 <                           IntByIntToInt reducer) {
3822 <        return ForkJoinTasks.reduceToInt
3823 <            (this, transformer, basis, reducer).invoke();
3821 >                           IntBinaryOperator reducer) {
3822 >        if (transformer == null || reducer == null)
3823 >            throw new NullPointerException();
3824 >        return new MapReduceMappingsToIntTask<K,V>
3825 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3826 >             null, transformer, basis, reducer).invoke();
3827      }
3828  
3829      /**
3830       * Performs the given action for each key.
3831       *
3832 +     * @param parallelismThreshold the (estimated) number of elements
3833 +     * needed for this operation to be executed in parallel
3834       * @param action the action
3835 +     * @since 1.8
3836       */
3837 <    public void forEachKey(Action<K> action) {
3838 <        ForkJoinTasks.forEachKey
3839 <            (this, action).invoke();
3837 >    public void forEachKey(long parallelismThreshold,
3838 >                           Consumer<? super K> action) {
3839 >        if (action == null) throw new NullPointerException();
3840 >        new ForEachKeyTask<K,V>
3841 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3842 >             action).invoke();
3843      }
3844  
3845      /**
3846       * Performs the given action for each non-null transformation
3847       * of each key.
3848       *
3849 +     * @param parallelismThreshold the (estimated) number of elements
3850 +     * needed for this operation to be executed in parallel
3851       * @param transformer a function returning the transformation
3852 <     * for an element, or null of there is no transformation (in
3853 <     * which case the action is not applied).
3852 >     * for an element, or null if there is no transformation (in
3853 >     * which case the action is not applied)
3854       * @param action the action
3855 +     * @param <U> the return type of the transformer
3856 +     * @since 1.8
3857       */
3858 <    public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
3859 <                               Action<U> action) {
3860 <        ForkJoinTasks.forEachKey
3861 <            (this, transformer, action).invoke();
3858 >    public <U> void forEachKey(long parallelismThreshold,
3859 >                               Function<? super K, ? extends U> transformer,
3860 >                               Consumer<? super U> action) {
3861 >        if (transformer == null || action == null)
3862 >            throw new NullPointerException();
3863 >        new ForEachTransformedKeyTask<K,V,U>
3864 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3865 >             transformer, action).invoke();
3866      }
3867  
3868      /**
# Line 3598 | Line 3872 | public class ConcurrentHashMap<K, V>
3872       * any other parallel invocations of the search function are
3873       * ignored.
3874       *
3875 +     * @param parallelismThreshold the (estimated) number of elements
3876 +     * needed for this operation to be executed in parallel
3877       * @param searchFunction a function returning a non-null
3878       * result on success, else null
3879 +     * @param <U> the return type of the search function
3880       * @return a non-null result from applying the given search
3881       * function on each key, or null if none
3882 +     * @since 1.8
3883       */
3884 <    public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
3885 <        return ForkJoinTasks.searchKeys
3886 <            (this, searchFunction).invoke();
3884 >    public <U> U searchKeys(long parallelismThreshold,
3885 >                            Function<? super K, ? extends U> searchFunction) {
3886 >        if (searchFunction == null) throw new NullPointerException();
3887 >        return new SearchKeysTask<K,V,U>
3888 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3889 >             searchFunction, new AtomicReference<U>()).invoke();
3890      }
3891  
3892      /**
3893       * Returns the result of accumulating all keys using the given
3894       * reducer to combine values, or null if none.
3895       *
3896 +     * @param parallelismThreshold the (estimated) number of elements
3897 +     * needed for this operation to be executed in parallel
3898       * @param reducer a commutative associative combining function
3899       * @return the result of accumulating all keys using the given
3900       * reducer to combine values, or null if none
3901 +     * @since 1.8
3902       */
3903 <    public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
3904 <        return ForkJoinTasks.reduceKeys
3905 <            (this, reducer).invoke();
3903 >    public K reduceKeys(long parallelismThreshold,
3904 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3905 >        if (reducer == null) throw new NullPointerException();
3906 >        return new ReduceKeysTask<K,V>
3907 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3908 >             null, reducer).invoke();
3909      }
3910  
3911      /**
# Line 3626 | Line 3913 | public class ConcurrentHashMap<K, V>
3913       * of all keys using the given reducer to combine values, or
3914       * null if none.
3915       *
3916 +     * @param parallelismThreshold the (estimated) number of elements
3917 +     * needed for this operation to be executed in parallel
3918       * @param transformer a function returning the transformation
3919 <     * for an element, or null of there is no transformation (in
3920 <     * which case it is not combined).
3919 >     * for an element, or null if there is no transformation (in
3920 >     * which case it is not combined)
3921       * @param reducer a commutative associative combining function
3922 +     * @param <U> the return type of the transformer
3923       * @return the result of accumulating the given transformation
3924       * of all keys
3925 +     * @since 1.8
3926       */
3927 <    public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
3928 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
3929 <        return ForkJoinTasks.reduceKeys
3930 <            (this, transformer, reducer).invoke();
3927 >    public <U> U reduceKeys(long parallelismThreshold,
3928 >                            Function<? super K, ? extends U> transformer,
3929 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3930 >        if (transformer == null || reducer == null)
3931 >            throw new NullPointerException();
3932 >        return new MapReduceKeysTask<K,V,U>
3933 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3934 >             null, transformer, reducer).invoke();
3935      }
3936  
3937      /**
# Line 3644 | Line 3939 | public class ConcurrentHashMap<K, V>
3939       * of all keys using the given reducer to combine values, and
3940       * the given basis as an identity value.
3941       *
3942 +     * @param parallelismThreshold the (estimated) number of elements
3943 +     * needed for this operation to be executed in parallel
3944       * @param transformer a function returning the transformation
3945       * for an element
3946       * @param basis the identity (initial default value) for the reduction
3947       * @param reducer a commutative associative combining function
3948 <     * @return  the result of accumulating the given transformation
3948 >     * @return the result of accumulating the given transformation
3949       * of all keys
3950 +     * @since 1.8
3951       */
3952 <    public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
3952 >    public double reduceKeysToDouble(long parallelismThreshold,
3953 >                                     ToDoubleFunction<? super K> transformer,
3954                                       double basis,
3955 <                                     DoubleByDoubleToDouble reducer) {
3956 <        return ForkJoinTasks.reduceKeysToDouble
3957 <            (this, transformer, basis, reducer).invoke();
3955 >                                     DoubleBinaryOperator reducer) {
3956 >        if (transformer == null || reducer == null)
3957 >            throw new NullPointerException();
3958 >        return new MapReduceKeysToDoubleTask<K,V>
3959 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3960 >             null, transformer, basis, reducer).invoke();
3961      }
3962  
3963      /**
# Line 3663 | Line 3965 | public class ConcurrentHashMap<K, V>
3965       * of all keys using the given reducer to combine values, and
3966       * the given basis as an identity value.
3967       *
3968 +     * @param parallelismThreshold the (estimated) number of elements
3969 +     * needed for this operation to be executed in parallel
3970       * @param transformer a function returning the transformation
3971       * for an element
3972       * @param basis the identity (initial default value) for the reduction
3973       * @param reducer a commutative associative combining function
3974       * @return the result of accumulating the given transformation
3975       * of all keys
3976 +     * @since 1.8
3977       */
3978 <    public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3978 >    public long reduceKeysToLong(long parallelismThreshold,
3979 >                                 ToLongFunction<? super K> transformer,
3980                                   long basis,
3981 <                                 LongByLongToLong reducer) {
3982 <        return ForkJoinTasks.reduceKeysToLong
3983 <            (this, transformer, basis, reducer).invoke();
3981 >                                 LongBinaryOperator reducer) {
3982 >        if (transformer == null || reducer == null)
3983 >            throw new NullPointerException();
3984 >        return new MapReduceKeysToLongTask<K,V>
3985 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3986 >             null, transformer, basis, reducer).invoke();
3987      }
3988  
3989      /**
# Line 3682 | Line 3991 | public class ConcurrentHashMap<K, V>
3991       * of all keys using the given reducer to combine values, and
3992       * the given basis as an identity value.
3993       *
3994 +     * @param parallelismThreshold the (estimated) number of elements
3995 +     * needed for this operation to be executed in parallel
3996       * @param transformer a function returning the transformation
3997       * for an element
3998       * @param basis the identity (initial default value) for the reduction
3999       * @param reducer a commutative associative combining function
4000       * @return the result of accumulating the given transformation
4001       * of all keys
4002 +     * @since 1.8
4003       */
4004 <    public int reduceKeysToInt(ObjectToInt<? super K> transformer,
4004 >    public int reduceKeysToInt(long parallelismThreshold,
4005 >                               ToIntFunction<? super K> transformer,
4006                                 int basis,
4007 <                               IntByIntToInt reducer) {
4008 <        return ForkJoinTasks.reduceKeysToInt
4009 <            (this, transformer, basis, reducer).invoke();
4007 >                               IntBinaryOperator reducer) {
4008 >        if (transformer == null || reducer == null)
4009 >            throw new NullPointerException();
4010 >        return new MapReduceKeysToIntTask<K,V>
4011 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4012 >             null, transformer, basis, reducer).invoke();
4013      }
4014  
4015      /**
4016       * Performs the given action for each value.
4017       *
4018 +     * @param parallelismThreshold the (estimated) number of elements
4019 +     * needed for this operation to be executed in parallel
4020       * @param action the action
4021 +     * @since 1.8
4022       */
4023 <    public void forEachValue(Action<V> action) {
4024 <        ForkJoinTasks.forEachValue
4025 <            (this, action).invoke();
4023 >    public void forEachValue(long parallelismThreshold,
4024 >                             Consumer<? super V> action) {
4025 >        if (action == null)
4026 >            throw new NullPointerException();
4027 >        new ForEachValueTask<K,V>
4028 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4029 >             action).invoke();
4030      }
4031  
4032      /**
4033       * Performs the given action for each non-null transformation
4034       * of each value.
4035       *
4036 +     * @param parallelismThreshold the (estimated) number of elements
4037 +     * needed for this operation to be executed in parallel
4038       * @param transformer a function returning the transformation
4039 <     * for an element, or null of there is no transformation (in
4040 <     * which case the action is not applied).
4039 >     * for an element, or null if there is no transformation (in
4040 >     * which case the action is not applied)
4041 >     * @param action the action
4042 >     * @param <U> the return type of the transformer
4043 >     * @since 1.8
4044       */
4045 <    public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
4046 <                                 Action<U> action) {
4047 <        ForkJoinTasks.forEachValue
4048 <            (this, transformer, action).invoke();
4045 >    public <U> void forEachValue(long parallelismThreshold,
4046 >                                 Function<? super V, ? extends U> transformer,
4047 >                                 Consumer<? super U> action) {
4048 >        if (transformer == null || action == null)
4049 >            throw new NullPointerException();
4050 >        new ForEachTransformedValueTask<K,V,U>
4051 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4052 >             transformer, action).invoke();
4053      }
4054  
4055      /**
# Line 3727 | Line 4059 | public class ConcurrentHashMap<K, V>
4059       * any other parallel invocations of the search function are
4060       * ignored.
4061       *
4062 +     * @param parallelismThreshold the (estimated) number of elements
4063 +     * needed for this operation to be executed in parallel
4064       * @param searchFunction a function returning a non-null
4065       * result on success, else null
4066 +     * @param <U> the return type of the search function
4067       * @return a non-null result from applying the given search
4068       * function on each value, or null if none
4069 <     *
4069 >     * @since 1.8
4070       */
4071 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
4072 <        return ForkJoinTasks.searchValues
4073 <            (this, searchFunction).invoke();
4071 >    public <U> U searchValues(long parallelismThreshold,
4072 >                              Function<? super V, ? extends U> searchFunction) {
4073 >        if (searchFunction == null) throw new NullPointerException();
4074 >        return new SearchValuesTask<K,V,U>
4075 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4076 >             searchFunction, new AtomicReference<U>()).invoke();
4077      }
4078  
4079      /**
4080       * Returns the result of accumulating all values using the
4081       * given reducer to combine values, or null if none.
4082       *
4083 +     * @param parallelismThreshold the (estimated) number of elements
4084 +     * needed for this operation to be executed in parallel
4085       * @param reducer a commutative associative combining function
4086 <     * @return  the result of accumulating all values
4086 >     * @return the result of accumulating all values
4087 >     * @since 1.8
4088       */
4089 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
4090 <        return ForkJoinTasks.reduceValues
4091 <            (this, reducer).invoke();
4089 >    public V reduceValues(long parallelismThreshold,
4090 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
4091 >        if (reducer == null) throw new NullPointerException();
4092 >        return new ReduceValuesTask<K,V>
4093 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4094 >             null, reducer).invoke();
4095      }
4096  
4097      /**
# Line 3755 | Line 4099 | public class ConcurrentHashMap<K, V>
4099       * of all values using the given reducer to combine values, or
4100       * null if none.
4101       *
4102 +     * @param parallelismThreshold the (estimated) number of elements
4103 +     * needed for this operation to be executed in parallel
4104       * @param transformer a function returning the transformation
4105 <     * for an element, or null of there is no transformation (in
4106 <     * which case it is not combined).
4105 >     * for an element, or null if there is no transformation (in
4106 >     * which case it is not combined)
4107       * @param reducer a commutative associative combining function
4108 +     * @param <U> the return type of the transformer
4109       * @return the result of accumulating the given transformation
4110       * of all values
4111 +     * @since 1.8
4112       */
4113 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
4114 <                              BiFun<? super U, ? super U, ? extends U> reducer) {
4115 <        return ForkJoinTasks.reduceValues
4116 <            (this, transformer, reducer).invoke();
4113 >    public <U> U reduceValues(long parallelismThreshold,
4114 >                              Function<? super V, ? extends U> transformer,
4115 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
4116 >        if (transformer == null || reducer == null)
4117 >            throw new NullPointerException();
4118 >        return new MapReduceValuesTask<K,V,U>
4119 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4120 >             null, transformer, reducer).invoke();
4121      }
4122  
4123      /**
# Line 3773 | Line 4125 | public class ConcurrentHashMap<K, V>
4125       * of all values using the given reducer to combine values,
4126       * and the given basis as an identity value.
4127       *
4128 +     * @param parallelismThreshold the (estimated) number of elements
4129 +     * needed for this operation to be executed in parallel
4130       * @param transformer a function returning the transformation
4131       * for an element
4132       * @param basis the identity (initial default value) for the reduction
4133       * @param reducer a commutative associative combining function
4134       * @return the result of accumulating the given transformation
4135       * of all values
4136 +     * @since 1.8
4137       */
4138 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
4138 >    public double reduceValuesToDouble(long parallelismThreshold,
4139 >                                       ToDoubleFunction<? super V> transformer,
4140                                         double basis,
4141 <                                       DoubleByDoubleToDouble reducer) {
4142 <        return ForkJoinTasks.reduceValuesToDouble
4143 <            (this, transformer, basis, reducer).invoke();
4141 >                                       DoubleBinaryOperator reducer) {
4142 >        if (transformer == null || reducer == null)
4143 >            throw new NullPointerException();
4144 >        return new MapReduceValuesToDoubleTask<K,V>
4145 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4146 >             null, transformer, basis, reducer).invoke();
4147      }
4148  
4149      /**
# Line 3792 | Line 4151 | public class ConcurrentHashMap<K, V>
4151       * of all values using the given reducer to combine values,
4152       * and the given basis as an identity value.
4153       *
4154 +     * @param parallelismThreshold the (estimated) number of elements
4155 +     * needed for this operation to be executed in parallel
4156       * @param transformer a function returning the transformation
4157       * for an element
4158       * @param basis the identity (initial default value) for the reduction
4159       * @param reducer a commutative associative combining function
4160       * @return the result of accumulating the given transformation
4161       * of all values
4162 +     * @since 1.8
4163       */
4164 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
4164 >    public long reduceValuesToLong(long parallelismThreshold,
4165 >                                   ToLongFunction<? super V> transformer,
4166                                     long basis,
4167 <                                   LongByLongToLong reducer) {
4168 <        return ForkJoinTasks.reduceValuesToLong
4169 <            (this, transformer, basis, reducer).invoke();
4167 >                                   LongBinaryOperator reducer) {
4168 >        if (transformer == null || reducer == null)
4169 >            throw new NullPointerException();
4170 >        return new MapReduceValuesToLongTask<K,V>
4171 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4172 >             null, transformer, basis, reducer).invoke();
4173      }
4174  
4175      /**
# Line 3811 | Line 4177 | public class ConcurrentHashMap<K, V>
4177       * of all values using the given reducer to combine values,
4178       * and the given basis as an identity value.
4179       *
4180 +     * @param parallelismThreshold the (estimated) number of elements
4181 +     * needed for this operation to be executed in parallel
4182       * @param transformer a function returning the transformation
4183       * for an element
4184       * @param basis the identity (initial default value) for the reduction
4185       * @param reducer a commutative associative combining function
4186       * @return the result of accumulating the given transformation
4187       * of all values
4188 +     * @since 1.8
4189       */
4190 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4190 >    public int reduceValuesToInt(long parallelismThreshold,
4191 >                                 ToIntFunction<? super V> transformer,
4192                                   int basis,
4193 <                                 IntByIntToInt reducer) {
4194 <        return ForkJoinTasks.reduceValuesToInt
4195 <            (this, transformer, basis, reducer).invoke();
4193 >                                 IntBinaryOperator reducer) {
4194 >        if (transformer == null || reducer == null)
4195 >            throw new NullPointerException();
4196 >        return new MapReduceValuesToIntTask<K,V>
4197 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4198 >             null, transformer, basis, reducer).invoke();
4199      }
4200  
4201      /**
4202       * Performs the given action for each entry.
4203       *
4204 +     * @param parallelismThreshold the (estimated) number of elements
4205 +     * needed for this operation to be executed in parallel
4206       * @param action the action
4207 +     * @since 1.8
4208       */
4209 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
4210 <        ForkJoinTasks.forEachEntry
4211 <            (this, action).invoke();
4209 >    public void forEachEntry(long parallelismThreshold,
4210 >                             Consumer<? super Map.Entry<K,V>> action) {
4211 >        if (action == null) throw new NullPointerException();
4212 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4213 >                                  action).invoke();
4214      }
4215  
4216      /**
4217       * Performs the given action for each non-null transformation
4218       * of each entry.
4219       *
4220 +     * @param parallelismThreshold the (estimated) number of elements
4221 +     * needed for this operation to be executed in parallel
4222       * @param transformer a function returning the transformation
4223 <     * for an element, or null of there is no transformation (in
4224 <     * which case the action is not applied).
4223 >     * for an element, or null if there is no transformation (in
4224 >     * which case the action is not applied)
4225       * @param action the action
4226 +     * @param <U> the return type of the transformer
4227 +     * @since 1.8
4228       */
4229 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4230 <                                 Action<U> action) {
4231 <        ForkJoinTasks.forEachEntry
4232 <            (this, transformer, action).invoke();
4229 >    public <U> void forEachEntry(long parallelismThreshold,
4230 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
4231 >                                 Consumer<? super U> action) {
4232 >        if (transformer == null || action == null)
4233 >            throw new NullPointerException();
4234 >        new ForEachTransformedEntryTask<K,V,U>
4235 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4236 >             transformer, action).invoke();
4237      }
4238  
4239      /**
# Line 3857 | Line 4243 | public class ConcurrentHashMap<K, V>
4243       * any other parallel invocations of the search function are
4244       * ignored.
4245       *
4246 +     * @param parallelismThreshold the (estimated) number of elements
4247 +     * needed for this operation to be executed in parallel
4248       * @param searchFunction a function returning a non-null
4249       * result on success, else null
4250 +     * @param <U> the return type of the search function
4251       * @return a non-null result from applying the given search
4252       * function on each entry, or null if none
4253 +     * @since 1.8
4254       */
4255 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4256 <        return ForkJoinTasks.searchEntries
4257 <            (this, searchFunction).invoke();
4255 >    public <U> U searchEntries(long parallelismThreshold,
4256 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4257 >        if (searchFunction == null) throw new NullPointerException();
4258 >        return new SearchEntriesTask<K,V,U>
4259 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4260 >             searchFunction, new AtomicReference<U>()).invoke();
4261      }
4262  
4263      /**
4264       * Returns the result of accumulating all entries using the
4265       * given reducer to combine values, or null if none.
4266       *
4267 +     * @param parallelismThreshold the (estimated) number of elements
4268 +     * needed for this operation to be executed in parallel
4269       * @param reducer a commutative associative combining function
4270       * @return the result of accumulating all entries
4271 +     * @since 1.8
4272       */
4273 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4274 <        return ForkJoinTasks.reduceEntries
4275 <            (this, reducer).invoke();
4273 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4274 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4275 >        if (reducer == null) throw new NullPointerException();
4276 >        return new ReduceEntriesTask<K,V>
4277 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4278 >             null, reducer).invoke();
4279      }
4280  
4281      /**
# Line 3884 | Line 4283 | public class ConcurrentHashMap<K, V>
4283       * of all entries using the given reducer to combine values,
4284       * or null if none.
4285       *
4286 +     * @param parallelismThreshold the (estimated) number of elements
4287 +     * needed for this operation to be executed in parallel
4288       * @param transformer a function returning the transformation
4289 <     * for an element, or null of there is no transformation (in
4290 <     * which case it is not combined).
4289 >     * for an element, or null if there is no transformation (in
4290 >     * which case it is not combined)
4291       * @param reducer a commutative associative combining function
4292 +     * @param <U> the return type of the transformer
4293       * @return the result of accumulating the given transformation
4294       * of all entries
4295 +     * @since 1.8
4296       */
4297 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4298 <                               BiFun<? super U, ? super U, ? extends U> reducer) {
4299 <        return ForkJoinTasks.reduceEntries
4300 <            (this, transformer, reducer).invoke();
4297 >    public <U> U reduceEntries(long parallelismThreshold,
4298 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
4299 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
4300 >        if (transformer == null || reducer == null)
4301 >            throw new NullPointerException();
4302 >        return new MapReduceEntriesTask<K,V,U>
4303 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4304 >             null, transformer, reducer).invoke();
4305      }
4306  
4307      /**
# Line 3902 | Line 4309 | public class ConcurrentHashMap<K, V>
4309       * of all entries using the given reducer to combine values,
4310       * and the given basis as an identity value.
4311       *
4312 +     * @param parallelismThreshold the (estimated) number of elements
4313 +     * needed for this operation to be executed in parallel
4314       * @param transformer a function returning the transformation
4315       * for an element
4316       * @param basis the identity (initial default value) for the reduction
4317       * @param reducer a commutative associative combining function
4318       * @return the result of accumulating the given transformation
4319       * of all entries
4320 +     * @since 1.8
4321       */
4322 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4322 >    public double reduceEntriesToDouble(long parallelismThreshold,
4323 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
4324                                          double basis,
4325 <                                        DoubleByDoubleToDouble reducer) {
4326 <        return ForkJoinTasks.reduceEntriesToDouble
4327 <            (this, transformer, basis, reducer).invoke();
4325 >                                        DoubleBinaryOperator reducer) {
4326 >        if (transformer == null || reducer == null)
4327 >            throw new NullPointerException();
4328 >        return new MapReduceEntriesToDoubleTask<K,V>
4329 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4330 >             null, transformer, basis, reducer).invoke();
4331      }
4332  
4333      /**
# Line 3921 | Line 4335 | public class ConcurrentHashMap<K, V>
4335       * of all entries using the given reducer to combine values,
4336       * and the given basis as an identity value.
4337       *
4338 +     * @param parallelismThreshold the (estimated) number of elements
4339 +     * needed for this operation to be executed in parallel
4340       * @param transformer a function returning the transformation
4341       * for an element
4342       * @param basis the identity (initial default value) for the reduction
4343       * @param reducer a commutative associative combining function
4344 <     * @return  the result of accumulating the given transformation
4344 >     * @return the result of accumulating the given transformation
4345       * of all entries
4346 +     * @since 1.8
4347       */
4348 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4348 >    public long reduceEntriesToLong(long parallelismThreshold,
4349 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
4350                                      long basis,
4351 <                                    LongByLongToLong reducer) {
4352 <        return ForkJoinTasks.reduceEntriesToLong
4353 <            (this, transformer, basis, reducer).invoke();
4351 >                                    LongBinaryOperator reducer) {
4352 >        if (transformer == null || reducer == null)
4353 >            throw new NullPointerException();
4354 >        return new MapReduceEntriesToLongTask<K,V>
4355 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4356 >             null, transformer, basis, reducer).invoke();
4357      }
4358  
4359      /**
# Line 3940 | Line 4361 | public class ConcurrentHashMap<K, V>
4361       * of all entries using the given reducer to combine values,
4362       * and the given basis as an identity value.
4363       *
4364 +     * @param parallelismThreshold the (estimated) number of elements
4365 +     * needed for this operation to be executed in parallel
4366       * @param transformer a function returning the transformation
4367       * for an element
4368       * @param basis the identity (initial default value) for the reduction
4369       * @param reducer a commutative associative combining function
4370       * @return the result of accumulating the given transformation
4371       * of all entries
4372 +     * @since 1.8
4373       */
4374 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4374 >    public int reduceEntriesToInt(long parallelismThreshold,
4375 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
4376                                    int basis,
4377 <                                  IntByIntToInt reducer) {
4378 <        return ForkJoinTasks.reduceEntriesToInt
4379 <            (this, transformer, basis, reducer).invoke();
4377 >                                  IntBinaryOperator reducer) {
4378 >        if (transformer == null || reducer == null)
4379 >            throw new NullPointerException();
4380 >        return new MapReduceEntriesToIntTask<K,V>
4381 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4382 >             null, transformer, basis, reducer).invoke();
4383      }
4384  
4385 +
4386      /* ----------------Views -------------- */
4387  
4388      /**
4389       * Base class for views.
4390       */
4391 <    static abstract class CHMView<K, V> {
4392 <        final ConcurrentHashMap<K, V> map;
4393 <        CHMView(ConcurrentHashMap<K, V> map)  { this.map = map; }
4391 >    abstract static class CollectionView<K,V,E>
4392 >        implements Collection<E>, java.io.Serializable {
4393 >        private static final long serialVersionUID = 7249069246763182397L;
4394 >        final ConcurrentHashMap<K,V> map;
4395 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4396  
4397          /**
4398           * Returns the map backing this view.
# Line 3970 | Line 4401 | public class ConcurrentHashMap<K, V>
4401           */
4402          public ConcurrentHashMap<K,V> getMap() { return map; }
4403  
4404 <        public final int size()                 { return map.size(); }
4405 <        public final boolean isEmpty()          { return map.isEmpty(); }
4406 <        public final void clear()               { map.clear(); }
4404 >        /**
4405 >         * Removes all of the elements from this view, by removing all
4406 >         * the mappings from the map backing this view.
4407 >         */
4408 >        public final void clear()      { map.clear(); }
4409 >        public final int size()        { return map.size(); }
4410 >        public final boolean isEmpty() { return map.isEmpty(); }
4411  
4412          // implementations below rely on concrete classes supplying these
4413 <        abstract public Iterator<?> iterator();
4414 <        abstract public boolean contains(Object o);
4415 <        abstract public boolean remove(Object o);
4413 >        // abstract methods
4414 >        /**
4415 >         * Returns an iterator over the elements in this collection.
4416 >         *
4417 >         * <p>The returned iterator is
4418 >         * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
4419 >         *
4420 >         * @return an iterator over the elements in this collection
4421 >         */
4422 >        public abstract Iterator<E> iterator();
4423 >        public abstract boolean contains(Object o);
4424 >        public abstract boolean remove(Object o);
4425  
4426          private static final String oomeMsg = "Required array size too large";
4427  
4428          public final Object[] toArray() {
4429              long sz = map.mappingCount();
4430 <            if (sz > (long)(MAX_ARRAY_SIZE))
4430 >            if (sz > MAX_ARRAY_SIZE)
4431                  throw new OutOfMemoryError(oomeMsg);
4432              int n = (int)sz;
4433              Object[] r = new Object[n];
4434              int i = 0;
4435 <            Iterator<?> it = iterator();
3992 <            while (it.hasNext()) {
4435 >            for (E e : this) {
4436                  if (i == n) {
4437                      if (n >= MAX_ARRAY_SIZE)
4438                          throw new OutOfMemoryError(oomeMsg);
# Line 3999 | Line 4442 | public class ConcurrentHashMap<K, V>
4442                          n += (n >>> 1) + 1;
4443                      r = Arrays.copyOf(r, n);
4444                  }
4445 <                r[i++] = it.next();
4445 >                r[i++] = e;
4446              }
4447              return (i == n) ? r : Arrays.copyOf(r, i);
4448          }
4449  
4450 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4450 >        @SuppressWarnings("unchecked")
4451 >        public final <T> T[] toArray(T[] a) {
4452              long sz = map.mappingCount();
4453 <            if (sz > (long)(MAX_ARRAY_SIZE))
4453 >            if (sz > MAX_ARRAY_SIZE)
4454                  throw new OutOfMemoryError(oomeMsg);
4455              int m = (int)sz;
4456              T[] r = (a.length >= m) ? a :
# Line 4014 | Line 4458 | public class ConcurrentHashMap<K, V>
4458                  .newInstance(a.getClass().getComponentType(), m);
4459              int n = r.length;
4460              int i = 0;
4461 <            Iterator<?> it = iterator();
4018 <            while (it.hasNext()) {
4461 >            for (E e : this) {
4462                  if (i == n) {
4463                      if (n >= MAX_ARRAY_SIZE)
4464                          throw new OutOfMemoryError(oomeMsg);
# Line 4025 | Line 4468 | public class ConcurrentHashMap<K, V>
4468                          n += (n >>> 1) + 1;
4469                      r = Arrays.copyOf(r, n);
4470                  }
4471 <                r[i++] = (T)it.next();
4471 >                r[i++] = (T)e;
4472              }
4473              if (a == r && i < n) {
4474                  r[i] = null; // null-terminate
# Line 4034 | Line 4477 | public class ConcurrentHashMap<K, V>
4477              return (i == n) ? r : Arrays.copyOf(r, i);
4478          }
4479  
4480 <        public final int hashCode() {
4481 <            int h = 0;
4482 <            for (Iterator<?> it = iterator(); it.hasNext();)
4483 <                h += it.next().hashCode();
4484 <            return h;
4485 <        }
4486 <
4480 >        /**
4481 >         * Returns a string representation of this collection.
4482 >         * The string representation consists of the string representations
4483 >         * of the collection's elements in the order they are returned by
4484 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4485 >         * Adjacent elements are separated by the characters {@code ", "}
4486 >         * (comma and space).  Elements are converted to strings as by
4487 >         * {@link String#valueOf(Object)}.
4488 >         *
4489 >         * @return a string representation of this collection
4490 >         */
4491          public final String toString() {
4492              StringBuilder sb = new StringBuilder();
4493              sb.append('[');
4494 <            Iterator<?> it = iterator();
4494 >            Iterator<E> it = iterator();
4495              if (it.hasNext()) {
4496                  for (;;) {
4497                      Object e = it.next();
# Line 4059 | Line 4506 | public class ConcurrentHashMap<K, V>
4506  
4507          public final boolean containsAll(Collection<?> c) {
4508              if (c != this) {
4509 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4063 <                    Object e = it.next();
4509 >                for (Object e : c) {
4510                      if (e == null || !contains(e))
4511                          return false;
4512                  }
# Line 4069 | Line 4515 | public class ConcurrentHashMap<K, V>
4515          }
4516  
4517          public final boolean removeAll(Collection<?> c) {
4518 +            if (c == null) throw new NullPointerException();
4519              boolean modified = false;
4520 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4520 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4521                  if (c.contains(it.next())) {
4522                      it.remove();
4523                      modified = true;
# Line 4080 | Line 4527 | public class ConcurrentHashMap<K, V>
4527          }
4528  
4529          public final boolean retainAll(Collection<?> c) {
4530 +            if (c == null) throw new NullPointerException();
4531              boolean modified = false;
4532 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4532 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4533                  if (!c.contains(it.next())) {
4534                      it.remove();
4535                      modified = true;
# Line 4095 | Line 4543 | public class ConcurrentHashMap<K, V>
4543      /**
4544       * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4545       * which additions may optionally be enabled by mapping to a
4546 <     * common value.  This class cannot be directly instantiated. See
4547 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4548 <     * {@link #newKeySet(int)}.
4546 >     * common value.  This class cannot be directly instantiated.
4547 >     * See {@link #keySet() keySet()},
4548 >     * {@link #keySet(Object) keySet(V)},
4549 >     * {@link #newKeySet() newKeySet()},
4550 >     * {@link #newKeySet(int) newKeySet(int)}.
4551 >     *
4552 >     * @since 1.8
4553       */
4554 <    public static class KeySetView<K,V> extends CHMView<K,V> implements Set<K>, java.io.Serializable {
4554 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4555 >        implements Set<K>, java.io.Serializable {
4556          private static final long serialVersionUID = 7249069246763182397L;
4557          private final V value;
4558 <        KeySetView(ConcurrentHashMap<K, V> map, V value) {  // non-public
4558 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4559              super(map);
4560              this.value = value;
4561          }
# Line 4112 | Line 4565 | public class ConcurrentHashMap<K, V>
4565           * or {@code null} if additions are not supported.
4566           *
4567           * @return the default mapped value for additions, or {@code null}
4568 <         * if not supported.
4568 >         * if not supported
4569           */
4570          public V getMappedValue() { return value; }
4571  
4572 <        // implement Set API
4573 <
4572 >        /**
4573 >         * {@inheritDoc}
4574 >         * @throws NullPointerException if the specified key is null
4575 >         */
4576          public boolean contains(Object o) { return map.containsKey(o); }
4122        public boolean remove(Object o)   { return map.remove(o) != null; }
4577  
4578          /**
4579 <         * Returns a "weakly consistent" iterator that will never
4580 <         * throw {@link ConcurrentModificationException}, and
4581 <         * guarantees to traverse elements as they existed upon
4582 <         * construction of the iterator, and may (but is not
4583 <         * guaranteed to) reflect any modifications subsequent to
4584 <         * construction.
4579 >         * Removes the key from this map view, by removing the key (and its
4580 >         * corresponding value) from the backing map.  This method does
4581 >         * nothing if the key is not in the map.
4582 >         *
4583 >         * @param  o the key to be removed from the backing map
4584 >         * @return {@code true} if the backing map contained the specified key
4585 >         * @throws NullPointerException if the specified key is null
4586 >         */
4587 >        public boolean remove(Object o) { return map.remove(o) != null; }
4588 >
4589 >        /**
4590 >         * @return an iterator over the keys of the backing map
4591 >         */
4592 >        public Iterator<K> iterator() {
4593 >            Node<K,V>[] t;
4594 >            ConcurrentHashMap<K,V> m = map;
4595 >            int f = (t = m.table) == null ? 0 : t.length;
4596 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4597 >        }
4598 >
4599 >        /**
4600 >         * Adds the specified key to this set view by mapping the key to
4601 >         * the default mapped value in the backing map, if defined.
4602           *
4603 <         * @return an iterator over the keys of this map
4603 >         * @param e key to be added
4604 >         * @return {@code true} if this set changed as a result of the call
4605 >         * @throws NullPointerException if the specified key is null
4606 >         * @throws UnsupportedOperationException if no default mapped value
4607 >         * for additions was provided
4608           */
4134        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4609          public boolean add(K e) {
4610              V v;
4611              if ((v = value) == null)
4612                  throw new UnsupportedOperationException();
4613 <            if (e == null)
4140 <                throw new NullPointerException();
4141 <            return map.internalPutIfAbsent(e, v) == null;
4613 >            return map.putVal(e, v, true) == null;
4614          }
4615 +
4616 +        /**
4617 +         * Adds all of the elements in the specified collection to this set,
4618 +         * as if by calling {@link #add} on each one.
4619 +         *
4620 +         * @param c the elements to be inserted into this set
4621 +         * @return {@code true} if this set changed as a result of the call
4622 +         * @throws NullPointerException if the collection or any of its
4623 +         * elements are {@code null}
4624 +         * @throws UnsupportedOperationException if no default mapped value
4625 +         * for additions was provided
4626 +         */
4627          public boolean addAll(Collection<? extends K> c) {
4628              boolean added = false;
4629              V v;
4630              if ((v = value) == null)
4631                  throw new UnsupportedOperationException();
4632              for (K e : c) {
4633 <                if (e == null)
4150 <                    throw new NullPointerException();
4151 <                if (map.internalPutIfAbsent(e, v) == null)
4633 >                if (map.putVal(e, v, true) == null)
4634                      added = true;
4635              }
4636              return added;
4637          }
4638 +
4639 +        public int hashCode() {
4640 +            int h = 0;
4641 +            for (K e : this)
4642 +                h += e.hashCode();
4643 +            return h;
4644 +        }
4645 +
4646          public boolean equals(Object o) {
4647              Set<?> c;
4648              return ((o instanceof Set) &&
# Line 4160 | Line 4650 | public class ConcurrentHashMap<K, V>
4650                       (containsAll(c) && c.containsAll(this))));
4651          }
4652  
4653 <        /**
4654 <         * Performs the given action for each key.
4655 <         *
4656 <         * @param action the action
4657 <         */
4658 <        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();
4653 >        public Spliterator<K> spliterator() {
4654 >            Node<K,V>[] t;
4655 >            ConcurrentHashMap<K,V> m = map;
4656 >            long n = m.sumCount();
4657 >            int f = (t = m.table) == null ? 0 : t.length;
4658 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4659          }
4660  
4661 <        /**
4662 <         * Returns a non-null result from applying the given search
4663 <         * function on each key, or null if none. Upon success,
4664 <         * further element processing is suppressed and the results of
4665 <         * any other parallel invocations of the search function are
4666 <         * ignored.
4667 <         *
4668 <         * @param searchFunction a function returning a non-null
4196 <         * result on success, else null
4197 <         * @return a non-null result from applying the given search
4198 <         * function on each key, or null if none
4199 <         */
4200 <        public <U> U search(Fun<? super K, ? extends U> searchFunction) {
4201 <            return ForkJoinTasks.searchKeys
4202 <                (map, searchFunction).invoke();
4203 <        }
4204 <
4205 <        /**
4206 <         * Returns the result of accumulating all keys using the given
4207 <         * reducer to combine values, or null if none.
4208 <         *
4209 <         * @param reducer a commutative associative combining function
4210 <         * @return the result of accumulating all keys using the given
4211 <         * reducer to combine values, or null if none
4212 <         */
4213 <        public K reduce(BiFun<? super K, ? super K, ? extends K> reducer) {
4214 <            return ForkJoinTasks.reduceKeys
4215 <                (map, reducer).invoke();
4216 <        }
4217 <
4218 <        /**
4219 <         * Returns the result of accumulating the given transformation
4220 <         * of all keys using the given reducer to combine values, and
4221 <         * the given basis as an identity value.
4222 <         *
4223 <         * @param transformer a function returning the transformation
4224 <         * for an element
4225 <         * @param basis the identity (initial default value) for the reduction
4226 <         * @param reducer a commutative associative combining function
4227 <         * @return  the result of accumulating the given transformation
4228 <         * of all keys
4229 <         */
4230 <        public double reduceToDouble(ObjectToDouble<? super K> transformer,
4231 <                                     double basis,
4232 <                                     DoubleByDoubleToDouble reducer) {
4233 <            return ForkJoinTasks.reduceKeysToDouble
4234 <                (map, transformer, basis, reducer).invoke();
4235 <        }
4236 <
4237 <
4238 <        /**
4239 <         * Returns the result of accumulating the given transformation
4240 <         * of all keys using the given reducer to combine values, and
4241 <         * the given basis as an identity value.
4242 <         *
4243 <         * @param transformer a function returning the transformation
4244 <         * for an element
4245 <         * @param basis the identity (initial default value) for the reduction
4246 <         * @param reducer a commutative associative combining function
4247 <         * @return the result of accumulating the given transformation
4248 <         * of all keys
4249 <         */
4250 <        public long reduceToLong(ObjectToLong<? super K> transformer,
4251 <                                 long basis,
4252 <                                 LongByLongToLong reducer) {
4253 <            return ForkJoinTasks.reduceKeysToLong
4254 <                (map, transformer, basis, reducer).invoke();
4255 <        }
4256 <
4257 <        /**
4258 <         * Returns the result of accumulating the given transformation
4259 <         * of all keys using the given reducer to combine values, and
4260 <         * the given basis as an identity value.
4261 <         *
4262 <         * @param transformer a function returning the transformation
4263 <         * for an element
4264 <         * @param basis the identity (initial default value) for the reduction
4265 <         * @param reducer a commutative associative combining function
4266 <         * @return the result of accumulating the given transformation
4267 <         * of all keys
4268 <         */
4269 <        public int reduceToInt(ObjectToInt<? super K> transformer,
4270 <                               int basis,
4271 <                               IntByIntToInt reducer) {
4272 <            return ForkJoinTasks.reduceKeysToInt
4273 <                (map, transformer, basis, reducer).invoke();
4661 >        public void forEach(Consumer<? super K> action) {
4662 >            if (action == null) throw new NullPointerException();
4663 >            Node<K,V>[] t;
4664 >            if ((t = map.table) != null) {
4665 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4666 >                for (Node<K,V> p; (p = it.advance()) != null; )
4667 >                    action.accept(p.key);
4668 >            }
4669          }
4275
4670      }
4671  
4672      /**
4673       * A view of a ConcurrentHashMap as a {@link Collection} of
4674       * values, in which additions are disabled. This class cannot be
4675 <     * directly instantiated. See {@link #values},
4676 <     *
4677 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4678 <     * that will never throw {@link ConcurrentModificationException},
4679 <     * and guarantees to traverse elements as they existed upon
4680 <     * construction of the iterator, and may (but is not guaranteed to)
4681 <     * reflect any modifications subsequent to construction.
4682 <     */
4683 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4684 <        implements Collection<V> {
4291 <        ValuesView(ConcurrentHashMap<K, V> map)   { super(map); }
4292 <        public final boolean contains(Object o) { return map.containsValue(o); }
4675 >     * directly instantiated. See {@link #values()}.
4676 >     */
4677 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4678 >        implements Collection<V>, java.io.Serializable {
4679 >        private static final long serialVersionUID = 2249069246763182397L;
4680 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4681 >        public final boolean contains(Object o) {
4682 >            return map.containsValue(o);
4683 >        }
4684 >
4685          public final boolean remove(Object o) {
4686              if (o != null) {
4687 <                Iterator<V> it = new ValueIterator<K,V>(map);
4296 <                while (it.hasNext()) {
4687 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4688                      if (o.equals(it.next())) {
4689                          it.remove();
4690                          return true;
# Line 4303 | Line 4694 | public class ConcurrentHashMap<K, V>
4694              return false;
4695          }
4696  
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         */
4697          public final Iterator<V> iterator() {
4698 <            return new ValueIterator<K,V>(map);
4698 >            ConcurrentHashMap<K,V> m = map;
4699 >            Node<K,V>[] t;
4700 >            int f = (t = m.table) == null ? 0 : t.length;
4701 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4702          }
4703 +
4704          public final boolean add(V e) {
4705              throw new UnsupportedOperationException();
4706          }
# Line 4323 | Line 4708 | public class ConcurrentHashMap<K, V>
4708              throw new UnsupportedOperationException();
4709          }
4710  
4711 <        /**
4712 <         * Performs the given action for each value.
4328 <         *
4329 <         * @param action the action
4330 <         */
4331 <        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();
4711 >        public boolean removeIf(Predicate<? super V> filter) {
4712 >            return map.removeValueIf(filter);
4713          }
4714  
4715 <        /**
4716 <         * Returns a non-null result from applying the given search
4717 <         * function on each value, or null if none.  Upon success,
4718 <         * further element processing is suppressed and the results of
4719 <         * any other parallel invocations of the search function are
4720 <         * 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();
4715 >        public Spliterator<V> spliterator() {
4716 >            Node<K,V>[] t;
4717 >            ConcurrentHashMap<K,V> m = map;
4718 >            long n = m.sumCount();
4719 >            int f = (t = m.table) == null ? 0 : t.length;
4720 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4721          }
4722  
4723 <        /**
4724 <         * Returns the result of accumulating all values using the
4725 <         * given reducer to combine values, or null if none.
4726 <         *
4727 <         * @param reducer a commutative associative combining function
4728 <         * @return  the result of accumulating all values
4729 <         */
4730 <        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();
4723 >        public void forEach(Consumer<? super V> action) {
4724 >            if (action == null) throw new NullPointerException();
4725 >            Node<K,V>[] t;
4726 >            if ((t = map.table) != null) {
4727 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4728 >                for (Node<K,V> p; (p = it.advance()) != null; )
4729 >                    action.accept(p.val);
4730 >            }
4731          }
4454
4732      }
4733  
4734      /**
4735       * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4736       * entries.  This class cannot be directly instantiated. See
4737 <     * {@link #entrySet}.
4737 >     * {@link #entrySet()}.
4738       */
4739 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4740 <        implements Set<Map.Entry<K,V>> {
4741 <        EntrySetView(ConcurrentHashMap<K, V> map) { super(map); }
4742 <        public final boolean contains(Object o) {
4739 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4740 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4741 >        private static final long serialVersionUID = 2249069246763182397L;
4742 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4743 >
4744 >        public boolean contains(Object o) {
4745              Object k, v, r; Map.Entry<?,?> e;
4746              return ((o instanceof Map.Entry) &&
4747                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4470 | Line 4749 | public class ConcurrentHashMap<K, V>
4749                      (v = e.getValue()) != null &&
4750                      (v == r || v.equals(r)));
4751          }
4752 <        public final boolean remove(Object o) {
4752 >
4753 >        public boolean remove(Object o) {
4754              Object k, v; Map.Entry<?,?> e;
4755              return ((o instanceof Map.Entry) &&
4756                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4479 | Line 4759 | public class ConcurrentHashMap<K, V>
4759          }
4760  
4761          /**
4762 <         * 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
4762 >         * @return an iterator over the entries of the backing map
4763           */
4764 <        public final Iterator<Map.Entry<K,V>> iterator() {
4765 <            return new EntryIterator<K,V>(map);
4764 >        public Iterator<Map.Entry<K,V>> iterator() {
4765 >            ConcurrentHashMap<K,V> m = map;
4766 >            Node<K,V>[] t;
4767 >            int f = (t = m.table) == null ? 0 : t.length;
4768 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4769          }
4770  
4771 <        public final boolean add(Entry<K,V> e) {
4772 <            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;
4771 >        public boolean add(Entry<K,V> e) {
4772 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4773          }
4774 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4774 >
4775 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4776              boolean added = false;
4777              for (Entry<K,V> e : c) {
4778                  if (add(e))
# Line 4507 | Line 4780 | public class ConcurrentHashMap<K, V>
4780              }
4781              return added;
4782          }
4510        public boolean equals(Object o) {
4511            Set<?> c;
4512            return ((o instanceof Set) &&
4513                    ((c = (Set<?>)o) == this ||
4514                     (containsAll(c) && c.containsAll(this))));
4515        }
4516
4517        /**
4518         * Performs the given action for each entry.
4519         *
4520         * @param action the action
4521         */
4522        public void forEach(Action<Map.Entry<K,V>> action) {
4523            ForkJoinTasks.forEachEntry
4524                (map, action).invoke();
4525        }
4526
4527        /**
4528         * Performs the given action for each non-null transformation
4529         * of each entry.
4530         *
4531         * @param transformer a function returning the transformation
4532         * for an element, or null of there is no transformation (in
4533         * which case the action is not applied).
4534         * @param action the action
4535         */
4536        public <U> void forEach(Fun<Map.Entry<K,V>, ? extends U> transformer,
4537                                Action<U> action) {
4538            ForkJoinTasks.forEachEntry
4539                (map, transformer, action).invoke();
4540        }
4783  
4784 <        /**
4785 <         * 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();
4784 >        public boolean removeIf(Predicate<? super Entry<K,V>> filter) {
4785 >            return map.removeEntryIf(filter);
4786          }
4787  
4788 <        /**
4789 <         * Returns the result of accumulating all entries using the
4790 <         * given reducer to combine values, or null if none.
4791 <         *
4792 <         * @param reducer a commutative associative combining function
4793 <         * @return the result of accumulating all entries
4794 <         */
4795 <        public Map.Entry<K,V> reduce(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4796 <            return ForkJoinTasks.reduceEntries
4797 <                (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);
4788 >        public final int hashCode() {
4789 >            int h = 0;
4790 >            Node<K,V>[] t;
4791 >            if ((t = map.table) != null) {
4792 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4793 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4794 >                    h += p.hashCode();
4795 >                }
4796 >            }
4797 >            return h;
4798          }
4799  
4800 <        /**
4801 <         * Returns a task that when invoked, returns the result of
4802 <         * accumulating the given transformation of all keys using the given
4803 <         * reducer to combine values, and the given basis as an
4804 <         * 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);
4800 >        public final boolean equals(Object o) {
4801 >            Set<?> c;
4802 >            return ((o instanceof Set) &&
4803 >                    ((c = (Set<?>)o) == this ||
4804 >                     (containsAll(c) && c.containsAll(this))));
4805          }
4806  
4807 <        /**
4808 <         * Returns a task that when invoked, returns the result of
4809 <         * accumulating the given transformation of all keys using the given
4810 <         * reducer to combine values, and the given basis as an
4811 <         * identity value.
4812 <         *
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);
4807 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4808 >            Node<K,V>[] t;
4809 >            ConcurrentHashMap<K,V> m = map;
4810 >            long n = m.sumCount();
4811 >            int f = (t = m.table) == null ? 0 : t.length;
4812 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4813          }
4814  
4815 <        /**
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) {
4815 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4816              if (action == null) throw new NullPointerException();
4817 <            return new ForEachValueTask<K,V>(map, null, -1, null, action);
4818 <        }
4819 <
4820 <        /**
4821 <         * Returns a task that when invoked, performs the given action
4822 <         * 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);
4817 >            Node<K,V>[] t;
4818 >            if ((t = map.table) != null) {
4819 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4820 >                for (Node<K,V> p; (p = it.advance()) != null; )
4821 >                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
4822 >            }
4823          }
4824  
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        }
4825      }
4826  
4827      // -------------------------------------------------------
4828  
4829      /**
4830 <     * Base for FJ tasks for bulk operations. This adds a variant of
4831 <     * CountedCompleters and some split and merge bookkeeping to
4832 <     * iterator functionality. The forEach and reduce methods are
4833 <     * similar to those illustrated in CountedCompleter documentation,
4834 <     * except that bottom-up reduction completions perform them within
4835 <     * their compute methods. The search methods are like forEach
4836 <     * except they continually poll for success and exit early.  Also,
4837 <     * exceptions are handled in a simpler manner, by just trying to
4838 <     * complete root task exceptionally.
4839 <     */
4840 <    @SuppressWarnings("serial") static abstract class BulkTask<K,V,R> extends Traverser<K,V,R> {
4841 <        final BulkTask<K,V,?> parent;  // completion target
4842 <        int batch;                     // split control; -1 for unknown
4843 <        int pending;                   // completion control
4844 <
4845 <        BulkTask(ConcurrentHashMap<K,V> map, BulkTask<K,V,?> parent,
4846 <                 int batch) {
4847 <            super(map);
4848 <            this.parent = parent;
4849 <            this.batch = batch;
4850 <            if (parent != null && map != null) { // split parent
4851 <                Node[] t;
4852 <                if ((t = parent.tab) == null &&
4853 <                    (t = parent.tab = map.table) != null)
4854 <                    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;
4830 >     * Base class for bulk tasks. Repeats some fields and code from
4831 >     * class Traverser, because we need to subclass CountedCompleter.
4832 >     */
4833 >    @SuppressWarnings("serial")
4834 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4835 >        Node<K,V>[] tab;        // same as Traverser
4836 >        Node<K,V> next;
4837 >        TableStack<K,V> stack, spare;
4838 >        int index;
4839 >        int baseIndex;
4840 >        int baseLimit;
4841 >        final int baseSize;
4842 >        int batch;              // split control
4843 >
4844 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4845 >            super(par);
4846 >            this.batch = b;
4847 >            this.index = this.baseIndex = i;
4848 >            if ((this.tab = t) == null)
4849 >                this.baseSize = this.baseLimit = 0;
4850 >            else if (par == null)
4851 >                this.baseSize = this.baseLimit = t.length;
4852 >            else {
4853 >                this.baseLimit = f;
4854 >                this.baseSize = par.baseSize;
4855              }
4856          }
4857  
4858          /**
4859 <         * Forces root task to complete.
5351 <         * @param ex if null, complete normally, else exceptionally
5352 <         * @return false to simplify use
4859 >         * Same as Traverser version
4860           */
4861 <        final boolean tryCompleteComputation(Throwable ex) {
4862 <            for (BulkTask<K,V,?> a = this;;) {
4863 <                BulkTask<K,V,?> p = a.parent;
4864 <                if (p == null) {
4865 <                    if (ex != null)
4866 <                        a.completeExceptionally(ex);
4861 >        final Node<K,V> advance() {
4862 >            Node<K,V> e;
4863 >            if ((e = next) != null)
4864 >                e = e.next;
4865 >            for (;;) {
4866 >                Node<K,V>[] t; int i, n;
4867 >                if (e != null)
4868 >                    return next = e;
4869 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4870 >                    (n = t.length) <= (i = index) || i < 0)
4871 >                    return next = null;
4872 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
4873 >                    if (e instanceof ForwardingNode) {
4874 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4875 >                        e = null;
4876 >                        pushState(t, i, n);
4877 >                        continue;
4878 >                    }
4879 >                    else if (e instanceof TreeBin)
4880 >                        e = ((TreeBin<K,V>)e).first;
4881                      else
4882 <                        a.quietlyComplete();
5362 <                    return false;
4882 >                        e = null;
4883                  }
4884 <                a = p;
4884 >                if (stack != null)
4885 >                    recoverState(n);
4886 >                else if ((index = i + baseSize) >= n)
4887 >                    index = ++baseIndex;
4888              }
4889          }
4890  
4891 <        /**
4892 <         * Version of tryCompleteComputation for function screening checks
4893 <         */
4894 <        final boolean abortOnNullFunction() {
4895 <            return tryCompleteComputation(new Error("Unexpected null function"));
4896 <        }
4897 <
4898 <        // utilities
4899 <
4900 <        /** CompareAndSet pending count */
4901 <        final boolean casPending(int cmp, int val) {
4902 <            return U.compareAndSwapInt(this, PENDING, cmp, val);
4903 <        }
4904 <
4905 <        /**
4906 <         * Returns approx exp2 of the number of times (minus one) to
4907 <         * split task by two before executing leaf action. This value
4908 <         * is faster to compute and more convenient to use as a guide
4909 <         * to splitting than is the depth, since it is used while
4910 <         * dividing by two anyway.
4911 <         */
4912 <        final int batch() {
4913 <            ConcurrentHashMap<K, V> m; int b; Node[] t;  ForkJoinPool pool;
4914 <            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 <                }
4891 >        private void pushState(Node<K,V>[] t, int i, int n) {
4892 >            TableStack<K,V> s = spare;
4893 >            if (s != null)
4894 >                spare = s.next;
4895 >            else
4896 >                s = new TableStack<K,V>();
4897 >            s.tab = t;
4898 >            s.length = n;
4899 >            s.index = i;
4900 >            s.next = stack;
4901 >            stack = s;
4902 >        }
4903 >
4904 >        private void recoverState(int n) {
4905 >            TableStack<K,V> s; int len;
4906 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
4907 >                n = len;
4908 >                index = s.index;
4909 >                tab = s.tab;
4910 >                s.tab = null;
4911 >                TableStack<K,V> next = s.next;
4912 >                s.next = spare; // save for reuse
4913 >                stack = next;
4914 >                spare = s;
4915              }
4916 +            if (s == null && (index += baseSize) >= n)
4917 +                index = ++baseIndex;
4918          }
5468
4919      }
4920  
4921      /*
4922       * Task classes. Coded in a regular but ugly format/style to
4923       * simplify checks that each variant differs in the right way from
4924 <     * others.
4925 <     */
4926 <
4927 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4928 <        extends BulkAction<K,V,Void> {
4929 <        final Action<K> action;
4924 >     * others. The null screenings exist because compilers cannot tell
4925 >     * that we've already null-checked task arguments, so we force
4926 >     * simplest hoisted bypass to help avoid convoluted traps.
4927 >     */
4928 >    @SuppressWarnings("serial")
4929 >    static final class ForEachKeyTask<K,V>
4930 >        extends BulkTask<K,V,Void> {
4931 >        final Consumer<? super K> action;
4932          ForEachKeyTask
4933 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4934 <             ForEachKeyTask<K,V> nextTask,
4935 <             Action<K> action) {
5484 <            super(m, p, b, nextTask);
4933 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4934 >             Consumer<? super K> action) {
4935 >            super(p, b, i, f, t);
4936              this.action = action;
4937          }
4938 <        @SuppressWarnings("unchecked") public final boolean exec() {
4939 <            final Action<K> action = this.action;
4940 <            if (action == null)
4941 <                return abortOnNullFunction();
4942 <            ForEachKeyTask<K,V> subtasks = null;
4943 <            try {
4944 <                int b = batch(), c;
4945 <                while (b > 1 && baseIndex != baseLimit) {
4946 <                    do {} while (!casPending(c = pending, c+1));
4947 <                    (subtasks = new ForEachKeyTask<K,V>
4948 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4949 <                }
4950 <                while (advance() != null)
5500 <                    action.apply((K)nextKey);
5501 <            } catch (Throwable ex) {
5502 <                return tryCompleteComputation(ex);
4938 >        public final void compute() {
4939 >            final Consumer<? super K> action;
4940 >            if ((action = this.action) != null) {
4941 >                for (int i = baseIndex, f, h; batch > 0 &&
4942 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4943 >                    addToPendingCount(1);
4944 >                    new ForEachKeyTask<K,V>
4945 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4946 >                         action).fork();
4947 >                }
4948 >                for (Node<K,V> p; (p = advance()) != null;)
4949 >                    action.accept(p.key);
4950 >                propagateCompletion();
4951              }
5504            tryComplete(subtasks);
5505            return false;
4952          }
4953      }
4954  
4955 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4956 <        extends BulkAction<K,V,Void> {
4957 <        final Action<V> action;
4955 >    @SuppressWarnings("serial")
4956 >    static final class ForEachValueTask<K,V>
4957 >        extends BulkTask<K,V,Void> {
4958 >        final Consumer<? super V> action;
4959          ForEachValueTask
4960 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4961 <             ForEachValueTask<K,V> nextTask,
4962 <             Action<V> action) {
5516 <            super(m, p, b, nextTask);
4960 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4961 >             Consumer<? super V> action) {
4962 >            super(p, b, i, f, t);
4963              this.action = action;
4964          }
4965 <        @SuppressWarnings("unchecked") public final boolean exec() {
4966 <            final Action<V> action = this.action;
4967 <            if (action == null)
4968 <                return abortOnNullFunction();
4969 <            ForEachValueTask<K,V> subtasks = null;
4970 <            try {
4971 <                int b = batch(), c;
4972 <                while (b > 1 && baseIndex != baseLimit) {
4973 <                    do {} while (!casPending(c = pending, c+1));
4974 <                    (subtasks = new ForEachValueTask<K,V>
4975 <                     (map, this, b >>>= 1, subtasks, action)).fork();
4976 <                }
4977 <                Object v;
5532 <                while ((v = advance()) != null)
5533 <                    action.apply((V)v);
5534 <            } catch (Throwable ex) {
5535 <                return tryCompleteComputation(ex);
4965 >        public final void compute() {
4966 >            final Consumer<? super V> action;
4967 >            if ((action = this.action) != null) {
4968 >                for (int i = baseIndex, f, h; batch > 0 &&
4969 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4970 >                    addToPendingCount(1);
4971 >                    new ForEachValueTask<K,V>
4972 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4973 >                         action).fork();
4974 >                }
4975 >                for (Node<K,V> p; (p = advance()) != null;)
4976 >                    action.accept(p.val);
4977 >                propagateCompletion();
4978              }
5537            tryComplete(subtasks);
5538            return false;
4979          }
4980      }
4981  
4982 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4983 <        extends BulkAction<K,V,Void> {
4984 <        final Action<Entry<K,V>> action;
4982 >    @SuppressWarnings("serial")
4983 >    static final class ForEachEntryTask<K,V>
4984 >        extends BulkTask<K,V,Void> {
4985 >        final Consumer<? super Entry<K,V>> action;
4986          ForEachEntryTask
4987 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
4988 <             ForEachEntryTask<K,V> nextTask,
4989 <             Action<Entry<K,V>> action) {
5549 <            super(m, p, b, nextTask);
4987 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4988 >             Consumer<? super Entry<K,V>> action) {
4989 >            super(p, b, i, f, t);
4990              this.action = action;
4991          }
4992 <        @SuppressWarnings("unchecked") public final boolean exec() {
4993 <            final Action<Entry<K,V>> action = this.action;
4994 <            if (action == null)
4995 <                return abortOnNullFunction();
4996 <            ForEachEntryTask<K,V> subtasks = null;
4997 <            try {
4998 <                int b = batch(), c;
4999 <                while (b > 1 && baseIndex != baseLimit) {
5000 <                    do {} while (!casPending(c = pending, c+1));
5001 <                    (subtasks = new ForEachEntryTask<K,V>
5002 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5003 <                }
5004 <                Object v;
5565 <                while ((v = advance()) != null)
5566 <                    action.apply(entryFor((K)nextKey, (V)v));
5567 <            } catch (Throwable ex) {
5568 <                return tryCompleteComputation(ex);
4992 >        public final void compute() {
4993 >            final Consumer<? super Entry<K,V>> action;
4994 >            if ((action = this.action) != null) {
4995 >                for (int i = baseIndex, f, h; batch > 0 &&
4996 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4997 >                    addToPendingCount(1);
4998 >                    new ForEachEntryTask<K,V>
4999 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5000 >                         action).fork();
5001 >                }
5002 >                for (Node<K,V> p; (p = advance()) != null; )
5003 >                    action.accept(p);
5004 >                propagateCompletion();
5005              }
5570            tryComplete(subtasks);
5571            return false;
5006          }
5007      }
5008  
5009 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5010 <        extends BulkAction<K,V,Void> {
5011 <        final BiAction<K,V> action;
5009 >    @SuppressWarnings("serial")
5010 >    static final class ForEachMappingTask<K,V>
5011 >        extends BulkTask<K,V,Void> {
5012 >        final BiConsumer<? super K, ? super V> action;
5013          ForEachMappingTask
5014 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5015 <             ForEachMappingTask<K,V> nextTask,
5016 <             BiAction<K,V> action) {
5582 <            super(m, p, b, nextTask);
5014 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5015 >             BiConsumer<? super K,? super V> action) {
5016 >            super(p, b, i, f, t);
5017              this.action = action;
5018          }
5019 <        @SuppressWarnings("unchecked") public final boolean exec() {
5020 <            final BiAction<K,V> action = this.action;
5021 <            if (action == null)
5022 <                return abortOnNullFunction();
5023 <            ForEachMappingTask<K,V> subtasks = null;
5024 <            try {
5025 <                int b = batch(), c;
5026 <                while (b > 1 && baseIndex != baseLimit) {
5027 <                    do {} while (!casPending(c = pending, c+1));
5028 <                    (subtasks = new ForEachMappingTask<K,V>
5029 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5030 <                }
5031 <                Object v;
5598 <                while ((v = advance()) != null)
5599 <                    action.apply((K)nextKey, (V)v);
5600 <            } catch (Throwable ex) {
5601 <                return tryCompleteComputation(ex);
5019 >        public final void compute() {
5020 >            final BiConsumer<? super K, ? super V> action;
5021 >            if ((action = this.action) != null) {
5022 >                for (int i = baseIndex, f, h; batch > 0 &&
5023 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5024 >                    addToPendingCount(1);
5025 >                    new ForEachMappingTask<K,V>
5026 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5027 >                         action).fork();
5028 >                }
5029 >                for (Node<K,V> p; (p = advance()) != null; )
5030 >                    action.accept(p.key, p.val);
5031 >                propagateCompletion();
5032              }
5603            tryComplete(subtasks);
5604            return false;
5033          }
5034      }
5035  
5036 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5037 <        extends BulkAction<K,V,Void> {
5038 <        final Fun<? super K, ? extends U> transformer;
5039 <        final Action<U> action;
5036 >    @SuppressWarnings("serial")
5037 >    static final class ForEachTransformedKeyTask<K,V,U>
5038 >        extends BulkTask<K,V,Void> {
5039 >        final Function<? super K, ? extends U> transformer;
5040 >        final Consumer<? super U> action;
5041          ForEachTransformedKeyTask
5042 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5043 <             ForEachTransformedKeyTask<K,V,U> nextTask,
5044 <             Fun<? super K, ? extends U> transformer,
5045 <             Action<U> action) {
5046 <            super(m, p, b, nextTask);
5047 <            this.transformer = transformer;
5048 <            this.action = action;
5049 <
5050 <        }
5051 <        @SuppressWarnings("unchecked") public final boolean exec() {
5052 <            final Fun<? super K, ? extends U> transformer =
5053 <                this.transformer;
5054 <            final Action<U> action = this.action;
5055 <            if (transformer == null || action == null)
5056 <                return abortOnNullFunction();
5057 <            ForEachTransformedKeyTask<K,V,U> subtasks = null;
5058 <            try {
5059 <                int b = batch(), c;
5060 <                while (b > 1 && baseIndex != baseLimit) {
5061 <                    do {} while (!casPending(c = pending, c+1));
5062 <                    (subtasks = new ForEachTransformedKeyTask<K,V,U>
5063 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5064 <                }
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);
5042 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5043 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5044 >            super(p, b, i, f, t);
5045 >            this.transformer = transformer; this.action = action;
5046 >        }
5047 >        public final void compute() {
5048 >            final Function<? super K, ? extends U> transformer;
5049 >            final Consumer<? super U> action;
5050 >            if ((transformer = this.transformer) != null &&
5051 >                (action = this.action) != null) {
5052 >                for (int i = baseIndex, f, h; batch > 0 &&
5053 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5054 >                    addToPendingCount(1);
5055 >                    new ForEachTransformedKeyTask<K,V,U>
5056 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5057 >                         transformer, action).fork();
5058 >                }
5059 >                for (Node<K,V> p; (p = advance()) != null; ) {
5060 >                    U u;
5061 >                    if ((u = transformer.apply(p.key)) != null)
5062 >                        action.accept(u);
5063 >                }
5064 >                propagateCompletion();
5065              }
5644            tryComplete(subtasks);
5645            return false;
5066          }
5067      }
5068  
5069 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5070 <        extends BulkAction<K,V,Void> {
5071 <        final Fun<? super V, ? extends U> transformer;
5072 <        final Action<U> action;
5069 >    @SuppressWarnings("serial")
5070 >    static final class ForEachTransformedValueTask<K,V,U>
5071 >        extends BulkTask<K,V,Void> {
5072 >        final Function<? super V, ? extends U> transformer;
5073 >        final Consumer<? super U> action;
5074          ForEachTransformedValueTask
5075 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5076 <             ForEachTransformedValueTask<K,V,U> nextTask,
5077 <             Fun<? super V, ? extends U> transformer,
5078 <             Action<U> action) {
5079 <            super(m, p, b, nextTask);
5080 <            this.transformer = transformer;
5081 <            this.action = action;
5082 <
5083 <        }
5084 <        @SuppressWarnings("unchecked") public final boolean exec() {
5085 <            final Fun<? super V, ? extends U> transformer =
5086 <                this.transformer;
5087 <            final Action<U> action = this.action;
5088 <            if (transformer == null || action == null)
5089 <                return abortOnNullFunction();
5090 <            ForEachTransformedValueTask<K,V,U> subtasks = null;
5091 <            try {
5092 <                int b = batch(), c;
5093 <                while (b > 1 && baseIndex != baseLimit) {
5094 <                    do {} while (!casPending(c = pending, c+1));
5095 <                    (subtasks = new ForEachTransformedValueTask<K,V,U>
5096 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5097 <                }
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);
5075 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5076 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5077 >            super(p, b, i, f, t);
5078 >            this.transformer = transformer; this.action = action;
5079 >        }
5080 >        public final void compute() {
5081 >            final Function<? super V, ? extends U> transformer;
5082 >            final Consumer<? super U> action;
5083 >            if ((transformer = this.transformer) != null &&
5084 >                (action = this.action) != null) {
5085 >                for (int i = baseIndex, f, h; batch > 0 &&
5086 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5087 >                    addToPendingCount(1);
5088 >                    new ForEachTransformedValueTask<K,V,U>
5089 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5090 >                         transformer, action).fork();
5091 >                }
5092 >                for (Node<K,V> p; (p = advance()) != null; ) {
5093 >                    U u;
5094 >                    if ((u = transformer.apply(p.val)) != null)
5095 >                        action.accept(u);
5096 >                }
5097 >                propagateCompletion();
5098              }
5685            tryComplete(subtasks);
5686            return false;
5099          }
5100      }
5101  
5102 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5103 <        extends BulkAction<K,V,Void> {
5104 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5105 <        final Action<U> action;
5102 >    @SuppressWarnings("serial")
5103 >    static final class ForEachTransformedEntryTask<K,V,U>
5104 >        extends BulkTask<K,V,Void> {
5105 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5106 >        final Consumer<? super U> action;
5107          ForEachTransformedEntryTask
5108 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5109 <             ForEachTransformedEntryTask<K,V,U> nextTask,
5110 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5111 <             Action<U> action) {
5112 <            super(m, p, b, nextTask);
5113 <            this.transformer = transformer;
5114 <            this.action = action;
5115 <
5116 <        }
5117 <        @SuppressWarnings("unchecked") public final boolean exec() {
5118 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5119 <                this.transformer;
5120 <            final Action<U> action = this.action;
5121 <            if (transformer == null || action == null)
5122 <                return abortOnNullFunction();
5123 <            ForEachTransformedEntryTask<K,V,U> subtasks = null;
5124 <            try {
5125 <                int b = batch(), c;
5126 <                while (b > 1 && baseIndex != baseLimit) {
5127 <                    do {} while (!casPending(c = pending, c+1));
5128 <                    (subtasks = new ForEachTransformedEntryTask<K,V,U>
5129 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5130 <                }
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);
5108 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5109 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5110 >            super(p, b, i, f, t);
5111 >            this.transformer = transformer; this.action = action;
5112 >        }
5113 >        public final void compute() {
5114 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5115 >            final Consumer<? super U> action;
5116 >            if ((transformer = this.transformer) != null &&
5117 >                (action = this.action) != null) {
5118 >                for (int i = baseIndex, f, h; batch > 0 &&
5119 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5120 >                    addToPendingCount(1);
5121 >                    new ForEachTransformedEntryTask<K,V,U>
5122 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5123 >                         transformer, action).fork();
5124 >                }
5125 >                for (Node<K,V> p; (p = advance()) != null; ) {
5126 >                    U u;
5127 >                    if ((u = transformer.apply(p)) != null)
5128 >                        action.accept(u);
5129 >                }
5130 >                propagateCompletion();
5131              }
5726            tryComplete(subtasks);
5727            return false;
5132          }
5133      }
5134  
5135 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5136 <        extends BulkAction<K,V,Void> {
5137 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5138 <        final Action<U> action;
5135 >    @SuppressWarnings("serial")
5136 >    static final class ForEachTransformedMappingTask<K,V,U>
5137 >        extends BulkTask<K,V,Void> {
5138 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5139 >        final Consumer<? super U> action;
5140          ForEachTransformedMappingTask
5141 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5142 <             ForEachTransformedMappingTask<K,V,U> nextTask,
5143 <             BiFun<? super K, ? super V, ? extends U> transformer,
5144 <             Action<U> action) {
5145 <            super(m, p, b, nextTask);
5146 <            this.transformer = transformer;
5147 <            this.action = action;
5148 <
5149 <        }
5150 <        @SuppressWarnings("unchecked") public final boolean exec() {
5151 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5152 <                this.transformer;
5153 <            final Action<U> action = this.action;
5154 <            if (transformer == null || action == null)
5155 <                return abortOnNullFunction();
5156 <            ForEachTransformedMappingTask<K,V,U> subtasks = null;
5157 <            try {
5158 <                int b = batch(), c;
5159 <                while (b > 1 && baseIndex != baseLimit) {
5160 <                    do {} while (!casPending(c = pending, c+1));
5161 <                    (subtasks = new ForEachTransformedMappingTask<K,V,U>
5162 <                     (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);
5141 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5142 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5143 >             Consumer<? super U> action) {
5144 >            super(p, b, i, f, t);
5145 >            this.transformer = transformer; this.action = action;
5146 >        }
5147 >        public final void compute() {
5148 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5149 >            final Consumer<? super U> action;
5150 >            if ((transformer = this.transformer) != null &&
5151 >                (action = this.action) != null) {
5152 >                for (int i = baseIndex, f, h; batch > 0 &&
5153 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5154 >                    addToPendingCount(1);
5155 >                    new ForEachTransformedMappingTask<K,V,U>
5156 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5157 >                         transformer, action).fork();
5158 >                }
5159 >                for (Node<K,V> p; (p = advance()) != null; ) {
5160 >                    U u;
5161 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5162 >                        action.accept(u);
5163                  }
5164 <            } catch (Throwable ex) {
5765 <                return tryCompleteComputation(ex);
5164 >                propagateCompletion();
5165              }
5767            tryComplete(subtasks);
5768            return false;
5166          }
5167      }
5168  
5169 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5170 <        extends BulkAction<K,V,U> {
5171 <        final Fun<? super K, ? extends U> searchFunction;
5169 >    @SuppressWarnings("serial")
5170 >    static final class SearchKeysTask<K,V,U>
5171 >        extends BulkTask<K,V,U> {
5172 >        final Function<? super K, ? extends U> searchFunction;
5173          final AtomicReference<U> result;
5174          SearchKeysTask
5175 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5176 <             SearchKeysTask<K,V,U> nextTask,
5779 <             Fun<? super K, ? extends U> searchFunction,
5175 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5176 >             Function<? super K, ? extends U> searchFunction,
5177               AtomicReference<U> result) {
5178 <            super(m, p, b, nextTask);
5178 >            super(p, b, i, f, t);
5179              this.searchFunction = searchFunction; this.result = result;
5180          }
5181 <        @SuppressWarnings("unchecked") public final boolean exec() {
5182 <            AtomicReference<U> result = this.result;
5183 <            final Fun<? super K, ? extends U> searchFunction =
5184 <                this.searchFunction;
5185 <            if (searchFunction == null || result == null)
5186 <                return abortOnNullFunction();
5187 <            SearchKeysTask<K,V,U> subtasks = null;
5188 <            try {
5189 <                int b = batch(), c;
5190 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5191 <                    do {} while (!casPending(c = pending, c+1));
5192 <                    (subtasks = new SearchKeysTask<K,V,U>
5193 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5194 <                }
5195 <                U u;
5196 <                while (result.get() == null && advance() != null) {
5197 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
5181 >        public final U getRawResult() { return result.get(); }
5182 >        public final void compute() {
5183 >            final Function<? super K, ? extends U> searchFunction;
5184 >            final AtomicReference<U> result;
5185 >            if ((searchFunction = this.searchFunction) != null &&
5186 >                (result = this.result) != null) {
5187 >                for (int i = baseIndex, f, h; batch > 0 &&
5188 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5189 >                    if (result.get() != null)
5190 >                        return;
5191 >                    addToPendingCount(1);
5192 >                    new SearchKeysTask<K,V,U>
5193 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5194 >                         searchFunction, result).fork();
5195 >                }
5196 >                while (result.get() == null) {
5197 >                    U u;
5198 >                    Node<K,V> p;
5199 >                    if ((p = advance()) == null) {
5200 >                        propagateCompletion();
5201 >                        break;
5202 >                    }
5203 >                    if ((u = searchFunction.apply(p.key)) != null) {
5204                          if (result.compareAndSet(null, u))
5205 <                            tryCompleteComputation(null);
5205 >                            quietlyCompleteRoot();
5206                          break;
5207                      }
5208                  }
5806            } catch (Throwable ex) {
5807                return tryCompleteComputation(ex);
5209              }
5809            tryComplete(subtasks);
5810            return false;
5210          }
5812        public final U getRawResult() { return result.get(); }
5211      }
5212  
5213 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5214 <        extends BulkAction<K,V,U> {
5215 <        final Fun<? super V, ? extends U> searchFunction;
5213 >    @SuppressWarnings("serial")
5214 >    static final class SearchValuesTask<K,V,U>
5215 >        extends BulkTask<K,V,U> {
5216 >        final Function<? super V, ? extends U> searchFunction;
5217          final AtomicReference<U> result;
5218          SearchValuesTask
5219 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5220 <             SearchValuesTask<K,V,U> nextTask,
5822 <             Fun<? super V, ? extends U> searchFunction,
5219 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5220 >             Function<? super V, ? extends U> searchFunction,
5221               AtomicReference<U> result) {
5222 <            super(m, p, b, nextTask);
5222 >            super(p, b, i, f, t);
5223              this.searchFunction = searchFunction; this.result = result;
5224          }
5225 <        @SuppressWarnings("unchecked") public final boolean exec() {
5226 <            AtomicReference<U> result = this.result;
5227 <            final Fun<? super V, ? extends U> searchFunction =
5228 <                this.searchFunction;
5229 <            if (searchFunction == null || result == null)
5230 <                return abortOnNullFunction();
5231 <            SearchValuesTask<K,V,U> subtasks = null;
5232 <            try {
5233 <                int b = batch(), c;
5234 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5235 <                    do {} while (!casPending(c = pending, c+1));
5236 <                    (subtasks = new SearchValuesTask<K,V,U>
5237 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5238 <                }
5239 <                Object v; U u;
5240 <                while (result.get() == null && (v = advance()) != null) {
5241 <                    if ((u = searchFunction.apply((V)v)) != null) {
5225 >        public final U getRawResult() { return result.get(); }
5226 >        public final void compute() {
5227 >            final Function<? super V, ? extends U> searchFunction;
5228 >            final AtomicReference<U> result;
5229 >            if ((searchFunction = this.searchFunction) != null &&
5230 >                (result = this.result) != null) {
5231 >                for (int i = baseIndex, f, h; batch > 0 &&
5232 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5233 >                    if (result.get() != null)
5234 >                        return;
5235 >                    addToPendingCount(1);
5236 >                    new SearchValuesTask<K,V,U>
5237 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5238 >                         searchFunction, result).fork();
5239 >                }
5240 >                while (result.get() == null) {
5241 >                    U u;
5242 >                    Node<K,V> p;
5243 >                    if ((p = advance()) == null) {
5244 >                        propagateCompletion();
5245 >                        break;
5246 >                    }
5247 >                    if ((u = searchFunction.apply(p.val)) != null) {
5248                          if (result.compareAndSet(null, u))
5249 <                            tryCompleteComputation(null);
5249 >                            quietlyCompleteRoot();
5250                          break;
5251                      }
5252                  }
5849            } catch (Throwable ex) {
5850                return tryCompleteComputation(ex);
5253              }
5852            tryComplete(subtasks);
5853            return false;
5254          }
5855        public final U getRawResult() { return result.get(); }
5255      }
5256  
5257 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5258 <        extends BulkAction<K,V,U> {
5259 <        final Fun<Entry<K,V>, ? extends U> searchFunction;
5257 >    @SuppressWarnings("serial")
5258 >    static final class SearchEntriesTask<K,V,U>
5259 >        extends BulkTask<K,V,U> {
5260 >        final Function<Entry<K,V>, ? extends U> searchFunction;
5261          final AtomicReference<U> result;
5262          SearchEntriesTask
5263 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5264 <             SearchEntriesTask<K,V,U> nextTask,
5865 <             Fun<Entry<K,V>, ? extends U> searchFunction,
5263 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5264 >             Function<Entry<K,V>, ? extends U> searchFunction,
5265               AtomicReference<U> result) {
5266 <            super(m, p, b, nextTask);
5266 >            super(p, b, i, f, t);
5267              this.searchFunction = searchFunction; this.result = result;
5268          }
5269 <        @SuppressWarnings("unchecked") public final boolean exec() {
5270 <            AtomicReference<U> result = this.result;
5271 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
5272 <                this.searchFunction;
5273 <            if (searchFunction == null || result == null)
5274 <                return abortOnNullFunction();
5275 <            SearchEntriesTask<K,V,U> subtasks = null;
5276 <            try {
5277 <                int b = batch(), c;
5278 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5279 <                    do {} while (!casPending(c = pending, c+1));
5280 <                    (subtasks = new SearchEntriesTask<K,V,U>
5281 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5282 <                }
5283 <                Object v; U u;
5284 <                while (result.get() == null && (v = advance()) != null) {
5285 <                    if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
5286 <                        if (result.compareAndSet(null, u))
5287 <                            tryCompleteComputation(null);
5269 >        public final U getRawResult() { return result.get(); }
5270 >        public final void compute() {
5271 >            final Function<Entry<K,V>, ? extends U> searchFunction;
5272 >            final AtomicReference<U> result;
5273 >            if ((searchFunction = this.searchFunction) != null &&
5274 >                (result = this.result) != null) {
5275 >                for (int i = baseIndex, f, h; batch > 0 &&
5276 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5277 >                    if (result.get() != null)
5278 >                        return;
5279 >                    addToPendingCount(1);
5280 >                    new SearchEntriesTask<K,V,U>
5281 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5282 >                         searchFunction, result).fork();
5283 >                }
5284 >                while (result.get() == null) {
5285 >                    U u;
5286 >                    Node<K,V> p;
5287 >                    if ((p = advance()) == null) {
5288 >                        propagateCompletion();
5289                          break;
5290                      }
5291 +                    if ((u = searchFunction.apply(p)) != null) {
5292 +                        if (result.compareAndSet(null, u))
5293 +                            quietlyCompleteRoot();
5294 +                        return;
5295 +                    }
5296                  }
5892            } catch (Throwable ex) {
5893                return tryCompleteComputation(ex);
5297              }
5895            tryComplete(subtasks);
5896            return false;
5298          }
5898        public final U getRawResult() { return result.get(); }
5299      }
5300  
5301 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5302 <        extends BulkAction<K,V,U> {
5303 <        final BiFun<? super K, ? super V, ? extends U> searchFunction;
5301 >    @SuppressWarnings("serial")
5302 >    static final class SearchMappingsTask<K,V,U>
5303 >        extends BulkTask<K,V,U> {
5304 >        final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5305          final AtomicReference<U> result;
5306          SearchMappingsTask
5307 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5308 <             SearchMappingsTask<K,V,U> nextTask,
5908 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
5307 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5308 >             BiFunction<? super K, ? super V, ? extends U> searchFunction,
5309               AtomicReference<U> result) {
5310 <            super(m, p, b, nextTask);
5310 >            super(p, b, i, f, t);
5311              this.searchFunction = searchFunction; this.result = result;
5312          }
5313 <        @SuppressWarnings("unchecked") public final boolean exec() {
5314 <            AtomicReference<U> result = this.result;
5315 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
5316 <                this.searchFunction;
5317 <            if (searchFunction == null || result == null)
5318 <                return abortOnNullFunction();
5319 <            SearchMappingsTask<K,V,U> subtasks = null;
5320 <            try {
5321 <                int b = batch(), c;
5322 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5323 <                    do {} while (!casPending(c = pending, c+1));
5324 <                    (subtasks = new SearchMappingsTask<K,V,U>
5325 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5326 <                }
5327 <                Object v; U u;
5328 <                while (result.get() == null && (v = advance()) != null) {
5329 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5313 >        public final U getRawResult() { return result.get(); }
5314 >        public final void compute() {
5315 >            final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5316 >            final AtomicReference<U> result;
5317 >            if ((searchFunction = this.searchFunction) != null &&
5318 >                (result = this.result) != null) {
5319 >                for (int i = baseIndex, f, h; batch > 0 &&
5320 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5321 >                    if (result.get() != null)
5322 >                        return;
5323 >                    addToPendingCount(1);
5324 >                    new SearchMappingsTask<K,V,U>
5325 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5326 >                         searchFunction, result).fork();
5327 >                }
5328 >                while (result.get() == null) {
5329 >                    U u;
5330 >                    Node<K,V> p;
5331 >                    if ((p = advance()) == null) {
5332 >                        propagateCompletion();
5333 >                        break;
5334 >                    }
5335 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5336                          if (result.compareAndSet(null, u))
5337 <                            tryCompleteComputation(null);
5337 >                            quietlyCompleteRoot();
5338                          break;
5339                      }
5340                  }
5935            } catch (Throwable ex) {
5936                return tryCompleteComputation(ex);
5341              }
5938            tryComplete(subtasks);
5939            return false;
5342          }
5941        public final U getRawResult() { return result.get(); }
5343      }
5344  
5345 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5345 >    @SuppressWarnings("serial")
5346 >    static final class ReduceKeysTask<K,V>
5347          extends BulkTask<K,V,K> {
5348 <        final BiFun<? super K, ? super K, ? extends K> reducer;
5348 >        final BiFunction<? super K, ? super K, ? extends K> reducer;
5349          K result;
5350          ReduceKeysTask<K,V> rights, nextRight;
5351          ReduceKeysTask
5352 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5352 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5353               ReduceKeysTask<K,V> nextRight,
5354 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5355 <            super(m, p, b); this.nextRight = nextRight;
5354 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
5355 >            super(p, b, i, f, t); this.nextRight = nextRight;
5356              this.reducer = reducer;
5357          }
5358 <        @SuppressWarnings("unchecked") public final boolean exec() {
5359 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5360 <                this.reducer;
5361 <            if (reducer == null)
5362 <                return abortOnNullFunction();
5363 <            try {
5364 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5963 <                    do {} while (!casPending(c = pending, c+1));
5358 >        public final K getRawResult() { return result; }
5359 >        public final void compute() {
5360 >            final BiFunction<? super K, ? super K, ? extends K> reducer;
5361 >            if ((reducer = this.reducer) != null) {
5362 >                for (int i = baseIndex, f, h; batch > 0 &&
5363 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5364 >                    addToPendingCount(1);
5365                      (rights = new ReduceKeysTask<K,V>
5366 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5366 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5367 >                      rights, reducer)).fork();
5368                  }
5369                  K r = null;
5370 <                while (advance() != null) {
5371 <                    K u = (K)nextKey;
5372 <                    r = (r == null) ? u : reducer.apply(r, u);
5370 >                for (Node<K,V> p; (p = advance()) != null; ) {
5371 >                    K u = p.key;
5372 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5373                  }
5374                  result = r;
5375 <                for (ReduceKeysTask<K,V> t = this, s;;) {
5376 <                    int c; BulkTask<K,V,?> par; K tr, sr;
5377 <                    if ((c = t.pending) == 0) {
5378 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5379 <                            if ((sr = s.result) != null)
5380 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5381 <                        }
5382 <                        if ((par = t.parent) == null ||
5383 <                            !(par instanceof ReduceKeysTask)) {
5384 <                            t.quietlyComplete();
5385 <                            break;
5386 <                        }
5985 <                        t = (ReduceKeysTask<K,V>)par;
5375 >                CountedCompleter<?> c;
5376 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5377 >                    @SuppressWarnings("unchecked")
5378 >                    ReduceKeysTask<K,V>
5379 >                        t = (ReduceKeysTask<K,V>)c,
5380 >                        s = t.rights;
5381 >                    while (s != null) {
5382 >                        K tr, sr;
5383 >                        if ((sr = s.result) != null)
5384 >                            t.result = (((tr = t.result) == null) ? sr :
5385 >                                        reducer.apply(tr, sr));
5386 >                        s = t.rights = s.nextRight;
5387                      }
5987                    else if (t.casPending(c, c - 1))
5988                        break;
5388                  }
5990            } catch (Throwable ex) {
5991                return tryCompleteComputation(ex);
5389              }
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;
5390          }
6002        public final K getRawResult() { return result; }
5391      }
5392  
5393 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5393 >    @SuppressWarnings("serial")
5394 >    static final class ReduceValuesTask<K,V>
5395          extends BulkTask<K,V,V> {
5396 <        final BiFun<? super V, ? super V, ? extends V> reducer;
5396 >        final BiFunction<? super V, ? super V, ? extends V> reducer;
5397          V result;
5398          ReduceValuesTask<K,V> rights, nextRight;
5399          ReduceValuesTask
5400 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5400 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5401               ReduceValuesTask<K,V> nextRight,
5402 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5403 <            super(m, p, b); this.nextRight = nextRight;
5402 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
5403 >            super(p, b, i, f, t); this.nextRight = nextRight;
5404              this.reducer = reducer;
5405          }
5406 <        @SuppressWarnings("unchecked") public final boolean exec() {
5407 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5408 <                this.reducer;
5409 <            if (reducer == null)
5410 <                return abortOnNullFunction();
5411 <            try {
5412 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6024 <                    do {} while (!casPending(c = pending, c+1));
5406 >        public final V getRawResult() { return result; }
5407 >        public final void compute() {
5408 >            final BiFunction<? super V, ? super V, ? extends V> reducer;
5409 >            if ((reducer = this.reducer) != null) {
5410 >                for (int i = baseIndex, f, h; batch > 0 &&
5411 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5412 >                    addToPendingCount(1);
5413                      (rights = new ReduceValuesTask<K,V>
5414 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5414 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5415 >                      rights, reducer)).fork();
5416                  }
5417                  V r = null;
5418 <                Object v;
5419 <                while ((v = advance()) != null) {
5420 <                    V u = (V)v;
6032 <                    r = (r == null) ? u : reducer.apply(r, u);
5418 >                for (Node<K,V> p; (p = advance()) != null; ) {
5419 >                    V v = p.val;
5420 >                    r = (r == null) ? v : reducer.apply(r, v);
5421                  }
5422                  result = r;
5423 <                for (ReduceValuesTask<K,V> t = this, s;;) {
5424 <                    int c; BulkTask<K,V,?> par; V tr, sr;
5425 <                    if ((c = t.pending) == 0) {
5426 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5427 <                            if ((sr = s.result) != null)
5428 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5429 <                        }
5430 <                        if ((par = t.parent) == null ||
5431 <                            !(par instanceof ReduceValuesTask)) {
5432 <                            t.quietlyComplete();
5433 <                            break;
5434 <                        }
6047 <                        t = (ReduceValuesTask<K,V>)par;
5423 >                CountedCompleter<?> c;
5424 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5425 >                    @SuppressWarnings("unchecked")
5426 >                    ReduceValuesTask<K,V>
5427 >                        t = (ReduceValuesTask<K,V>)c,
5428 >                        s = t.rights;
5429 >                    while (s != null) {
5430 >                        V tr, sr;
5431 >                        if ((sr = s.result) != null)
5432 >                            t.result = (((tr = t.result) == null) ? sr :
5433 >                                        reducer.apply(tr, sr));
5434 >                        s = t.rights = s.nextRight;
5435                      }
6049                    else if (t.casPending(c, c - 1))
6050                        break;
5436                  }
6052            } catch (Throwable ex) {
6053                return tryCompleteComputation(ex);
6054            }
6055            ReduceValuesTask<K,V> s = rights;
6056            if (s != null && !inForkJoinPool()) {
6057                do  {
6058                    if (s.tryUnfork())
6059                        s.exec();
6060                } while ((s = s.nextRight) != null);
5437              }
6062            return false;
5438          }
6064        public final V getRawResult() { return result; }
5439      }
5440  
5441 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5441 >    @SuppressWarnings("serial")
5442 >    static final class ReduceEntriesTask<K,V>
5443          extends BulkTask<K,V,Map.Entry<K,V>> {
5444 <        final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5444 >        final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5445          Map.Entry<K,V> result;
5446          ReduceEntriesTask<K,V> rights, nextRight;
5447          ReduceEntriesTask
5448 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5448 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5449               ReduceEntriesTask<K,V> nextRight,
5450 <             BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5451 <            super(m, p, b); this.nextRight = nextRight;
5450 >             BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5451 >            super(p, b, i, f, t); this.nextRight = nextRight;
5452              this.reducer = reducer;
5453          }
5454 <        @SuppressWarnings("unchecked") public final boolean exec() {
5455 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
5456 <                this.reducer;
5457 <            if (reducer == null)
5458 <                return abortOnNullFunction();
5459 <            try {
5460 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6086 <                    do {} while (!casPending(c = pending, c+1));
5454 >        public final Map.Entry<K,V> getRawResult() { return result; }
5455 >        public final void compute() {
5456 >            final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5457 >            if ((reducer = this.reducer) != null) {
5458 >                for (int i = baseIndex, f, h; batch > 0 &&
5459 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5460 >                    addToPendingCount(1);
5461                      (rights = new ReduceEntriesTask<K,V>
5462 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5462 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5463 >                      rights, reducer)).fork();
5464                  }
5465                  Map.Entry<K,V> r = null;
5466 <                Object v;
5467 <                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 <                }
5466 >                for (Node<K,V> p; (p = advance()) != null; )
5467 >                    r = (r == null) ? p : reducer.apply(r, p);
5468                  result = r;
5469 <                for (ReduceEntriesTask<K,V> t = this, s;;) {
5470 <                    int c; BulkTask<K,V,?> par; Map.Entry<K,V> tr, sr;
5471 <                    if ((c = t.pending) == 0) {
5472 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5473 <                            if ((sr = s.result) != null)
5474 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5475 <                        }
5476 <                        if ((par = t.parent) == null ||
5477 <                            !(par instanceof ReduceEntriesTask)) {
5478 <                            t.quietlyComplete();
5479 <                            break;
5480 <                        }
6109 <                        t = (ReduceEntriesTask<K,V>)par;
5469 >                CountedCompleter<?> c;
5470 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5471 >                    @SuppressWarnings("unchecked")
5472 >                    ReduceEntriesTask<K,V>
5473 >                        t = (ReduceEntriesTask<K,V>)c,
5474 >                        s = t.rights;
5475 >                    while (s != null) {
5476 >                        Map.Entry<K,V> tr, sr;
5477 >                        if ((sr = s.result) != null)
5478 >                            t.result = (((tr = t.result) == null) ? sr :
5479 >                                        reducer.apply(tr, sr));
5480 >                        s = t.rights = s.nextRight;
5481                      }
6111                    else if (t.casPending(c, c - 1))
6112                        break;
5482                  }
6114            } catch (Throwable ex) {
6115                return tryCompleteComputation(ex);
6116            }
6117            ReduceEntriesTask<K,V> s = rights;
6118            if (s != null && !inForkJoinPool()) {
6119                do  {
6120                    if (s.tryUnfork())
6121                        s.exec();
6122                } while ((s = s.nextRight) != null);
5483              }
6124            return false;
5484          }
6126        public final Map.Entry<K,V> getRawResult() { return result; }
5485      }
5486  
5487 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5487 >    @SuppressWarnings("serial")
5488 >    static final class MapReduceKeysTask<K,V,U>
5489          extends BulkTask<K,V,U> {
5490 <        final Fun<? super K, ? extends U> transformer;
5491 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5490 >        final Function<? super K, ? extends U> transformer;
5491 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5492          U result;
5493          MapReduceKeysTask<K,V,U> rights, nextRight;
5494          MapReduceKeysTask
5495 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5495 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5496               MapReduceKeysTask<K,V,U> nextRight,
5497 <             Fun<? super K, ? extends U> transformer,
5498 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5499 <            super(m, p, b); this.nextRight = nextRight;
5497 >             Function<? super K, ? extends U> transformer,
5498 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5499 >            super(p, b, i, f, t); this.nextRight = nextRight;
5500              this.transformer = transformer;
5501              this.reducer = reducer;
5502          }
5503 <        @SuppressWarnings("unchecked") public final boolean exec() {
5504 <            final Fun<? super K, ? extends U> transformer =
5505 <                this.transformer;
5506 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5507 <                this.reducer;
5508 <            if (transformer == null || reducer == null)
5509 <                return abortOnNullFunction();
5510 <            try {
5511 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6153 <                    do {} while (!casPending(c = pending, c+1));
5503 >        public final U getRawResult() { return result; }
5504 >        public final void compute() {
5505 >            final Function<? super K, ? extends U> transformer;
5506 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5507 >            if ((transformer = this.transformer) != null &&
5508 >                (reducer = this.reducer) != null) {
5509 >                for (int i = baseIndex, f, h; batch > 0 &&
5510 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5511 >                    addToPendingCount(1);
5512                      (rights = new MapReduceKeysTask<K,V,U>
5513 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5513 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5514 >                      rights, transformer, reducer)).fork();
5515                  }
5516 <                U r = null, u;
5517 <                while (advance() != null) {
5518 <                    if ((u = transformer.apply((K)nextKey)) != null)
5516 >                U r = null;
5517 >                for (Node<K,V> p; (p = advance()) != null; ) {
5518 >                    U u;
5519 >                    if ((u = transformer.apply(p.key)) != null)
5520                          r = (r == null) ? u : reducer.apply(r, u);
5521                  }
5522                  result = r;
5523 <                for (MapReduceKeysTask<K,V,U> t = this, s;;) {
5524 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5525 <                    if ((c = t.pending) == 0) {
5526 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5527 <                            if ((sr = s.result) != null)
5528 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5529 <                        }
5530 <                        if ((par = t.parent) == null ||
5531 <                            !(par instanceof MapReduceKeysTask)) {
5532 <                            t.quietlyComplete();
5533 <                            break;
5534 <                        }
6175 <                        t = (MapReduceKeysTask<K,V,U>)par;
5523 >                CountedCompleter<?> c;
5524 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5525 >                    @SuppressWarnings("unchecked")
5526 >                    MapReduceKeysTask<K,V,U>
5527 >                        t = (MapReduceKeysTask<K,V,U>)c,
5528 >                        s = t.rights;
5529 >                    while (s != null) {
5530 >                        U tr, sr;
5531 >                        if ((sr = s.result) != null)
5532 >                            t.result = (((tr = t.result) == null) ? sr :
5533 >                                        reducer.apply(tr, sr));
5534 >                        s = t.rights = s.nextRight;
5535                      }
6177                    else if (t.casPending(c, c - 1))
6178                        break;
5536                  }
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);
5537              }
6190            return false;
5538          }
6192        public final U getRawResult() { return result; }
5539      }
5540  
5541 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5541 >    @SuppressWarnings("serial")
5542 >    static final class MapReduceValuesTask<K,V,U>
5543          extends BulkTask<K,V,U> {
5544 <        final Fun<? super V, ? extends U> transformer;
5545 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5544 >        final Function<? super V, ? extends U> transformer;
5545 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5546          U result;
5547          MapReduceValuesTask<K,V,U> rights, nextRight;
5548          MapReduceValuesTask
5549 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5549 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5550               MapReduceValuesTask<K,V,U> nextRight,
5551 <             Fun<? super V, ? extends U> transformer,
5552 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5553 <            super(m, p, b); this.nextRight = nextRight;
5551 >             Function<? super V, ? extends U> transformer,
5552 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5553 >            super(p, b, i, f, t); this.nextRight = nextRight;
5554              this.transformer = transformer;
5555              this.reducer = reducer;
5556          }
5557 <        @SuppressWarnings("unchecked") public final boolean exec() {
5558 <            final Fun<? super V, ? extends U> transformer =
5559 <                this.transformer;
5560 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5561 <                this.reducer;
5562 <            if (transformer == null || reducer == null)
5563 <                return abortOnNullFunction();
5564 <            try {
5565 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6219 <                    do {} while (!casPending(c = pending, c+1));
5557 >        public final U getRawResult() { return result; }
5558 >        public final void compute() {
5559 >            final Function<? super V, ? extends U> transformer;
5560 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5561 >            if ((transformer = this.transformer) != null &&
5562 >                (reducer = this.reducer) != null) {
5563 >                for (int i = baseIndex, f, h; batch > 0 &&
5564 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5565 >                    addToPendingCount(1);
5566                      (rights = new MapReduceValuesTask<K,V,U>
5567 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5567 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5568 >                      rights, transformer, reducer)).fork();
5569                  }
5570 <                U r = null, u;
5571 <                Object v;
5572 <                while ((v = advance()) != null) {
5573 <                    if ((u = transformer.apply((V)v)) != null)
5570 >                U r = null;
5571 >                for (Node<K,V> p; (p = advance()) != null; ) {
5572 >                    U u;
5573 >                    if ((u = transformer.apply(p.val)) != null)
5574                          r = (r == null) ? u : reducer.apply(r, u);
5575                  }
5576                  result = r;
5577 <                for (MapReduceValuesTask<K,V,U> t = this, s;;) {
5578 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5579 <                    if ((c = t.pending) == 0) {
5580 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5581 <                            if ((sr = s.result) != null)
5582 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5583 <                        }
5584 <                        if ((par = t.parent) == null ||
5585 <                            !(par instanceof MapReduceValuesTask)) {
5586 <                            t.quietlyComplete();
5587 <                            break;
5588 <                        }
6242 <                        t = (MapReduceValuesTask<K,V,U>)par;
5577 >                CountedCompleter<?> c;
5578 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5579 >                    @SuppressWarnings("unchecked")
5580 >                    MapReduceValuesTask<K,V,U>
5581 >                        t = (MapReduceValuesTask<K,V,U>)c,
5582 >                        s = t.rights;
5583 >                    while (s != null) {
5584 >                        U tr, sr;
5585 >                        if ((sr = s.result) != null)
5586 >                            t.result = (((tr = t.result) == null) ? sr :
5587 >                                        reducer.apply(tr, sr));
5588 >                        s = t.rights = s.nextRight;
5589                      }
6244                    else if (t.casPending(c, c - 1))
6245                        break;
5590                  }
6247            } catch (Throwable ex) {
6248                return tryCompleteComputation(ex);
5591              }
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;
5592          }
6259        public final U getRawResult() { return result; }
5593      }
5594  
5595 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5595 >    @SuppressWarnings("serial")
5596 >    static final class MapReduceEntriesTask<K,V,U>
5597          extends BulkTask<K,V,U> {
5598 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5599 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5598 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5599 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5600          U result;
5601          MapReduceEntriesTask<K,V,U> rights, nextRight;
5602          MapReduceEntriesTask
5603 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5603 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5604               MapReduceEntriesTask<K,V,U> nextRight,
5605 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5606 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5607 <            super(m, p, b); this.nextRight = nextRight;
5605 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5606 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5607 >            super(p, b, i, f, t); this.nextRight = nextRight;
5608              this.transformer = transformer;
5609              this.reducer = reducer;
5610          }
5611 <        @SuppressWarnings("unchecked") public final boolean exec() {
5612 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5613 <                this.transformer;
5614 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5615 <                this.reducer;
5616 <            if (transformer == null || reducer == null)
5617 <                return abortOnNullFunction();
5618 <            try {
5619 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6286 <                    do {} while (!casPending(c = pending, c+1));
5611 >        public final U getRawResult() { return result; }
5612 >        public final void compute() {
5613 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5614 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5615 >            if ((transformer = this.transformer) != null &&
5616 >                (reducer = this.reducer) != null) {
5617 >                for (int i = baseIndex, f, h; batch > 0 &&
5618 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5619 >                    addToPendingCount(1);
5620                      (rights = new MapReduceEntriesTask<K,V,U>
5621 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5621 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5622 >                      rights, transformer, reducer)).fork();
5623                  }
5624 <                U r = null, u;
5625 <                Object v;
5626 <                while ((v = advance()) != null) {
5627 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5624 >                U r = null;
5625 >                for (Node<K,V> p; (p = advance()) != null; ) {
5626 >                    U u;
5627 >                    if ((u = transformer.apply(p)) != null)
5628                          r = (r == null) ? u : reducer.apply(r, u);
5629                  }
5630                  result = r;
5631 <                for (MapReduceEntriesTask<K,V,U> t = this, s;;) {
5632 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5633 <                    if ((c = t.pending) == 0) {
5634 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5635 <                            if ((sr = s.result) != null)
5636 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5637 <                        }
5638 <                        if ((par = t.parent) == null ||
5639 <                            !(par instanceof MapReduceEntriesTask)) {
5640 <                            t.quietlyComplete();
5641 <                            break;
5642 <                        }
6309 <                        t = (MapReduceEntriesTask<K,V,U>)par;
5631 >                CountedCompleter<?> c;
5632 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5633 >                    @SuppressWarnings("unchecked")
5634 >                    MapReduceEntriesTask<K,V,U>
5635 >                        t = (MapReduceEntriesTask<K,V,U>)c,
5636 >                        s = t.rights;
5637 >                    while (s != null) {
5638 >                        U tr, sr;
5639 >                        if ((sr = s.result) != null)
5640 >                            t.result = (((tr = t.result) == null) ? sr :
5641 >                                        reducer.apply(tr, sr));
5642 >                        s = t.rights = s.nextRight;
5643                      }
6311                    else if (t.casPending(c, c - 1))
6312                        break;
5644                  }
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);
5645              }
6324            return false;
5646          }
6326        public final U getRawResult() { return result; }
5647      }
5648  
5649 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5649 >    @SuppressWarnings("serial")
5650 >    static final class MapReduceMappingsTask<K,V,U>
5651          extends BulkTask<K,V,U> {
5652 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5653 <        final BiFun<? super U, ? super U, ? extends U> reducer;
5652 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5653 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5654          U result;
5655          MapReduceMappingsTask<K,V,U> rights, nextRight;
5656          MapReduceMappingsTask
5657 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5657 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5658               MapReduceMappingsTask<K,V,U> nextRight,
5659 <             BiFun<? super K, ? super V, ? extends U> transformer,
5660 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5661 <            super(m, p, b); this.nextRight = nextRight;
5659 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5660 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5661 >            super(p, b, i, f, t); this.nextRight = nextRight;
5662              this.transformer = transformer;
5663              this.reducer = reducer;
5664          }
5665 <        @SuppressWarnings("unchecked") public final boolean exec() {
5666 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5667 <                this.transformer;
5668 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5669 <                this.reducer;
5670 <            if (transformer == null || reducer == null)
5671 <                return abortOnNullFunction();
5672 <            try {
5673 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6353 <                    do {} while (!casPending(c = pending, c+1));
5665 >        public final U getRawResult() { return result; }
5666 >        public final void compute() {
5667 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5668 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5669 >            if ((transformer = this.transformer) != null &&
5670 >                (reducer = this.reducer) != null) {
5671 >                for (int i = baseIndex, f, h; batch > 0 &&
5672 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5673 >                    addToPendingCount(1);
5674                      (rights = new MapReduceMappingsTask<K,V,U>
5675 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5675 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5676 >                      rights, transformer, reducer)).fork();
5677                  }
5678 <                U r = null, u;
5679 <                Object v;
5680 <                while ((v = advance()) != null) {
5681 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5678 >                U r = null;
5679 >                for (Node<K,V> p; (p = advance()) != null; ) {
5680 >                    U u;
5681 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5682                          r = (r == null) ? u : reducer.apply(r, u);
5683                  }
5684                  result = r;
5685 <                for (MapReduceMappingsTask<K,V,U> t = this, s;;) {
5686 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5687 <                    if ((c = t.pending) == 0) {
5688 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5689 <                            if ((sr = s.result) != null)
5690 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5691 <                        }
5692 <                        if ((par = t.parent) == null ||
5693 <                            !(par instanceof MapReduceMappingsTask)) {
5694 <                            t.quietlyComplete();
5695 <                            break;
5696 <                        }
6376 <                        t = (MapReduceMappingsTask<K,V,U>)par;
5685 >                CountedCompleter<?> c;
5686 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5687 >                    @SuppressWarnings("unchecked")
5688 >                    MapReduceMappingsTask<K,V,U>
5689 >                        t = (MapReduceMappingsTask<K,V,U>)c,
5690 >                        s = t.rights;
5691 >                    while (s != null) {
5692 >                        U tr, sr;
5693 >                        if ((sr = s.result) != null)
5694 >                            t.result = (((tr = t.result) == null) ? sr :
5695 >                                        reducer.apply(tr, sr));
5696 >                        s = t.rights = s.nextRight;
5697                      }
6378                    else if (t.casPending(c, c - 1))
6379                        break;
5698                  }
6381            } catch (Throwable ex) {
6382                return tryCompleteComputation(ex);
5699              }
6384            MapReduceMappingsTask<K,V,U> s = rights;
6385            if (s != null && !inForkJoinPool()) {
6386                do  {
6387                    if (s.tryUnfork())
6388                        s.exec();
6389                } while ((s = s.nextRight) != null);
6390            }
6391            return false;
5700          }
6393        public final U getRawResult() { return result; }
5701      }
5702  
5703 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5703 >    @SuppressWarnings("serial")
5704 >    static final class MapReduceKeysToDoubleTask<K,V>
5705          extends BulkTask<K,V,Double> {
5706 <        final ObjectToDouble<? super K> transformer;
5707 <        final DoubleByDoubleToDouble reducer;
5706 >        final ToDoubleFunction<? super K> transformer;
5707 >        final DoubleBinaryOperator reducer;
5708          final double basis;
5709          double result;
5710          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5711          MapReduceKeysToDoubleTask
5712 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5712 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5713               MapReduceKeysToDoubleTask<K,V> nextRight,
5714 <             ObjectToDouble<? super K> transformer,
5714 >             ToDoubleFunction<? super K> transformer,
5715               double basis,
5716 <             DoubleByDoubleToDouble reducer) {
5717 <            super(m, p, b); this.nextRight = nextRight;
5716 >             DoubleBinaryOperator reducer) {
5717 >            super(p, b, i, f, t); this.nextRight = nextRight;
5718              this.transformer = transformer;
5719              this.basis = basis; this.reducer = reducer;
5720          }
5721 <        @SuppressWarnings("unchecked") public final boolean exec() {
5722 <            final ObjectToDouble<? super K> transformer =
5723 <                this.transformer;
5724 <            final DoubleByDoubleToDouble reducer = this.reducer;
5725 <            if (transformer == null || reducer == null)
5726 <                return abortOnNullFunction();
5727 <            try {
5728 <                final double id = this.basis;
5729 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5730 <                    do {} while (!casPending(c = pending, c+1));
5721 >        public final Double getRawResult() { return result; }
5722 >        public final void compute() {
5723 >            final ToDoubleFunction<? super K> transformer;
5724 >            final DoubleBinaryOperator reducer;
5725 >            if ((transformer = this.transformer) != null &&
5726 >                (reducer = this.reducer) != null) {
5727 >                double r = this.basis;
5728 >                for (int i = baseIndex, f, h; batch > 0 &&
5729 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5730 >                    addToPendingCount(1);
5731                      (rights = new MapReduceKeysToDoubleTask<K,V>
5732 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5732 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5733 >                      rights, transformer, r, reducer)).fork();
5734                  }
5735 <                double r = id;
5736 <                while (advance() != null)
6428 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5735 >                for (Node<K,V> p; (p = advance()) != null; )
5736 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5737                  result = r;
5738 <                for (MapReduceKeysToDoubleTask<K,V> t = this, s;;) {
5739 <                    int c; BulkTask<K,V,?> par;
5740 <                    if ((c = t.pending) == 0) {
5741 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5742 <                            t.result = reducer.apply(t.result, s.result);
5743 <                        }
5744 <                        if ((par = t.parent) == null ||
5745 <                            !(par instanceof MapReduceKeysToDoubleTask)) {
5746 <                            t.quietlyComplete();
6439 <                            break;
6440 <                        }
6441 <                        t = (MapReduceKeysToDoubleTask<K,V>)par;
5738 >                CountedCompleter<?> c;
5739 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5740 >                    @SuppressWarnings("unchecked")
5741 >                    MapReduceKeysToDoubleTask<K,V>
5742 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
5743 >                        s = t.rights;
5744 >                    while (s != null) {
5745 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5746 >                        s = t.rights = s.nextRight;
5747                      }
6443                    else if (t.casPending(c, c - 1))
6444                        break;
5748                  }
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);
5749              }
6456            return false;
5750          }
6458        public final Double getRawResult() { return result; }
5751      }
5752  
5753 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5753 >    @SuppressWarnings("serial")
5754 >    static final class MapReduceValuesToDoubleTask<K,V>
5755          extends BulkTask<K,V,Double> {
5756 <        final ObjectToDouble<? super V> transformer;
5757 <        final DoubleByDoubleToDouble reducer;
5756 >        final ToDoubleFunction<? super V> transformer;
5757 >        final DoubleBinaryOperator reducer;
5758          final double basis;
5759          double result;
5760          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5761          MapReduceValuesToDoubleTask
5762 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5762 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5763               MapReduceValuesToDoubleTask<K,V> nextRight,
5764 <             ObjectToDouble<? super V> transformer,
5764 >             ToDoubleFunction<? super V> transformer,
5765               double basis,
5766 <             DoubleByDoubleToDouble reducer) {
5767 <            super(m, p, b); this.nextRight = nextRight;
5766 >             DoubleBinaryOperator reducer) {
5767 >            super(p, b, i, f, t); this.nextRight = nextRight;
5768              this.transformer = transformer;
5769              this.basis = basis; this.reducer = reducer;
5770          }
5771 <        @SuppressWarnings("unchecked") public final boolean exec() {
5772 <            final ObjectToDouble<? super V> transformer =
5773 <                this.transformer;
5774 <            final DoubleByDoubleToDouble reducer = this.reducer;
5775 <            if (transformer == null || reducer == null)
5776 <                return abortOnNullFunction();
5777 <            try {
5778 <                final double id = this.basis;
5779 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5780 <                    do {} while (!casPending(c = pending, c+1));
5771 >        public final Double getRawResult() { return result; }
5772 >        public final void compute() {
5773 >            final ToDoubleFunction<? super V> transformer;
5774 >            final DoubleBinaryOperator reducer;
5775 >            if ((transformer = this.transformer) != null &&
5776 >                (reducer = this.reducer) != null) {
5777 >                double r = this.basis;
5778 >                for (int i = baseIndex, f, h; batch > 0 &&
5779 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5780 >                    addToPendingCount(1);
5781                      (rights = new MapReduceValuesToDoubleTask<K,V>
5782 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5782 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5783 >                      rights, transformer, r, reducer)).fork();
5784                  }
5785 <                double r = id;
5786 <                Object v;
6493 <                while ((v = advance()) != null)
6494 <                    r = reducer.apply(r, transformer.apply((V)v));
5785 >                for (Node<K,V> p; (p = advance()) != null; )
5786 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5787                  result = r;
5788 <                for (MapReduceValuesToDoubleTask<K,V> t = this, s;;) {
5789 <                    int c; BulkTask<K,V,?> par;
5790 <                    if ((c = t.pending) == 0) {
5791 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5792 <                            t.result = reducer.apply(t.result, s.result);
5793 <                        }
5794 <                        if ((par = t.parent) == null ||
5795 <                            !(par instanceof MapReduceValuesToDoubleTask)) {
5796 <                            t.quietlyComplete();
6505 <                            break;
6506 <                        }
6507 <                        t = (MapReduceValuesToDoubleTask<K,V>)par;
5788 >                CountedCompleter<?> c;
5789 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5790 >                    @SuppressWarnings("unchecked")
5791 >                    MapReduceValuesToDoubleTask<K,V>
5792 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
5793 >                        s = t.rights;
5794 >                    while (s != null) {
5795 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5796 >                        s = t.rights = s.nextRight;
5797                      }
6509                    else if (t.casPending(c, c - 1))
6510                        break;
5798                  }
6512            } catch (Throwable ex) {
6513                return tryCompleteComputation(ex);
5799              }
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;
5800          }
6524        public final Double getRawResult() { return result; }
5801      }
5802  
5803 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5803 >    @SuppressWarnings("serial")
5804 >    static final class MapReduceEntriesToDoubleTask<K,V>
5805          extends BulkTask<K,V,Double> {
5806 <        final ObjectToDouble<Map.Entry<K,V>> transformer;
5807 <        final DoubleByDoubleToDouble reducer;
5806 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
5807 >        final DoubleBinaryOperator reducer;
5808          final double basis;
5809          double result;
5810          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5811          MapReduceEntriesToDoubleTask
5812 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5812 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5813               MapReduceEntriesToDoubleTask<K,V> nextRight,
5814 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5814 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5815               double basis,
5816 <             DoubleByDoubleToDouble reducer) {
5817 <            super(m, p, b); this.nextRight = nextRight;
5816 >             DoubleBinaryOperator reducer) {
5817 >            super(p, b, i, f, t); this.nextRight = nextRight;
5818              this.transformer = transformer;
5819              this.basis = basis; this.reducer = reducer;
5820          }
5821 <        @SuppressWarnings("unchecked") public final boolean exec() {
5822 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
5823 <                this.transformer;
5824 <            final DoubleByDoubleToDouble reducer = this.reducer;
5825 <            if (transformer == null || reducer == null)
5826 <                return abortOnNullFunction();
5827 <            try {
5828 <                final double id = this.basis;
5829 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5830 <                    do {} while (!casPending(c = pending, c+1));
5821 >        public final Double getRawResult() { return result; }
5822 >        public final void compute() {
5823 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
5824 >            final DoubleBinaryOperator reducer;
5825 >            if ((transformer = this.transformer) != null &&
5826 >                (reducer = this.reducer) != null) {
5827 >                double r = this.basis;
5828 >                for (int i = baseIndex, f, h; batch > 0 &&
5829 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5830 >                    addToPendingCount(1);
5831                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5832 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5832 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5833 >                      rights, transformer, r, reducer)).fork();
5834                  }
5835 <                double r = id;
5836 <                Object v;
6559 <                while ((v = advance()) != null)
6560 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5835 >                for (Node<K,V> p; (p = advance()) != null; )
5836 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5837                  result = r;
5838 <                for (MapReduceEntriesToDoubleTask<K,V> t = this, s;;) {
5839 <                    int c; BulkTask<K,V,?> par;
5840 <                    if ((c = t.pending) == 0) {
5841 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5842 <                            t.result = reducer.apply(t.result, s.result);
5843 <                        }
5844 <                        if ((par = t.parent) == null ||
5845 <                            !(par instanceof MapReduceEntriesToDoubleTask)) {
5846 <                            t.quietlyComplete();
6571 <                            break;
6572 <                        }
6573 <                        t = (MapReduceEntriesToDoubleTask<K,V>)par;
5838 >                CountedCompleter<?> c;
5839 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5840 >                    @SuppressWarnings("unchecked")
5841 >                    MapReduceEntriesToDoubleTask<K,V>
5842 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
5843 >                        s = t.rights;
5844 >                    while (s != null) {
5845 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5846 >                        s = t.rights = s.nextRight;
5847                      }
6575                    else if (t.casPending(c, c - 1))
6576                        break;
5848                  }
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);
5849              }
6588            return false;
5850          }
6590        public final Double getRawResult() { return result; }
5851      }
5852  
5853 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5853 >    @SuppressWarnings("serial")
5854 >    static final class MapReduceMappingsToDoubleTask<K,V>
5855          extends BulkTask<K,V,Double> {
5856 <        final ObjectByObjectToDouble<? super K, ? super V> transformer;
5857 <        final DoubleByDoubleToDouble reducer;
5856 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
5857 >        final DoubleBinaryOperator reducer;
5858          final double basis;
5859          double result;
5860          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5861          MapReduceMappingsToDoubleTask
5862 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5862 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5863               MapReduceMappingsToDoubleTask<K,V> nextRight,
5864 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
5864 >             ToDoubleBiFunction<? super K, ? super V> transformer,
5865               double basis,
5866 <             DoubleByDoubleToDouble reducer) {
5867 <            super(m, p, b); this.nextRight = nextRight;
5866 >             DoubleBinaryOperator reducer) {
5867 >            super(p, b, i, f, t); this.nextRight = nextRight;
5868              this.transformer = transformer;
5869              this.basis = basis; this.reducer = reducer;
5870          }
5871 <        @SuppressWarnings("unchecked") public final boolean exec() {
5872 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
5873 <                this.transformer;
5874 <            final DoubleByDoubleToDouble reducer = this.reducer;
5875 <            if (transformer == null || reducer == null)
5876 <                return abortOnNullFunction();
5877 <            try {
5878 <                final double id = this.basis;
5879 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5880 <                    do {} while (!casPending(c = pending, c+1));
5871 >        public final Double getRawResult() { return result; }
5872 >        public final void compute() {
5873 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
5874 >            final DoubleBinaryOperator reducer;
5875 >            if ((transformer = this.transformer) != null &&
5876 >                (reducer = this.reducer) != null) {
5877 >                double r = this.basis;
5878 >                for (int i = baseIndex, f, h; batch > 0 &&
5879 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5880 >                    addToPendingCount(1);
5881                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5882 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5882 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5883 >                      rights, transformer, r, reducer)).fork();
5884                  }
5885 <                double r = id;
5886 <                Object v;
6625 <                while ((v = advance()) != null)
6626 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5885 >                for (Node<K,V> p; (p = advance()) != null; )
5886 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5887                  result = r;
5888 <                for (MapReduceMappingsToDoubleTask<K,V> t = this, s;;) {
5889 <                    int c; BulkTask<K,V,?> par;
5890 <                    if ((c = t.pending) == 0) {
5891 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5892 <                            t.result = reducer.apply(t.result, s.result);
5893 <                        }
5894 <                        if ((par = t.parent) == null ||
5895 <                            !(par instanceof MapReduceMappingsToDoubleTask)) {
5896 <                            t.quietlyComplete();
6637 <                            break;
6638 <                        }
6639 <                        t = (MapReduceMappingsToDoubleTask<K,V>)par;
5888 >                CountedCompleter<?> c;
5889 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5890 >                    @SuppressWarnings("unchecked")
5891 >                    MapReduceMappingsToDoubleTask<K,V>
5892 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
5893 >                        s = t.rights;
5894 >                    while (s != null) {
5895 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5896 >                        s = t.rights = s.nextRight;
5897                      }
6641                    else if (t.casPending(c, c - 1))
6642                        break;
5898                  }
6644            } catch (Throwable ex) {
6645                return tryCompleteComputation(ex);
5899              }
6647            MapReduceMappingsToDoubleTask<K,V> s = rights;
6648            if (s != null && !inForkJoinPool()) {
6649                do  {
6650                    if (s.tryUnfork())
6651                        s.exec();
6652                } while ((s = s.nextRight) != null);
6653            }
6654            return false;
5900          }
6656        public final Double getRawResult() { return result; }
5901      }
5902  
5903 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5903 >    @SuppressWarnings("serial")
5904 >    static final class MapReduceKeysToLongTask<K,V>
5905          extends BulkTask<K,V,Long> {
5906 <        final ObjectToLong<? super K> transformer;
5907 <        final LongByLongToLong reducer;
5906 >        final ToLongFunction<? super K> transformer;
5907 >        final LongBinaryOperator reducer;
5908          final long basis;
5909          long result;
5910          MapReduceKeysToLongTask<K,V> rights, nextRight;
5911          MapReduceKeysToLongTask
5912 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5912 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5913               MapReduceKeysToLongTask<K,V> nextRight,
5914 <             ObjectToLong<? super K> transformer,
5914 >             ToLongFunction<? super K> transformer,
5915               long basis,
5916 <             LongByLongToLong reducer) {
5917 <            super(m, p, b); this.nextRight = nextRight;
5916 >             LongBinaryOperator reducer) {
5917 >            super(p, b, i, f, t); this.nextRight = nextRight;
5918              this.transformer = transformer;
5919              this.basis = basis; this.reducer = reducer;
5920          }
5921 <        @SuppressWarnings("unchecked") public final boolean exec() {
5922 <            final ObjectToLong<? super K> transformer =
5923 <                this.transformer;
5924 <            final LongByLongToLong reducer = this.reducer;
5925 <            if (transformer == null || reducer == null)
5926 <                return abortOnNullFunction();
5927 <            try {
5928 <                final long id = this.basis;
5929 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5930 <                    do {} while (!casPending(c = pending, c+1));
5921 >        public final Long getRawResult() { return result; }
5922 >        public final void compute() {
5923 >            final ToLongFunction<? super K> transformer;
5924 >            final LongBinaryOperator reducer;
5925 >            if ((transformer = this.transformer) != null &&
5926 >                (reducer = this.reducer) != null) {
5927 >                long r = this.basis;
5928 >                for (int i = baseIndex, f, h; batch > 0 &&
5929 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5930 >                    addToPendingCount(1);
5931                      (rights = new MapReduceKeysToLongTask<K,V>
5932 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5932 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5933 >                      rights, transformer, r, reducer)).fork();
5934                  }
5935 <                long r = id;
5936 <                while (advance() != null)
6691 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5935 >                for (Node<K,V> p; (p = advance()) != null; )
5936 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5937                  result = r;
5938 <                for (MapReduceKeysToLongTask<K,V> t = this, s;;) {
5939 <                    int c; BulkTask<K,V,?> par;
5940 <                    if ((c = t.pending) == 0) {
5941 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5942 <                            t.result = reducer.apply(t.result, s.result);
5943 <                        }
5944 <                        if ((par = t.parent) == null ||
5945 <                            !(par instanceof MapReduceKeysToLongTask)) {
5946 <                            t.quietlyComplete();
6702 <                            break;
6703 <                        }
6704 <                        t = (MapReduceKeysToLongTask<K,V>)par;
5938 >                CountedCompleter<?> c;
5939 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5940 >                    @SuppressWarnings("unchecked")
5941 >                    MapReduceKeysToLongTask<K,V>
5942 >                        t = (MapReduceKeysToLongTask<K,V>)c,
5943 >                        s = t.rights;
5944 >                    while (s != null) {
5945 >                        t.result = reducer.applyAsLong(t.result, s.result);
5946 >                        s = t.rights = s.nextRight;
5947                      }
6706                    else if (t.casPending(c, c - 1))
6707                        break;
5948                  }
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);
5949              }
6719            return false;
5950          }
6721        public final Long getRawResult() { return result; }
5951      }
5952  
5953 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5953 >    @SuppressWarnings("serial")
5954 >    static final class MapReduceValuesToLongTask<K,V>
5955          extends BulkTask<K,V,Long> {
5956 <        final ObjectToLong<? super V> transformer;
5957 <        final LongByLongToLong reducer;
5956 >        final ToLongFunction<? super V> transformer;
5957 >        final LongBinaryOperator reducer;
5958          final long basis;
5959          long result;
5960          MapReduceValuesToLongTask<K,V> rights, nextRight;
5961          MapReduceValuesToLongTask
5962 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5962 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5963               MapReduceValuesToLongTask<K,V> nextRight,
5964 <             ObjectToLong<? super V> transformer,
5964 >             ToLongFunction<? super V> transformer,
5965               long basis,
5966 <             LongByLongToLong reducer) {
5967 <            super(m, p, b); this.nextRight = nextRight;
5966 >             LongBinaryOperator reducer) {
5967 >            super(p, b, i, f, t); this.nextRight = nextRight;
5968              this.transformer = transformer;
5969              this.basis = basis; this.reducer = reducer;
5970          }
5971 <        @SuppressWarnings("unchecked") public final boolean exec() {
5972 <            final ObjectToLong<? super V> transformer =
5973 <                this.transformer;
5974 <            final LongByLongToLong reducer = this.reducer;
5975 <            if (transformer == null || reducer == null)
5976 <                return abortOnNullFunction();
5977 <            try {
5978 <                final long id = this.basis;
5979 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5980 <                    do {} while (!casPending(c = pending, c+1));
5971 >        public final Long getRawResult() { return result; }
5972 >        public final void compute() {
5973 >            final ToLongFunction<? super V> transformer;
5974 >            final LongBinaryOperator reducer;
5975 >            if ((transformer = this.transformer) != null &&
5976 >                (reducer = this.reducer) != null) {
5977 >                long r = this.basis;
5978 >                for (int i = baseIndex, f, h; batch > 0 &&
5979 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5980 >                    addToPendingCount(1);
5981                      (rights = new MapReduceValuesToLongTask<K,V>
5982 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5982 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5983 >                      rights, transformer, r, reducer)).fork();
5984                  }
5985 <                long r = id;
5986 <                Object v;
6756 <                while ((v = advance()) != null)
6757 <                    r = reducer.apply(r, transformer.apply((V)v));
5985 >                for (Node<K,V> p; (p = advance()) != null; )
5986 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5987                  result = r;
5988 <                for (MapReduceValuesToLongTask<K,V> t = this, s;;) {
5989 <                    int c; BulkTask<K,V,?> par;
5990 <                    if ((c = t.pending) == 0) {
5991 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5992 <                            t.result = reducer.apply(t.result, s.result);
5993 <                        }
5994 <                        if ((par = t.parent) == null ||
5995 <                            !(par instanceof MapReduceValuesToLongTask)) {
5996 <                            t.quietlyComplete();
6768 <                            break;
6769 <                        }
6770 <                        t = (MapReduceValuesToLongTask<K,V>)par;
5988 >                CountedCompleter<?> c;
5989 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5990 >                    @SuppressWarnings("unchecked")
5991 >                    MapReduceValuesToLongTask<K,V>
5992 >                        t = (MapReduceValuesToLongTask<K,V>)c,
5993 >                        s = t.rights;
5994 >                    while (s != null) {
5995 >                        t.result = reducer.applyAsLong(t.result, s.result);
5996 >                        s = t.rights = s.nextRight;
5997                      }
6772                    else if (t.casPending(c, c - 1))
6773                        break;
5998                  }
6775            } catch (Throwable ex) {
6776                return tryCompleteComputation(ex);
5999              }
6778            MapReduceValuesToLongTask<K,V> s = rights;
6779            if (s != null && !inForkJoinPool()) {
6780                do  {
6781                    if (s.tryUnfork())
6782                        s.exec();
6783                } while ((s = s.nextRight) != null);
6784            }
6785            return false;
6000          }
6787        public final Long getRawResult() { return result; }
6001      }
6002  
6003 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6003 >    @SuppressWarnings("serial")
6004 >    static final class MapReduceEntriesToLongTask<K,V>
6005          extends BulkTask<K,V,Long> {
6006 <        final ObjectToLong<Map.Entry<K,V>> transformer;
6007 <        final LongByLongToLong reducer;
6006 >        final ToLongFunction<Map.Entry<K,V>> transformer;
6007 >        final LongBinaryOperator reducer;
6008          final long basis;
6009          long result;
6010          MapReduceEntriesToLongTask<K,V> rights, nextRight;
6011          MapReduceEntriesToLongTask
6012 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6012 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6013               MapReduceEntriesToLongTask<K,V> nextRight,
6014 <             ObjectToLong<Map.Entry<K,V>> transformer,
6014 >             ToLongFunction<Map.Entry<K,V>> transformer,
6015               long basis,
6016 <             LongByLongToLong reducer) {
6017 <            super(m, p, b); this.nextRight = nextRight;
6016 >             LongBinaryOperator reducer) {
6017 >            super(p, b, i, f, t); this.nextRight = nextRight;
6018              this.transformer = transformer;
6019              this.basis = basis; this.reducer = reducer;
6020          }
6021 <        @SuppressWarnings("unchecked") public final boolean exec() {
6022 <            final ObjectToLong<Map.Entry<K,V>> transformer =
6023 <                this.transformer;
6024 <            final LongByLongToLong reducer = this.reducer;
6025 <            if (transformer == null || reducer == null)
6026 <                return abortOnNullFunction();
6027 <            try {
6028 <                final long id = this.basis;
6029 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6030 <                    do {} while (!casPending(c = pending, c+1));
6021 >        public final Long getRawResult() { return result; }
6022 >        public final void compute() {
6023 >            final ToLongFunction<Map.Entry<K,V>> transformer;
6024 >            final LongBinaryOperator reducer;
6025 >            if ((transformer = this.transformer) != null &&
6026 >                (reducer = this.reducer) != null) {
6027 >                long r = this.basis;
6028 >                for (int i = baseIndex, f, h; batch > 0 &&
6029 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6030 >                    addToPendingCount(1);
6031                      (rights = new MapReduceEntriesToLongTask<K,V>
6032 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6032 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6033 >                      rights, transformer, r, reducer)).fork();
6034                  }
6035 <                long r = id;
6036 <                Object v;
6822 <                while ((v = advance()) != null)
6823 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6035 >                for (Node<K,V> p; (p = advance()) != null; )
6036 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
6037                  result = r;
6038 <                for (MapReduceEntriesToLongTask<K,V> t = this, s;;) {
6039 <                    int c; BulkTask<K,V,?> par;
6040 <                    if ((c = t.pending) == 0) {
6041 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6042 <                            t.result = reducer.apply(t.result, s.result);
6043 <                        }
6044 <                        if ((par = t.parent) == null ||
6045 <                            !(par instanceof MapReduceEntriesToLongTask)) {
6046 <                            t.quietlyComplete();
6834 <                            break;
6835 <                        }
6836 <                        t = (MapReduceEntriesToLongTask<K,V>)par;
6038 >                CountedCompleter<?> c;
6039 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6040 >                    @SuppressWarnings("unchecked")
6041 >                    MapReduceEntriesToLongTask<K,V>
6042 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
6043 >                        s = t.rights;
6044 >                    while (s != null) {
6045 >                        t.result = reducer.applyAsLong(t.result, s.result);
6046 >                        s = t.rights = s.nextRight;
6047                      }
6838                    else if (t.casPending(c, c - 1))
6839                        break;
6048                  }
6841            } catch (Throwable ex) {
6842                return tryCompleteComputation(ex);
6843            }
6844            MapReduceEntriesToLongTask<K,V> s = rights;
6845            if (s != null && !inForkJoinPool()) {
6846                do  {
6847                    if (s.tryUnfork())
6848                        s.exec();
6849                } while ((s = s.nextRight) != null);
6049              }
6851            return false;
6050          }
6853        public final Long getRawResult() { return result; }
6051      }
6052  
6053 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6053 >    @SuppressWarnings("serial")
6054 >    static final class MapReduceMappingsToLongTask<K,V>
6055          extends BulkTask<K,V,Long> {
6056 <        final ObjectByObjectToLong<? super K, ? super V> transformer;
6057 <        final LongByLongToLong reducer;
6056 >        final ToLongBiFunction<? super K, ? super V> transformer;
6057 >        final LongBinaryOperator reducer;
6058          final long basis;
6059          long result;
6060          MapReduceMappingsToLongTask<K,V> rights, nextRight;
6061          MapReduceMappingsToLongTask
6062 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6062 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6063               MapReduceMappingsToLongTask<K,V> nextRight,
6064 <             ObjectByObjectToLong<? super K, ? super V> transformer,
6064 >             ToLongBiFunction<? super K, ? super V> transformer,
6065               long basis,
6066 <             LongByLongToLong reducer) {
6067 <            super(m, p, b); this.nextRight = nextRight;
6066 >             LongBinaryOperator reducer) {
6067 >            super(p, b, i, f, t); this.nextRight = nextRight;
6068              this.transformer = transformer;
6069              this.basis = basis; this.reducer = reducer;
6070          }
6071 <        @SuppressWarnings("unchecked") public final boolean exec() {
6072 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
6073 <                this.transformer;
6074 <            final LongByLongToLong reducer = this.reducer;
6075 <            if (transformer == null || reducer == null)
6076 <                return abortOnNullFunction();
6077 <            try {
6078 <                final long id = this.basis;
6079 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6080 <                    do {} while (!casPending(c = pending, c+1));
6071 >        public final Long getRawResult() { return result; }
6072 >        public final void compute() {
6073 >            final ToLongBiFunction<? super K, ? super V> transformer;
6074 >            final LongBinaryOperator reducer;
6075 >            if ((transformer = this.transformer) != null &&
6076 >                (reducer = this.reducer) != null) {
6077 >                long r = this.basis;
6078 >                for (int i = baseIndex, f, h; batch > 0 &&
6079 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6080 >                    addToPendingCount(1);
6081                      (rights = new MapReduceMappingsToLongTask<K,V>
6082 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6082 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6083 >                      rights, transformer, r, reducer)).fork();
6084                  }
6085 <                long r = id;
6086 <                Object v;
6888 <                while ((v = advance()) != null)
6889 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6085 >                for (Node<K,V> p; (p = advance()) != null; )
6086 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
6087                  result = r;
6088 <                for (MapReduceMappingsToLongTask<K,V> t = this, s;;) {
6089 <                    int c; BulkTask<K,V,?> par;
6090 <                    if ((c = t.pending) == 0) {
6091 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6092 <                            t.result = reducer.apply(t.result, s.result);
6093 <                        }
6094 <                        if ((par = t.parent) == null ||
6095 <                            !(par instanceof MapReduceMappingsToLongTask)) {
6096 <                            t.quietlyComplete();
6900 <                            break;
6901 <                        }
6902 <                        t = (MapReduceMappingsToLongTask<K,V>)par;
6088 >                CountedCompleter<?> c;
6089 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6090 >                    @SuppressWarnings("unchecked")
6091 >                    MapReduceMappingsToLongTask<K,V>
6092 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
6093 >                        s = t.rights;
6094 >                    while (s != null) {
6095 >                        t.result = reducer.applyAsLong(t.result, s.result);
6096 >                        s = t.rights = s.nextRight;
6097                      }
6904                    else if (t.casPending(c, c - 1))
6905                        break;
6098                  }
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);
6099              }
6917            return false;
6100          }
6919        public final Long getRawResult() { return result; }
6101      }
6102  
6103 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6103 >    @SuppressWarnings("serial")
6104 >    static final class MapReduceKeysToIntTask<K,V>
6105          extends BulkTask<K,V,Integer> {
6106 <        final ObjectToInt<? super K> transformer;
6107 <        final IntByIntToInt reducer;
6106 >        final ToIntFunction<? super K> transformer;
6107 >        final IntBinaryOperator reducer;
6108          final int basis;
6109          int result;
6110          MapReduceKeysToIntTask<K,V> rights, nextRight;
6111          MapReduceKeysToIntTask
6112 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6112 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6113               MapReduceKeysToIntTask<K,V> nextRight,
6114 <             ObjectToInt<? super K> transformer,
6114 >             ToIntFunction<? super K> transformer,
6115               int basis,
6116 <             IntByIntToInt reducer) {
6117 <            super(m, p, b); this.nextRight = nextRight;
6116 >             IntBinaryOperator reducer) {
6117 >            super(p, b, i, f, t); this.nextRight = nextRight;
6118              this.transformer = transformer;
6119              this.basis = basis; this.reducer = reducer;
6120          }
6121 <        @SuppressWarnings("unchecked") public final boolean exec() {
6122 <            final ObjectToInt<? super K> transformer =
6123 <                this.transformer;
6124 <            final IntByIntToInt reducer = this.reducer;
6125 <            if (transformer == null || reducer == null)
6126 <                return abortOnNullFunction();
6127 <            try {
6128 <                final int id = this.basis;
6129 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6130 <                    do {} while (!casPending(c = pending, c+1));
6121 >        public final Integer getRawResult() { return result; }
6122 >        public final void compute() {
6123 >            final ToIntFunction<? super K> transformer;
6124 >            final IntBinaryOperator reducer;
6125 >            if ((transformer = this.transformer) != null &&
6126 >                (reducer = this.reducer) != null) {
6127 >                int r = this.basis;
6128 >                for (int i = baseIndex, f, h; batch > 0 &&
6129 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6130 >                    addToPendingCount(1);
6131                      (rights = new MapReduceKeysToIntTask<K,V>
6132 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6132 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6133 >                      rights, transformer, r, reducer)).fork();
6134                  }
6135 <                int r = id;
6136 <                while (advance() != null)
6954 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
6135 >                for (Node<K,V> p; (p = advance()) != null; )
6136 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
6137                  result = r;
6138 <                for (MapReduceKeysToIntTask<K,V> t = this, s;;) {
6139 <                    int c; BulkTask<K,V,?> par;
6140 <                    if ((c = t.pending) == 0) {
6141 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6142 <                            t.result = reducer.apply(t.result, s.result);
6143 <                        }
6144 <                        if ((par = t.parent) == null ||
6145 <                            !(par instanceof MapReduceKeysToIntTask)) {
6146 <                            t.quietlyComplete();
6965 <                            break;
6966 <                        }
6967 <                        t = (MapReduceKeysToIntTask<K,V>)par;
6138 >                CountedCompleter<?> c;
6139 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6140 >                    @SuppressWarnings("unchecked")
6141 >                    MapReduceKeysToIntTask<K,V>
6142 >                        t = (MapReduceKeysToIntTask<K,V>)c,
6143 >                        s = t.rights;
6144 >                    while (s != null) {
6145 >                        t.result = reducer.applyAsInt(t.result, s.result);
6146 >                        s = t.rights = s.nextRight;
6147                      }
6969                    else if (t.casPending(c, c - 1))
6970                        break;
6148                  }
6972            } catch (Throwable ex) {
6973                return tryCompleteComputation(ex);
6974            }
6975            MapReduceKeysToIntTask<K,V> s = rights;
6976            if (s != null && !inForkJoinPool()) {
6977                do  {
6978                    if (s.tryUnfork())
6979                        s.exec();
6980                } while ((s = s.nextRight) != null);
6149              }
6982            return false;
6150          }
6984        public final Integer getRawResult() { return result; }
6151      }
6152  
6153 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6153 >    @SuppressWarnings("serial")
6154 >    static final class MapReduceValuesToIntTask<K,V>
6155          extends BulkTask<K,V,Integer> {
6156 <        final ObjectToInt<? super V> transformer;
6157 <        final IntByIntToInt reducer;
6156 >        final ToIntFunction<? super V> transformer;
6157 >        final IntBinaryOperator reducer;
6158          final int basis;
6159          int result;
6160          MapReduceValuesToIntTask<K,V> rights, nextRight;
6161          MapReduceValuesToIntTask
6162 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6162 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6163               MapReduceValuesToIntTask<K,V> nextRight,
6164 <             ObjectToInt<? super V> transformer,
6164 >             ToIntFunction<? super V> transformer,
6165               int basis,
6166 <             IntByIntToInt reducer) {
6167 <            super(m, p, b); this.nextRight = nextRight;
6166 >             IntBinaryOperator reducer) {
6167 >            super(p, b, i, f, t); this.nextRight = nextRight;
6168              this.transformer = transformer;
6169              this.basis = basis; this.reducer = reducer;
6170          }
6171 <        @SuppressWarnings("unchecked") public final boolean exec() {
6172 <            final ObjectToInt<? super V> transformer =
6173 <                this.transformer;
6174 <            final IntByIntToInt reducer = this.reducer;
6175 <            if (transformer == null || reducer == null)
6176 <                return abortOnNullFunction();
6177 <            try {
6178 <                final int id = this.basis;
6179 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6180 <                    do {} while (!casPending(c = pending, c+1));
6171 >        public final Integer getRawResult() { return result; }
6172 >        public final void compute() {
6173 >            final ToIntFunction<? super V> transformer;
6174 >            final IntBinaryOperator reducer;
6175 >            if ((transformer = this.transformer) != null &&
6176 >                (reducer = this.reducer) != null) {
6177 >                int r = this.basis;
6178 >                for (int i = baseIndex, f, h; batch > 0 &&
6179 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6180 >                    addToPendingCount(1);
6181                      (rights = new MapReduceValuesToIntTask<K,V>
6182 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6182 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6183 >                      rights, transformer, r, reducer)).fork();
6184                  }
6185 <                int r = id;
6186 <                Object v;
7019 <                while ((v = advance()) != null)
7020 <                    r = reducer.apply(r, transformer.apply((V)v));
6185 >                for (Node<K,V> p; (p = advance()) != null; )
6186 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
6187                  result = r;
6188 <                for (MapReduceValuesToIntTask<K,V> t = this, s;;) {
6189 <                    int c; BulkTask<K,V,?> par;
6190 <                    if ((c = t.pending) == 0) {
6191 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6192 <                            t.result = reducer.apply(t.result, s.result);
6193 <                        }
6194 <                        if ((par = t.parent) == null ||
6195 <                            !(par instanceof MapReduceValuesToIntTask)) {
6196 <                            t.quietlyComplete();
7031 <                            break;
7032 <                        }
7033 <                        t = (MapReduceValuesToIntTask<K,V>)par;
6188 >                CountedCompleter<?> c;
6189 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6190 >                    @SuppressWarnings("unchecked")
6191 >                    MapReduceValuesToIntTask<K,V>
6192 >                        t = (MapReduceValuesToIntTask<K,V>)c,
6193 >                        s = t.rights;
6194 >                    while (s != null) {
6195 >                        t.result = reducer.applyAsInt(t.result, s.result);
6196 >                        s = t.rights = s.nextRight;
6197                      }
7035                    else if (t.casPending(c, c - 1))
7036                        break;
6198                  }
7038            } catch (Throwable ex) {
7039                return tryCompleteComputation(ex);
6199              }
7041            MapReduceValuesToIntTask<K,V> s = rights;
7042            if (s != null && !inForkJoinPool()) {
7043                do  {
7044                    if (s.tryUnfork())
7045                        s.exec();
7046                } while ((s = s.nextRight) != null);
7047            }
7048            return false;
6200          }
7050        public final Integer getRawResult() { return result; }
6201      }
6202  
6203 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6203 >    @SuppressWarnings("serial")
6204 >    static final class MapReduceEntriesToIntTask<K,V>
6205          extends BulkTask<K,V,Integer> {
6206 <        final ObjectToInt<Map.Entry<K,V>> transformer;
6207 <        final IntByIntToInt reducer;
6206 >        final ToIntFunction<Map.Entry<K,V>> transformer;
6207 >        final IntBinaryOperator reducer;
6208          final int basis;
6209          int result;
6210          MapReduceEntriesToIntTask<K,V> rights, nextRight;
6211          MapReduceEntriesToIntTask
6212 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6212 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6213               MapReduceEntriesToIntTask<K,V> nextRight,
6214 <             ObjectToInt<Map.Entry<K,V>> transformer,
6214 >             ToIntFunction<Map.Entry<K,V>> transformer,
6215               int basis,
6216 <             IntByIntToInt reducer) {
6217 <            super(m, p, b); this.nextRight = nextRight;
6216 >             IntBinaryOperator reducer) {
6217 >            super(p, b, i, f, t); this.nextRight = nextRight;
6218              this.transformer = transformer;
6219              this.basis = basis; this.reducer = reducer;
6220          }
6221 <        @SuppressWarnings("unchecked") public final boolean exec() {
6222 <            final ObjectToInt<Map.Entry<K,V>> transformer =
6223 <                this.transformer;
6224 <            final IntByIntToInt reducer = this.reducer;
6225 <            if (transformer == null || reducer == null)
6226 <                return abortOnNullFunction();
6227 <            try {
6228 <                final int id = this.basis;
6229 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6230 <                    do {} while (!casPending(c = pending, c+1));
6221 >        public final Integer getRawResult() { return result; }
6222 >        public final void compute() {
6223 >            final ToIntFunction<Map.Entry<K,V>> transformer;
6224 >            final IntBinaryOperator reducer;
6225 >            if ((transformer = this.transformer) != null &&
6226 >                (reducer = this.reducer) != null) {
6227 >                int r = this.basis;
6228 >                for (int i = baseIndex, f, h; batch > 0 &&
6229 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6230 >                    addToPendingCount(1);
6231                      (rights = new MapReduceEntriesToIntTask<K,V>
6232 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6232 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6233 >                      rights, transformer, r, reducer)).fork();
6234                  }
6235 <                int r = id;
6236 <                Object v;
7085 <                while ((v = advance()) != null)
7086 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6235 >                for (Node<K,V> p; (p = advance()) != null; )
6236 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
6237                  result = r;
6238 <                for (MapReduceEntriesToIntTask<K,V> t = this, s;;) {
6239 <                    int c; BulkTask<K,V,?> par;
6240 <                    if ((c = t.pending) == 0) {
6241 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6242 <                            t.result = reducer.apply(t.result, s.result);
6243 <                        }
6244 <                        if ((par = t.parent) == null ||
6245 <                            !(par instanceof MapReduceEntriesToIntTask)) {
6246 <                            t.quietlyComplete();
7097 <                            break;
7098 <                        }
7099 <                        t = (MapReduceEntriesToIntTask<K,V>)par;
6238 >                CountedCompleter<?> c;
6239 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6240 >                    @SuppressWarnings("unchecked")
6241 >                    MapReduceEntriesToIntTask<K,V>
6242 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
6243 >                        s = t.rights;
6244 >                    while (s != null) {
6245 >                        t.result = reducer.applyAsInt(t.result, s.result);
6246 >                        s = t.rights = s.nextRight;
6247                      }
7101                    else if (t.casPending(c, c - 1))
7102                        break;
6248                  }
7104            } catch (Throwable ex) {
7105                return tryCompleteComputation(ex);
7106            }
7107            MapReduceEntriesToIntTask<K,V> s = rights;
7108            if (s != null && !inForkJoinPool()) {
7109                do  {
7110                    if (s.tryUnfork())
7111                        s.exec();
7112                } while ((s = s.nextRight) != null);
6249              }
7114            return false;
6250          }
7116        public final Integer getRawResult() { return result; }
6251      }
6252  
6253 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6253 >    @SuppressWarnings("serial")
6254 >    static final class MapReduceMappingsToIntTask<K,V>
6255          extends BulkTask<K,V,Integer> {
6256 <        final ObjectByObjectToInt<? super K, ? super V> transformer;
6257 <        final IntByIntToInt reducer;
6256 >        final ToIntBiFunction<? super K, ? super V> transformer;
6257 >        final IntBinaryOperator reducer;
6258          final int basis;
6259          int result;
6260          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6261          MapReduceMappingsToIntTask
6262 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6263 <             MapReduceMappingsToIntTask<K,V> rights,
6264 <             ObjectByObjectToInt<? super K, ? super V> transformer,
6262 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6263 >             MapReduceMappingsToIntTask<K,V> nextRight,
6264 >             ToIntBiFunction<? super K, ? super V> transformer,
6265               int basis,
6266 <             IntByIntToInt reducer) {
6267 <            super(m, p, b); this.nextRight = nextRight;
6266 >             IntBinaryOperator reducer) {
6267 >            super(p, b, i, f, t); this.nextRight = nextRight;
6268              this.transformer = transformer;
6269              this.basis = basis; this.reducer = reducer;
6270          }
6271 <        @SuppressWarnings("unchecked") public final boolean exec() {
6272 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
6273 <                this.transformer;
6274 <            final IntByIntToInt reducer = this.reducer;
6275 <            if (transformer == null || reducer == null)
6276 <                return abortOnNullFunction();
6277 <            try {
6278 <                final int id = this.basis;
6279 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6280 <                    do {} while (!casPending(c = pending, c+1));
6271 >        public final Integer getRawResult() { return result; }
6272 >        public final void compute() {
6273 >            final ToIntBiFunction<? super K, ? super V> transformer;
6274 >            final IntBinaryOperator reducer;
6275 >            if ((transformer = this.transformer) != null &&
6276 >                (reducer = this.reducer) != null) {
6277 >                int r = this.basis;
6278 >                for (int i = baseIndex, f, h; batch > 0 &&
6279 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6280 >                    addToPendingCount(1);
6281                      (rights = new MapReduceMappingsToIntTask<K,V>
6282 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6282 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6283 >                      rights, transformer, r, reducer)).fork();
6284                  }
6285 <                int r = id;
6286 <                Object v;
7151 <                while ((v = advance()) != null)
7152 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6285 >                for (Node<K,V> p; (p = advance()) != null; )
6286 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6287                  result = r;
6288 <                for (MapReduceMappingsToIntTask<K,V> t = this, s;;) {
6289 <                    int c; BulkTask<K,V,?> par;
6290 <                    if ((c = t.pending) == 0) {
6291 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6292 <                            t.result = reducer.apply(t.result, s.result);
6293 <                        }
6294 <                        if ((par = t.parent) == null ||
6295 <                            !(par instanceof MapReduceMappingsToIntTask)) {
6296 <                            t.quietlyComplete();
7163 <                            break;
7164 <                        }
7165 <                        t = (MapReduceMappingsToIntTask<K,V>)par;
6288 >                CountedCompleter<?> c;
6289 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6290 >                    @SuppressWarnings("unchecked")
6291 >                    MapReduceMappingsToIntTask<K,V>
6292 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6293 >                        s = t.rights;
6294 >                    while (s != null) {
6295 >                        t.result = reducer.applyAsInt(t.result, s.result);
6296 >                        s = t.rights = s.nextRight;
6297                      }
7167                    else if (t.casPending(c, c - 1))
7168                        break;
6298                  }
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);
6299              }
7180            return false;
6300          }
7182        public final Integer getRawResult() { return result; }
6301      }
6302  
6303      // Unsafe mechanics
6304 <    private static final sun.misc.Unsafe UNSAFE;
6305 <    private static final long counterOffset;
6306 <    private static final long sizeCtlOffset;
6307 <    private static final long ABASE;
6304 >    private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
6305 >    private static final long SIZECTL;
6306 >    private static final long TRANSFERINDEX;
6307 >    private static final long BASECOUNT;
6308 >    private static final long CELLSBUSY;
6309 >    private static final long CELLVALUE;
6310 >    private static final int ABASE;
6311      private static final int ASHIFT;
6312  
6313      static {
7193        int ss;
6314          try {
6315 <            UNSAFE = sun.misc.Unsafe.getUnsafe();
6316 <            Class<?> k = ConcurrentHashMap.class;
6317 <            counterOffset = UNSAFE.objectFieldOffset
6318 <                (k.getDeclaredField("counter"));
6319 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6320 <                (k.getDeclaredField("sizeCtl"));
6321 <            Class<?> sc = Node[].class;
6322 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6323 <            ss = UNSAFE.arrayIndexScale(sc);
6324 <        } catch (Exception e) {
6315 >            SIZECTL = U.objectFieldOffset
6316 >                (ConcurrentHashMap.class.getDeclaredField("sizeCtl"));
6317 >            TRANSFERINDEX = U.objectFieldOffset
6318 >                (ConcurrentHashMap.class.getDeclaredField("transferIndex"));
6319 >            BASECOUNT = U.objectFieldOffset
6320 >                (ConcurrentHashMap.class.getDeclaredField("baseCount"));
6321 >            CELLSBUSY = U.objectFieldOffset
6322 >                (ConcurrentHashMap.class.getDeclaredField("cellsBusy"));
6323 >
6324 >            CELLVALUE = U.objectFieldOffset
6325 >                (CounterCell.class.getDeclaredField("value"));
6326 >
6327 >            ABASE = U.arrayBaseOffset(Node[].class);
6328 >            int scale = U.arrayIndexScale(Node[].class);
6329 >            if ((scale & (scale - 1)) != 0)
6330 >                throw new Error("array index scale not a power of two");
6331 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6332 >        } catch (ReflectiveOperationException e) {
6333              throw new Error(e);
6334          }
6335 <        if ((ss & (ss-1)) != 0)
6336 <            throw new Error("data type scale not a power of two");
6337 <        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6335 >
6336 >        // Reduce the risk of rare disastrous classloading in first call to
6337 >        // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
6338 >        Class<?> ensureLoaded = LockSupport.class;
6339      }
6340   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines