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

Comparing jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java (file contents):
Revision 1.145 by jsr166, Sun Nov 18 18:03:10 2012 UTC vs.
Revision 1.238 by jsr166, Thu Jul 18 18:21:22 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines