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

Comparing jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java (file contents):
Revision 1.143 by jsr166, Fri Nov 9 03:30:03 2012 UTC vs.
Revision 1.189 by jsr166, Mon Feb 18 01:30:23 2013 UTC

# Line 5 | Line 5
5   */
6  
7   package java.util.concurrent;
8 import java.util.concurrent.atomic.LongAdder;
8   import java.util.concurrent.ForkJoinPool;
9 < import java.util.concurrent.ForkJoinTask;
9 > import java.util.concurrent.CountedCompleter;
10 > import java.util.function.*;
11 > import java.util.Spliterator;
12 > import java.util.stream.Stream;
13 > import java.util.stream.Streams;
14  
15   import java.util.Comparator;
16   import java.util.Arrays;
# Line 24 | Line 27 | import java.util.Enumeration;
27   import java.util.ConcurrentModificationException;
28   import java.util.NoSuchElementException;
29   import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.ThreadLocalRandom;
28 import java.util.concurrent.locks.LockSupport;
30   import java.util.concurrent.locks.AbstractQueuedSynchronizer;
31 + import java.util.concurrent.atomic.AtomicInteger;
32   import java.util.concurrent.atomic.AtomicReference;
31
33   import java.io.Serializable;
34  
35   /**
# Line 43 | Line 44 | import java.io.Serializable;
44   * interoperable with {@code Hashtable} in programs that rely on its
45   * thread safety but not on its synchronization details.
46   *
47 < * <p> Retrieval operations (including {@code get}) generally do not
47 > * <p>Retrieval operations (including {@code get}) generally do not
48   * block, so may overlap with update operations (including {@code put}
49   * and {@code remove}). Retrievals reflect the results of the most
50   * recently <em>completed</em> update operations holding upon their
# Line 64 | Line 65 | import java.io.Serializable;
65   * that may be adequate for monitoring or estimation purposes, but not
66   * for program control.
67   *
68 < * <p> The table is dynamically expanded when there are too many
68 > * <p>The table is dynamically expanded when there are too many
69   * collisions (i.e., keys that have distinct hash codes but fall into
70   * the same slot modulo the table size), with the expected average
71   * effect of maintaining roughly two bins per mapping (corresponding
# Line 85 | Line 86 | import java.io.Serializable;
86   * {@code hashCode()} is a sure way to slow down performance of any
87   * hash table.
88   *
89 < * <p> A {@link Set} projection of a ConcurrentHashMap may be created
89 > * <p>A {@link Set} projection of a ConcurrentHashMap may be created
90   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
91   * (using {@link #keySet(Object)} when only keys are of interest, and the
92   * mapped values are (perhaps transiently) not used or all take the
93   * same mapping value.
94   *
95 < * <p> A ConcurrentHashMap can be used as scalable frequency map (a
96 < * form of histogram or multiset) by using {@link LongAdder} values
97 < * and initializing via {@link #computeIfAbsent}. For example, to add
98 < * a count to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you
99 < * can use {@code freqs.computeIfAbsent(k -> new
100 < * LongAdder()).increment();}
95 > * <p>A ConcurrentHashMap can be used as scalable frequency map (a
96 > * form of histogram or multiset) by using {@link
97 > * java.util.concurrent.atomic.LongAdder} values and initializing via
98 > * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count
99 > * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
100 > * {@code freqs.computeIfAbsent(k -> new LongAdder()).increment();}
101   *
102   * <p>This class and its views and iterators implement all of the
103   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
104   * interfaces.
105   *
106 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
106 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
107   * does <em>not</em> allow {@code null} to be used as a key or value.
108   *
109 < * <p>ConcurrentHashMaps support parallel operations using the {@link
110 < * ForkJoinPool#commonPool}. (Tasks that may be used in other contexts
111 < * are available in class {@link ForkJoinTasks}). These operations are
112 < * designed to be safely, and often sensibly, applied even with maps
113 < * that are being concurrently updated by other threads; for example,
114 < * when computing a snapshot summary of the values in a shared
115 < * registry.  There are three kinds of operation, each with four
116 < * forms, accepting functions with Keys, Values, Entries, and (Key,
117 < * Value) arguments and/or return values. (The first three forms are
118 < * also available via the {@link #keySet()}, {@link #values()} and
119 < * {@link #entrySet()} views). Because the elements of a
120 < * ConcurrentHashMap are not ordered in any particular way, and may be
121 < * processed in different orders in different parallel executions, the
122 < * correctness of supplied functions should not depend on any
123 < * ordering, or on any other objects or values that may transiently
124 < * change while computation is in progress; and except for forEach
125 < * actions, should ideally be side-effect-free.
109 > * <p>ConcurrentHashMaps support sequential and parallel operations
110 > * bulk operations. (Parallel forms use the {@link
111 > * ForkJoinPool#commonPool()}). Tasks that may be used in other
112 > * contexts are available in class {@link ForkJoinTasks}. These
113 > * operations are designed to be safely, and often sensibly, applied
114 > * even with maps that are being concurrently updated by other
115 > * threads; for example, when computing a snapshot summary of the
116 > * values in a shared registry.  There are three kinds of operation,
117 > * each with four forms, accepting functions with Keys, Values,
118 > * Entries, and (Key, Value) arguments and/or return values. Because
119 > * the elements of a ConcurrentHashMap are not ordered in any
120 > * particular way, and may be processed in different orders in
121 > * different parallel executions, the correctness of supplied
122 > * functions should not depend on any ordering, or on any other
123 > * objects or values that may transiently change while computation is
124 > * in progress; and except for forEach actions, should ideally be
125 > * side-effect-free.
126   *
127   * <ul>
128   * <li> forEach: Perform a given action on each element.
# Line 148 | Line 149 | import java.io.Serializable;
149   * <li> Reductions to scalar doubles, longs, and ints, using a
150   * given basis value.</li>
151   *
151 * </li>
152   * </ul>
153 + * </li>
154   * </ul>
155   *
156   * <p>The concurrency properties of bulk operations follow
# Line 187 | Line 188 | import java.io.Serializable;
188   * arguments can be supplied using {@code new
189   * AbstractMap.SimpleEntry(k,v)}.
190   *
191 < * <p> Bulk operations may complete abruptly, throwing an
191 > * <p>Bulk operations may complete abruptly, throwing an
192   * exception encountered in the application of a supplied
193   * function. Bear in mind when handling such exceptions that other
194   * concurrently executing functions could also have thrown
195   * exceptions, or would have done so if the first exception had
196   * not occurred.
197   *
198 < * <p>Parallel speedups for bulk operations compared to sequential
199 < * processing are common but not guaranteed.  Operations involving
200 < * brief functions on small maps may execute more slowly than
201 < * sequential loops if the underlying work to parallelize the
202 < * computation is more expensive than the computation itself.
203 < * Similarly, parallelization may not lead to much actual parallelism
204 < * if all processors are busy performing unrelated tasks.
198 > * <p>Speedups for parallel compared to sequential forms are common
199 > * but not guaranteed.  Parallel operations involving brief functions
200 > * on small maps may execute more slowly than sequential forms if the
201 > * underlying work to parallelize the computation is more expensive
202 > * than the computation itself.  Similarly, parallelization may not
203 > * lead to much actual parallelism if all processors are busy
204 > * performing unrelated tasks.
205   *
206 < * <p> All arguments to all task methods must be non-null.
206 < *
207 < * <p><em>jsr166e note: During transition, this class
208 < * uses nested functional interfaces with different names but the
209 < * same forms as those expected for JDK8.<em>
206 > * <p>All arguments to all task methods must be non-null.
207   *
208   * <p>This class is a member of the
209   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
# Line 217 | Line 214 | import java.io.Serializable;
214   * @param <K> the type of keys maintained by this map
215   * @param <V> the type of mapped values
216   */
217 < public class ConcurrentHashMap<K, V>
218 <    implements ConcurrentMap<K, V>, Serializable {
217 > public class ConcurrentHashMap<K,V>
218 >    implements ConcurrentMap<K,V>, Serializable {
219      private static final long serialVersionUID = 7249069246763182397L;
220  
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
221      /*
222       * Overview:
223       *
# Line 301 | Line 228 | public class ConcurrentHashMap<K, V>
228       * the same or better than java.util.HashMap, and to support high
229       * initial insertion rates on an empty table by many threads.
230       *
231 <     * Each key-value mapping is held in a Node.  Because Node fields
232 <     * can contain special values, they are defined using plain Object
233 <     * types. Similarly in turn, all internal methods that use them
234 <     * work off Object types. And similarly, so do the internal
235 <     * methods of auxiliary iterator and view classes.  All public
236 <     * generic typed methods relay in/out of these internal methods,
237 <     * supplying null-checks and casts as needed. This also allows
238 <     * many of the public methods to be factored into a smaller number
239 <     * of internal methods (although sadly not so for the five
313 <     * variants of put-related operations). The validation-based
314 <     * approach explained below leads to a lot of code sprawl because
231 >     * Each key-value mapping is held in a Node.  Because Node key
232 >     * fields can contain special values, they are defined using plain
233 >     * Object types (not type "K"). This leads to a lot of explicit
234 >     * casting (and many explicit warning suppressions to tell
235 >     * compilers not to complain about it). It also allows some of the
236 >     * public methods to be factored into a smaller number of internal
237 >     * methods (although sadly not so for the five variants of
238 >     * put-related operations). The validation-based approach
239 >     * explained below leads to a lot of code sprawl because
240       * retry-control precludes factoring into smaller methods.
241       *
242       * The table is lazily initialized to a power-of-two size upon the
# Line 325 | Line 250 | public class ConcurrentHashMap<K, V>
250       * as lookups check hash code and non-nullness of value before
251       * checking key equality.
252       *
253 <     * We use the top two bits of Node hash fields for control
254 <     * purposes -- they are available anyway because of addressing
255 <     * constraints.  As explained further below, these top bits are
256 <     * used as follows:
257 <     *  00 - Normal
258 <     *  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).
253 >     * We use the top (sign) bit of Node hash fields for control
254 >     * purposes -- it is available anyway because of addressing
255 >     * constraints.  Nodes with negative hash fields are forwarding
256 >     * nodes to either TreeBins or resized tables.  The lower 31 bits
257 >     * of each normal Node's hash field contain a transformation of
258 >     * the key's hash code.
259       *
260       * Insertion (via put or its variants) of the first node in an
261       * empty bin is performed by just CASing it to the bin.  This is
# Line 346 | Line 264 | public class ConcurrentHashMap<K, V>
264       * delete, and replace) require locks.  We do not want to waste
265       * the space required to associate a distinct lock object with
266       * each bin, so instead use the first node of a bin list itself as
267 <     * a lock. Blocking support for these locks relies on the builtin
268 <     * "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.
267 >     * a lock. Locking support for these locks relies on builtin
268 >     * "synchronized" monitors.
269       *
270       * Using the first node of a list as a lock does not by itself
271       * suffice though: When a node is locked, any update must first
# Line 413 | Line 327 | public class ConcurrentHashMap<K, V>
327       * iterators in the same way.
328       *
329       * The table is resized when occupancy exceeds a percentage
330 <     * threshold (nominally, 0.75, but see below).  Only a single
331 <     * thread performs the resize (using field "sizeCtl", to arrange
332 <     * exclusion), but the table otherwise remains usable for reads
333 <     * and updates. Resizing proceeds by transferring bins, one by
334 <     * one, from the table to the next table.  Because we are using
335 <     * power-of-two expansion, the elements from each bin must either
336 <     * stay at same index, or move with a power of two offset. We
337 <     * eliminate unnecessary node creation by catching cases where old
338 <     * nodes can be reused because their next fields won't change.  On
339 <     * average, only about one-sixth of them need cloning when a table
340 <     * doubles. The nodes they replace will be garbage collectable as
341 <     * soon as they are no longer referenced by any reader thread that
342 <     * may be in the midst of concurrently traversing table.  Upon
343 <     * transfer, the old table bin contains only a special forwarding
344 <     * node (with hash field "MOVED") that contains the next table as
345 <     * its key. On encountering a forwarding node, access and update
346 <     * operations restart, using the new table.
347 <     *
348 <     * Each bin transfer requires its bin lock. However, unlike other
349 <     * cases, a transfer can skip a bin if it fails to acquire its
350 <     * lock, and revisit it later (unless it is a TreeBin). Method
351 <     * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
352 <     * have been skipped because of failure to acquire a lock, and
353 <     * blocks only if none are available (i.e., only very rarely).
354 <     * The transfer operation must also ensure that all accessible
355 <     * bins in both the old and new table are usable by any traversal.
356 <     * When there are no lock acquisition failures, this is arranged
357 <     * simply by proceeding from the last bin (table.length - 1) up
358 <     * towards the first.  Upon seeing a forwarding node, traversals
359 <     * (see class Iter) arrange to move to the new table
360 <     * without revisiting nodes.  However, when any node is skipped
361 <     * during a transfer, all earlier table bins may have become
362 <     * visible, so are initialized with a reverse-forwarding node back
363 <     * to the old table until the new ones are established. (This
364 <     * sometimes requires transiently locking a forwarding node, which
365 <     * is possible under the above encoding.) These more expensive
366 <     * mechanics trigger only when necessary.
330 >     * threshold (nominally, 0.75, but see below).  Any thread
331 >     * noticing an overfull bin may assist in resizing after the
332 >     * initiating thread allocates and sets up the replacement
333 >     * array. However, rather than stalling, these other threads may
334 >     * proceed with insertions etc.  The use of TreeBins shields us
335 >     * from the worst case effects of overfilling while resizes are in
336 >     * progress.  Resizing proceeds by transferring bins, one by one,
337 >     * from the table to the next table. To enable concurrency, the
338 >     * next table must be (incrementally) prefilled with place-holders
339 >     * serving as reverse forwarders to the old table.  Because we are
340 >     * using power-of-two expansion, the elements from each bin must
341 >     * either stay at same index, or move with a power of two
342 >     * offset. We eliminate unnecessary node creation by catching
343 >     * cases where old nodes can be reused because their next fields
344 >     * won't change.  On average, only about one-sixth of them need
345 >     * cloning when a table doubles. The nodes they replace will be
346 >     * garbage collectable as soon as they are no longer referenced by
347 >     * any reader thread that may be in the midst of concurrently
348 >     * traversing table.  Upon transfer, the old table bin contains
349 >     * only a special forwarding node (with hash field "MOVED") that
350 >     * contains the next table as its key. On encountering a
351 >     * forwarding node, access and update operations restart, using
352 >     * the new table.
353 >     *
354 >     * Each bin transfer requires its bin lock, which can stall
355 >     * waiting for locks while resizing. However, because other
356 >     * threads can join in and help resize rather than contend for
357 >     * locks, average aggregate waits become shorter as resizing
358 >     * progresses.  The transfer operation must also ensure that all
359 >     * accessible bins in both the old and new table are usable by any
360 >     * traversal.  This is arranged by proceeding from the last bin
361 >     * (table.length - 1) up towards the first.  Upon seeing a
362 >     * forwarding node, traversals (see class Traverser) arrange to
363 >     * move to the new table without revisiting nodes.  However, to
364 >     * ensure that no intervening nodes are skipped, bin splitting can
365 >     * only begin after the associated reverse-forwarders are in
366 >     * place.
367       *
368       * The traversal scheme also applies to partial traversals of
369       * ranges of bins (via an alternate Traverser constructor)
# Line 464 | Line 378 | public class ConcurrentHashMap<K, V>
378       * These cases attempt to override the initial capacity settings,
379       * but harmlessly fail to take effect in cases of races.
380       *
381 <     * The element count is maintained using a LongAdder, which avoids
382 <     * contention on updates but can encounter cache thrashing if read
383 <     * too frequently during concurrent access. To avoid reading so
384 <     * often, resizing is attempted either when a bin lock is
385 <     * contended, or upon adding to a bin already holding two or more
386 <     * nodes (checked before adding in the xIfAbsent methods, after
387 <     * adding in others). Under uniform hash distributions, the
388 <     * probability of this occurring at threshold is around 13%,
389 <     * meaning that only about 1 in 8 puts check threshold (and after
390 <     * resizing, many fewer do so). But this approximation has high
391 <     * variance for small table sizes, so we check on any collision
392 <     * for sizes <= 64. The bulk putAll operation further reduces
393 <     * contention by only committing count updates upon these size
394 <     * checks.
381 >     * The element count is maintained using a specialization of
382 >     * LongAdder. We need to incorporate a specialization rather than
383 >     * just use a LongAdder in order to access implicit
384 >     * contention-sensing that leads to creation of multiple
385 >     * Cells.  The counter mechanics avoid contention on
386 >     * updates but can encounter cache thrashing if read too
387 >     * frequently during concurrent access. To avoid reading so often,
388 >     * resizing under contention is attempted only upon adding to a
389 >     * bin already holding two or more nodes. Under uniform hash
390 >     * distributions, the probability of this occurring at threshold
391 >     * is around 13%, meaning that only about 1 in 8 puts check
392 >     * threshold (and after resizing, many fewer do so). The bulk
393 >     * putAll operation further reduces contention by only committing
394 >     * count updates upon these size checks.
395       *
396       * Maintaining API and serialization compatibility with previous
397       * versions of this class introduces several oddities. Mainly: We
# Line 528 | Line 442 | public class ConcurrentHashMap<K, V>
442      private static final float LOAD_FACTOR = 0.75f;
443  
444      /**
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    /**
445       * The bin count threshold for using a tree rather than list for a
446       * bin.  The value reflects the approximate break-even point for
447       * using tree-based operations.
448       */
449      private static final int TREE_THRESHOLD = 8;
450  
451 +    /**
452 +     * Minimum number of rebinnings per transfer step. Ranges are
453 +     * subdivided to allow multiple resizer threads.  This value
454 +     * serves as a lower bound to avoid resizers encountering
455 +     * excessive memory contention.  The value should be at least
456 +     * DEFAULT_CAPACITY.
457 +     */
458 +    private static final int MIN_TRANSFER_STRIDE = 16;
459 +
460      /*
461 <     * Encodings for special uses of Node hash fields. See above for
546 <     * explanation.
461 >     * Encodings for Node hash fields. See above for explanation.
462       */
463      static final int MOVED     = 0x80000000; // hash field for forwarding nodes
464 <    static final int LOCKED    = 0x40000000; // set/tested only as a bit
465 <    static final int WAITING   = 0xc0000000; // both bits set/tested together
466 <    static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
464 >    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
465 >
466 >    /** Number of CPUS, to place bounds on some sizings */
467 >    static final int NCPU = Runtime.getRuntime().availableProcessors();
468 >
469 >    /* ---------------- Counters -------------- */
470 >
471 >    // Adapted from LongAdder and Striped64.
472 >    // See their internal docs for explanation.
473 >
474 >    // A padded cell for distributing counts
475 >    static final class Cell {
476 >        volatile long p0, p1, p2, p3, p4, p5, p6;
477 >        volatile long value;
478 >        volatile long q0, q1, q2, q3, q4, q5, q6;
479 >        Cell(long x) { value = x; }
480 >    }
481  
482      /* ---------------- Fields -------------- */
483  
# Line 556 | Line 485 | public class ConcurrentHashMap<K, V>
485       * The array of bins. Lazily initialized upon first insertion.
486       * Size is always a power of two. Accessed directly by iterators.
487       */
488 <    transient volatile Node[] table;
488 >    transient volatile Node<V>[] table;
489 >
490 >    /**
491 >     * The next table to use; non-null only while resizing.
492 >     */
493 >    private transient volatile Node<V>[] nextTable;
494  
495      /**
496 <     * The counter maintaining number of elements.
496 >     * Base counter value, used mainly when there is no contention,
497 >     * but also as a fallback during table initialization
498 >     * races. Updated via CAS.
499       */
500 <    private transient final LongAdder counter;
500 >    private transient volatile long baseCount;
501  
502      /**
503       * Table initialization and resizing control.  When negative, the
504 <     * table is being initialized or resized. Otherwise, when table is
505 <     * null, holds the initial table size to use upon creation, or 0
506 <     * for default. After initialization, holds the next element count
507 <     * value upon which to resize the table.
504 >     * table is being initialized or resized: -1 for initialization,
505 >     * else -(1 + the number of active resizing threads).  Otherwise,
506 >     * when table is null, holds the initial table size to use upon
507 >     * creation, or 0 for default. After initialization, holds the
508 >     * next element count value upon which to resize the table.
509       */
510      private transient volatile int sizeCtl;
511  
512 +    /**
513 +     * The next table index (plus one) to split while resizing.
514 +     */
515 +    private transient volatile int transferIndex;
516 +
517 +    /**
518 +     * The least available table index to split while resizing.
519 +     */
520 +    private transient volatile int transferOrigin;
521 +
522 +    /**
523 +     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
524 +     */
525 +    private transient volatile int cellsBusy;
526 +
527 +    /**
528 +     * Table of counter cells. When non-null, size is a power of 2.
529 +     */
530 +    private transient volatile Cell[] counterCells;
531 +
532      // views
533      private transient KeySetView<K,V> keySet;
534      private transient ValuesView<K,V> values;
# Line 594 | Line 551 | public class ConcurrentHashMap<K, V>
551       * inline assignments below.
552       */
553  
554 <    static final Node tabAt(Node[] tab, int i) { // used by Iter
555 <        return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
554 >    @SuppressWarnings("unchecked") static final <V> Node<V> tabAt
555 >        (Node<V>[] tab, int i) { // used by Traverser
556 >        return (Node<V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
557      }
558  
559 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
560 <        return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
559 >    private static final <V> boolean casTabAt
560 >        (Node<V>[] tab, int i, Node<V> c, Node<V> v) {
561 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
562      }
563  
564 <    private static final void setTabAt(Node[] tab, int i, Node v) {
565 <        UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
564 >    private static final <V> void setTabAt
565 >        (Node<V>[] tab, int i, Node<V> v) {
566 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
567      }
568  
569      /* ---------------- Nodes -------------- */
# Line 618 | Line 578 | public class ConcurrentHashMap<K, V>
578       * before a val, but can only be used after checking val to be
579       * non-null.
580       */
581 <    static class Node {
582 <        volatile int hash;
581 >    static class Node<V> {
582 >        final int hash;
583          final Object key;
584 <        volatile Object val;
585 <        volatile Node next;
584 >        volatile V val;
585 >        volatile Node<V> next;
586  
587 <        Node(int hash, Object key, Object val, Node next) {
587 >        Node(int hash, Object key, V val, Node<V> next) {
588              this.hash = hash;
589              this.key = key;
590              this.val = val;
591              this.next = next;
592          }
633
634        /** CompareAndSet the hash field */
635        final boolean casHash(int cmp, int val) {
636            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
637        }
638
639        /** The number of spins before blocking for a lock */
640        static final int MAX_SPINS =
641            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
642
643        /**
644         * Spins a while if LOCKED bit set and this node is the first
645         * of its bin, and then sets WAITING bits on hash field and
646         * blocks (once) if they are still set.  It is OK for this
647         * method to return even if lock is not available upon exit,
648         * which enables these simple single-wait mechanics.
649         *
650         * The corresponding signalling operation is performed within
651         * callers: Upon detecting that WAITING has been set when
652         * unlocking lock (via a failed CAS from non-waiting LOCKED
653         * state), unlockers acquire the sync lock and perform a
654         * notifyAll.
655         *
656         * The initial sanity check on tab and bounds is not currently
657         * necessary in the only usages of this method, but enables
658         * use in other future contexts.
659         */
660        final void tryAwaitLock(Node[] tab, int i) {
661            if (tab != null && i >= 0 && i < tab.length) { // sanity check
662                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
663                int spins = MAX_SPINS, h;
664                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
665                    if (spins >= 0) {
666                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
667                        if (r >= 0 && --spins == 0)
668                            Thread.yield();  // yield before block
669                    }
670                    else if (casHash(h, h | WAITING)) {
671                        synchronized (this) {
672                            if (tabAt(tab, i) == this &&
673                                (hash & WAITING) == WAITING) {
674                                try {
675                                    wait();
676                                } catch (InterruptedException ie) {
677                                    try {
678                                        Thread.currentThread().interrupt();
679                                    } catch (SecurityException ignore) {
680                                    }
681                                }
682                            }
683                            else
684                                notifyAll(); // possibly won race vs signaller
685                        }
686                        break;
687                    }
688                }
689            }
690        }
691
692        // Unsafe mechanics for casHash
693        private static final sun.misc.Unsafe UNSAFE;
694        private static final long hashOffset;
695
696        static {
697            try {
698                UNSAFE = sun.misc.Unsafe.getUnsafe();
699                Class<?> k = Node.class;
700                hashOffset = UNSAFE.objectFieldOffset
701                    (k.getDeclaredField("hash"));
702            } catch (Exception e) {
703                throw new Error(e);
704            }
705        }
593      }
594  
595      /* ---------------- TreeBins -------------- */
# Line 710 | Line 597 | public class ConcurrentHashMap<K, V>
597      /**
598       * Nodes for use in TreeBins
599       */
600 <    static final class TreeNode extends Node {
601 <        TreeNode parent;  // red-black tree links
602 <        TreeNode left;
603 <        TreeNode right;
604 <        TreeNode prev;    // needed to unlink next upon deletion
600 >    static final class TreeNode<V> extends Node<V> {
601 >        TreeNode<V> parent;  // red-black tree links
602 >        TreeNode<V> left;
603 >        TreeNode<V> right;
604 >        TreeNode<V> prev;    // needed to unlink next upon deletion
605          boolean red;
606  
607 <        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
607 >        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
608              super(hash, key, val, next);
609              this.parent = parent;
610          }
# Line 766 | Line 653 | public class ConcurrentHashMap<K, V>
653       * and writers. Since we don't need to export full Lock API, we
654       * just override the minimal AQS methods and use them directly.
655       */
656 <    static final class TreeBin extends AbstractQueuedSynchronizer {
656 >    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
657          private static final long serialVersionUID = 2249069246763182397L;
658 <        transient TreeNode root;  // root of tree
659 <        transient TreeNode first; // head of next-pointer list
658 >        transient TreeNode<V> root;  // root of tree
659 >        transient TreeNode<V> first; // head of next-pointer list
660  
661          /* AQS overrides */
662          public final boolean isHeldExclusively() { return getState() > 0; }
# Line 800 | Line 687 | public class ConcurrentHashMap<K, V>
687          }
688  
689          /** From CLR */
690 <        private void rotateLeft(TreeNode p) {
690 >        private void rotateLeft(TreeNode<V> p) {
691              if (p != null) {
692 <                TreeNode r = p.right, pp, rl;
692 >                TreeNode<V> r = p.right, pp, rl;
693                  if ((rl = p.right = r.left) != null)
694                      rl.parent = p;
695                  if ((pp = r.parent = p.parent) == null)
# Line 817 | Line 704 | public class ConcurrentHashMap<K, V>
704          }
705  
706          /** From CLR */
707 <        private void rotateRight(TreeNode p) {
707 >        private void rotateRight(TreeNode<V> p) {
708              if (p != null) {
709 <                TreeNode l = p.left, pp, lr;
709 >                TreeNode<V> l = p.left, pp, lr;
710                  if ((lr = p.left = l.right) != null)
711                      lr.parent = p;
712                  if ((pp = l.parent = p.parent) == null)
# Line 837 | Line 724 | public class ConcurrentHashMap<K, V>
724           * Returns the TreeNode (or null if not found) for the given key
725           * starting at given root.
726           */
727 <        @SuppressWarnings("unchecked") final TreeNode getTreeNode
728 <            (int h, Object k, TreeNode p) {
727 >        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
728 >            (int h, Object k, TreeNode<V> p) {
729              Class<?> c = k.getClass();
730              while (p != null) {
731                  int dir, ph;  Object pk; Class<?> pc;
# Line 848 | Line 735 | public class ConcurrentHashMap<K, V>
735                      if (c != (pc = pk.getClass()) ||
736                          !(k instanceof Comparable) ||
737                          (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
738 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
739 <                        TreeNode r = null, s = null, pl, pr;
740 <                        if (dir >= 0) {
741 <                            if ((pl = p.left) != null && h <= pl.hash)
742 <                                s = pl;
738 >                        if ((dir = (c == pc) ? 0 :
739 >                             c.getName().compareTo(pc.getName())) == 0) {
740 >                            TreeNode<V> r = null, pl, pr; // check both sides
741 >                            if ((pr = p.right) != null && h >= pr.hash &&
742 >                                (r = getTreeNode(h, k, pr)) != null)
743 >                                return r;
744 >                            else if ((pl = p.left) != null && h <= pl.hash)
745 >                                dir = -1;
746 >                            else // nothing there
747 >                                return null;
748                          }
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;
749                      }
750                  }
751                  else
# Line 872 | Line 760 | public class ConcurrentHashMap<K, V>
760           * read-lock to call getTreeNode, but during failure to get
761           * lock, searches along next links.
762           */
763 <        final Object getValue(int h, Object k) {
764 <            Node r = null;
763 >        final V getValue(int h, Object k) {
764 >            Node<V> r = null;
765              int c = getState(); // Must read lock state first
766 <            for (Node e = first; e != null; e = e.next) {
766 >            for (Node<V> e = first; e != null; e = e.next) {
767                  if (c <= 0 && compareAndSetState(c, c - 1)) {
768                      try {
769                          r = getTreeNode(h, k, root);
# Line 884 | Line 772 | public class ConcurrentHashMap<K, V>
772                      }
773                      break;
774                  }
775 <                else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
775 >                else if (e.hash == h && k.equals(e.key)) {
776                      r = e;
777                      break;
778                  }
# Line 898 | Line 786 | public class ConcurrentHashMap<K, V>
786           * Finds or adds a node.
787           * @return null if added
788           */
789 <        @SuppressWarnings("unchecked") final TreeNode putTreeNode
790 <            (int h, Object k, Object v) {
789 >        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
790 >            (int h, Object k, V v) {
791              Class<?> c = k.getClass();
792 <            TreeNode pp = root, p = null;
792 >            TreeNode<V> pp = root, p = null;
793              int dir = 0;
794              while (pp != null) { // find existing node or leaf to insert at
795                  int ph;  Object pk; Class<?> pc;
# Line 912 | Line 800 | public class ConcurrentHashMap<K, V>
800                      if (c != (pc = pk.getClass()) ||
801                          !(k instanceof Comparable) ||
802                          (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
803 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
804 <                        TreeNode r = null, s = null, pl, pr;
805 <                        if (dir >= 0) {
806 <                            if ((pl = p.left) != null && h <= pl.hash)
807 <                                s = pl;
803 >                        TreeNode<V> s = null, r = null, pr;
804 >                        if ((dir = (c == pc) ? 0 :
805 >                             c.getName().compareTo(pc.getName())) == 0) {
806 >                            if ((pr = p.right) != null && h >= pr.hash &&
807 >                                (r = getTreeNode(h, k, pr)) != null)
808 >                                return r;
809 >                            else // continue left
810 >                                dir = -1;
811                          }
812                          else if ((pr = p.right) != null && h >= pr.hash)
813                              s = pr;
# Line 929 | Line 820 | public class ConcurrentHashMap<K, V>
820                  pp = (dir > 0) ? p.right : p.left;
821              }
822  
823 <            TreeNode f = first;
824 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
823 >            TreeNode<V> f = first;
824 >            TreeNode<V> x = first = new TreeNode<V>(h, k, v, f, p);
825              if (p == null)
826                  root = x;
827              else { // attach and rebalance; adapted from CLR
828 <                TreeNode xp, xpp;
828 >                TreeNode<V> xp, xpp;
829                  if (f != null)
830                      f.prev = x;
831                  if (dir <= 0)
# Line 944 | Line 835 | public class ConcurrentHashMap<K, V>
835                  x.red = true;
836                  while (x != null && (xp = x.parent) != null && xp.red &&
837                         (xpp = xp.parent) != null) {
838 <                    TreeNode xppl = xpp.left;
838 >                    TreeNode<V> xppl = xpp.left;
839                      if (xp == xppl) {
840 <                        TreeNode y = xpp.right;
840 >                        TreeNode<V> y = xpp.right;
841                          if (y != null && y.red) {
842                              y.red = false;
843                              xp.red = false;
# Line 968 | Line 859 | public class ConcurrentHashMap<K, V>
859                          }
860                      }
861                      else {
862 <                        TreeNode y = xppl;
862 >                        TreeNode<V> y = xppl;
863                          if (y != null && y.red) {
864                              y.red = false;
865                              xp.red = false;
# Line 990 | Line 881 | public class ConcurrentHashMap<K, V>
881                          }
882                      }
883                  }
884 <                TreeNode r = root;
884 >                TreeNode<V> r = root;
885                  if (r != null && r.red)
886                      r.red = false;
887              }
# Line 1005 | Line 896 | public class ConcurrentHashMap<K, V>
896           * that are accessible independently of lock. So instead we
897           * swap the tree linkages.
898           */
899 <        final void deleteTreeNode(TreeNode p) {
900 <            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
901 <            TreeNode pred = p.prev;
899 >        final void deleteTreeNode(TreeNode<V> p) {
900 >            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
901 >            TreeNode<V> pred = p.prev;
902              if (pred == null)
903                  first = next;
904              else
905                  pred.next = next;
906              if (next != null)
907                  next.prev = pred;
908 <            TreeNode replacement;
909 <            TreeNode pl = p.left;
910 <            TreeNode pr = p.right;
908 >            TreeNode<V> replacement;
909 >            TreeNode<V> pl = p.left;
910 >            TreeNode<V> pr = p.right;
911              if (pl != null && pr != null) {
912 <                TreeNode s = pr, sl;
912 >                TreeNode<V> s = pr, sl;
913                  while ((sl = s.left) != null) // find successor
914                      s = sl;
915                  boolean c = s.red; s.red = p.red; p.red = c; // swap colors
916 <                TreeNode sr = s.right;
917 <                TreeNode pp = p.parent;
916 >                TreeNode<V> sr = s.right;
917 >                TreeNode<V> pp = p.parent;
918                  if (s == pr) { // p was s's direct parent
919                      p.parent = s;
920                      s.right = p;
921                  }
922                  else {
923 <                    TreeNode sp = s.parent;
923 >                    TreeNode<V> sp = s.parent;
924                      if ((p.parent = sp) != null) {
925                          if (s == sp.left)
926                              sp.left = p;
# Line 1054 | Line 945 | public class ConcurrentHashMap<K, V>
945              }
946              else
947                  replacement = (pl != null) ? pl : pr;
948 <            TreeNode pp = p.parent;
948 >            TreeNode<V> pp = p.parent;
949              if (replacement == null) {
950                  if (pp == null) {
951                      root = null;
# Line 1073 | Line 964 | public class ConcurrentHashMap<K, V>
964                  p.left = p.right = p.parent = null;
965              }
966              if (!p.red) { // rebalance, from CLR
967 <                TreeNode x = replacement;
967 >                TreeNode<V> x = replacement;
968                  while (x != null) {
969 <                    TreeNode xp, xpl;
969 >                    TreeNode<V> xp, xpl;
970                      if (x.red || (xp = x.parent) == null) {
971                          x.red = false;
972                          break;
973                      }
974                      if (x == (xpl = xp.left)) {
975 <                        TreeNode sib = xp.right;
975 >                        TreeNode<V> sib = xp.right;
976                          if (sib != null && sib.red) {
977                              sib.red = false;
978                              xp.red = true;
# Line 1091 | Line 982 | public class ConcurrentHashMap<K, V>
982                          if (sib == null)
983                              x = xp;
984                          else {
985 <                            TreeNode sl = sib.left, sr = sib.right;
985 >                            TreeNode<V> sl = sib.left, sr = sib.right;
986                              if ((sr == null || !sr.red) &&
987                                  (sl == null || !sl.red)) {
988                                  sib.red = true;
# Line 1103 | Line 994 | public class ConcurrentHashMap<K, V>
994                                          sl.red = false;
995                                      sib.red = true;
996                                      rotateRight(sib);
997 <                                    sib = (xp = x.parent) == null ? null : xp.right;
997 >                                    sib = (xp = x.parent) == null ?
998 >                                        null : xp.right;
999                                  }
1000                                  if (sib != null) {
1001                                      sib.red = (xp == null) ? false : xp.red;
# Line 1119 | Line 1011 | public class ConcurrentHashMap<K, V>
1011                          }
1012                      }
1013                      else { // symmetric
1014 <                        TreeNode sib = xpl;
1014 >                        TreeNode<V> sib = xpl;
1015                          if (sib != null && sib.red) {
1016                              sib.red = false;
1017                              xp.red = true;
# Line 1129 | Line 1021 | public class ConcurrentHashMap<K, V>
1021                          if (sib == null)
1022                              x = xp;
1023                          else {
1024 <                            TreeNode sl = sib.left, sr = sib.right;
1024 >                            TreeNode<V> sl = sib.left, sr = sib.right;
1025                              if ((sl == null || !sl.red) &&
1026                                  (sr == null || !sr.red)) {
1027                                  sib.red = true;
# Line 1141 | Line 1033 | public class ConcurrentHashMap<K, V>
1033                                          sr.red = false;
1034                                      sib.red = true;
1035                                      rotateLeft(sib);
1036 <                                    sib = (xp = x.parent) == null ? null : xp.left;
1036 >                                    sib = (xp = x.parent) == null ?
1037 >                                        null : xp.left;
1038                                  }
1039                                  if (sib != null) {
1040                                      sib.red = (xp == null) ? false : xp.red;
# Line 1171 | Line 1064 | public class ConcurrentHashMap<K, V>
1064      /* ---------------- Collision reduction methods -------------- */
1065  
1066      /**
1067 <     * Spreads higher bits to lower, and also forces top 2 bits to 0.
1067 >     * Spreads higher bits to lower, and also forces top bit to 0.
1068       * Because the table uses power-of-two masking, sets of hashes
1069       * that vary only in bits above the current mask will always
1070       * collide. (Among known examples are sets of Float keys holding
# Line 1189 | Line 1082 | public class ConcurrentHashMap<K, V>
1082      }
1083  
1084      /**
1085 <     * Replaces a list bin with a tree bin. Call only when locked.
1086 <     * Fails to replace if the given key is non-comparable or table
1087 <     * is, or needs, resizing.
1088 <     */
1089 <    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1090 <        if ((key instanceof Comparable) &&
1091 <            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
1092 <            TreeBin t = new TreeBin();
1093 <            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));
1085 >     * Replaces a list bin with a tree bin if key is comparable.  Call
1086 >     * only when locked.
1087 >     */
1088 >    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1089 >        if (key instanceof Comparable) {
1090 >            TreeBin<V> t = new TreeBin<V>();
1091 >            for (Node<V> e = tabAt(tab, index); e != null; e = e.next)
1092 >                t.putTreeNode(e.hash, e.key, e.val);
1093 >            setTabAt(tab, index, new Node<V>(MOVED, t, null, null));
1094          }
1095      }
1096  
1097      /* ---------------- Internal access and update methods -------------- */
1098  
1099      /** Implementation for get and containsKey */
1100 <    private final Object internalGet(Object k) {
1100 >    @SuppressWarnings("unchecked") private final V internalGet(Object k) {
1101          int h = spread(k.hashCode());
1102 <        retry: for (Node[] tab = table; tab != null;) {
1103 <            Node e, p; Object ek, ev; int eh;      // locals to read fields once
1102 >        retry: for (Node<V>[] tab = table; tab != null;) {
1103 >            Node<V> e; Object ek; V ev; int eh; // locals to read fields once
1104              for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1105 <                if ((eh = e.hash) == MOVED) {
1105 >                if ((eh = e.hash) < 0) {
1106                      if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1107 <                        return ((TreeBin)ek).getValue(h, k);
1108 <                    else {                        // restart with new table
1109 <                        tab = (Node[])ek;
1107 >                        return ((TreeBin<V>)ek).getValue(h, k);
1108 >                    else {                      // restart with new table
1109 >                        tab = (Node<V>[])ek;
1110                          continue retry;
1111                      }
1112                  }
1113 <                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1113 >                else if (eh == h && (ev = e.val) != null &&
1114                           ((ek = e.key) == k || k.equals(ek)))
1115                      return ev;
1116              }
# Line 1233 | Line 1124 | public class ConcurrentHashMap<K, V>
1124       * Replaces node value with v, conditional upon match of cv if
1125       * non-null.  If resulting value is null, delete.
1126       */
1127 <    private final Object internalReplace(Object k, Object v, Object cv) {
1127 >    @SuppressWarnings("unchecked") private final V internalReplace
1128 >        (Object k, V v, Object cv) {
1129          int h = spread(k.hashCode());
1130 <        Object oldVal = null;
1131 <        for (Node[] tab = table;;) {
1132 <            Node f; int i, fh; Object fk;
1130 >        V oldVal = null;
1131 >        for (Node<V>[] tab = table;;) {
1132 >            Node<V> f; int i, fh; Object fk;
1133              if (tab == null ||
1134                  (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1135                  break;
1136 <            else if ((fh = f.hash) == MOVED) {
1136 >            else if ((fh = f.hash) < 0) {
1137                  if ((fk = f.key) instanceof TreeBin) {
1138 <                    TreeBin t = (TreeBin)fk;
1138 >                    TreeBin<V> t = (TreeBin<V>)fk;
1139                      boolean validated = false;
1140                      boolean deleted = false;
1141                      t.acquire(0);
1142                      try {
1143                          if (tabAt(tab, i) == f) {
1144                              validated = true;
1145 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1145 >                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1146                              if (p != null) {
1147 <                                Object pv = p.val;
1147 >                                V pv = p.val;
1148                                  if (cv == null || cv == pv || cv.equals(pv)) {
1149                                      oldVal = pv;
1150                                      if ((p.val = v) == null) {
# Line 1267 | Line 1159 | public class ConcurrentHashMap<K, V>
1159                      }
1160                      if (validated) {
1161                          if (deleted)
1162 <                            counter.add(-1L);
1162 >                            addCount(-1L, -1);
1163                          break;
1164                      }
1165                  }
1166                  else
1167 <                    tab = (Node[])fk;
1167 >                    tab = (Node<V>[])fk;
1168              }
1169 <            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
1169 >            else if (fh != h && f.next == null) // precheck
1170                  break;                          // rules out possible existence
1171 <            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)) {
1171 >            else {
1172                  boolean validated = false;
1173                  boolean deleted = false;
1174 <                try {
1174 >                synchronized (f) {
1175                      if (tabAt(tab, i) == f) {
1176                          validated = true;
1177 <                        for (Node e = f, pred = null;;) {
1178 <                            Object ek, ev;
1179 <                            if ((e.hash & HASH_BITS) == h &&
1177 >                        for (Node<V> e = f, pred = null;;) {
1178 >                            Object ek; V ev;
1179 >                            if (e.hash == h &&
1180                                  ((ev = e.val) != null) &&
1181                                  ((ek = e.key) == k || k.equals(ek))) {
1182                                  if (cv == null || cv == ev || cv.equals(ev)) {
1183                                      oldVal = ev;
1184                                      if ((e.val = v) == null) {
1185                                          deleted = true;
1186 <                                        Node en = e.next;
1186 >                                        Node<V> en = e.next;
1187                                          if (pred != null)
1188                                              pred.next = en;
1189                                          else
# Line 1309 | Line 1197 | public class ConcurrentHashMap<K, V>
1197                                  break;
1198                          }
1199                      }
1312                } finally {
1313                    if (!f.casHash(fh | LOCKED, fh)) {
1314                        f.hash = fh;
1315                        synchronized (f) { f.notifyAll(); };
1316                    }
1200                  }
1201                  if (validated) {
1202                      if (deleted)
1203 <                        counter.add(-1L);
1203 >                        addCount(-1L, -1);
1204                      break;
1205                  }
1206              }
# Line 1326 | Line 1209 | public class ConcurrentHashMap<K, V>
1209      }
1210  
1211      /*
1212 <     * Internal versions of the six insertion methods, each a
1213 <     * little more complicated than the last. All have
1331 <     * the same basic structure as the first (internalPut):
1212 >     * Internal versions of insertion methods
1213 >     * All have the same basic structure as the first (internalPut):
1214       *  1. If table uninitialized, create
1215       *  2. If bin empty, try to CAS new node
1216       *  3. If bin stale, use new table
1217       *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1218       *  5. Lock and validate; if valid, scan and add or update
1219       *
1220 <     * The others interweave other checks and/or alternative actions:
1221 <     *  * Plain put checks for and performs resize after insertion.
1222 <     *  * putIfAbsent prescans for mapping without lock (and fails to add
1223 <     *    if present), which also makes pre-emptive resize checks worthwhile.
1224 <     *  * computeIfAbsent extends form used in putIfAbsent with additional
1225 <     *    mechanics to deal with, calls, potential exceptions and null
1226 <     *    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.
1220 >     * The putAll method differs mainly in attempting to pre-allocate
1221 >     * enough table space, and also more lazily performs count updates
1222 >     * and checks.
1223 >     *
1224 >     * Most of the function-accepting methods can't be factored nicely
1225 >     * because they require different functional forms, so instead
1226 >     * sprawl out similar mechanics.
1227       */
1228  
1229 <    /** Implementation for put */
1230 <    private final Object internalPut(Object k, Object v) {
1229 >    /** Implementation for put and putIfAbsent */
1230 >    @SuppressWarnings("unchecked") private final V internalPut
1231 >        (K k, V v, boolean onlyIfAbsent) {
1232 >        if (k == null || v == null) throw new NullPointerException();
1233          int h = spread(k.hashCode());
1234 <        int count = 0;
1235 <        for (Node[] tab = table;;) {
1236 <            int i; Node f; int fh; Object fk;
1234 >        int len = 0;
1235 >        for (Node<V>[] tab = table;;) {
1236 >            int i, fh; Node<V> f; Object fk; V fv;
1237              if (tab == null)
1238                  tab = initTable();
1239              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1240 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1240 >                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1241                      break;                   // no lock when adding to empty bin
1242              }
1243 <            else if ((fh = f.hash) == MOVED) {
1243 >            else if ((fh = f.hash) < 0) {
1244                  if ((fk = f.key) instanceof TreeBin) {
1245 <                    TreeBin t = (TreeBin)fk;
1246 <                    Object oldVal = null;
1245 >                    TreeBin<V> t = (TreeBin<V>)fk;
1246 >                    V oldVal = null;
1247                      t.acquire(0);
1248                      try {
1249                          if (tabAt(tab, i) == f) {
1250 <                            count = 2;
1251 <                            TreeNode p = t.putTreeNode(h, k, v);
1250 >                            len = 2;
1251 >                            TreeNode<V> p = t.putTreeNode(h, k, v);
1252                              if (p != null) {
1253                                  oldVal = p.val;
1254 <                                p.val = v;
1254 >                                if (!onlyIfAbsent)
1255 >                                    p.val = v;
1256                              }
1257                          }
1258                      } finally {
1259                          t.release(0);
1260                      }
1261 <                    if (count != 0) {
1261 >                    if (len != 0) {
1262                          if (oldVal != null)
1263                              return oldVal;
1264                          break;
1265                      }
1266                  }
1267                  else
1268 <                    tab = (Node[])fk;
1268 >                    tab = (Node<V>[])fk;
1269              }
1270 <            else if ((fh & LOCKED) != 0) {
1271 <                checkForResize();
1272 <                f.tryAwaitLock(tab, i);
1273 <            }
1274 <            else if (f.casHash(fh, fh | LOCKED)) {
1275 <                Object oldVal = null;
1400 <                try {                        // needed in case equals() throws
1270 >            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1271 >                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1272 >                return fv;
1273 >            else {
1274 >                V oldVal = null;
1275 >                synchronized (f) {
1276                      if (tabAt(tab, i) == f) {
1277 <                        count = 1;
1278 <                        for (Node e = f;; ++count) {
1279 <                            Object ek, ev;
1280 <                            if ((e.hash & HASH_BITS) == h &&
1277 >                        len = 1;
1278 >                        for (Node<V> e = f;; ++len) {
1279 >                            Object ek; V ev;
1280 >                            if (e.hash == h &&
1281                                  (ev = e.val) != null &&
1282                                  ((ek = e.key) == k || k.equals(ek))) {
1283                                  oldVal = ev;
1284 <                                e.val = v;
1284 >                                if (!onlyIfAbsent)
1285 >                                    e.val = v;
1286                                  break;
1287                              }
1288 <                            Node last = e;
1288 >                            Node<V> last = e;
1289                              if ((e = e.next) == null) {
1290 <                                last.next = new Node(h, k, v, null);
1291 <                                if (count >= TREE_THRESHOLD)
1290 >                                last.next = new Node<V>(h, k, v, null);
1291 >                                if (len >= TREE_THRESHOLD)
1292                                      replaceWithTreeBin(tab, i, k);
1293                                  break;
1294                              }
1295                          }
1296                      }
1421                } finally {                  // unlock and signal if needed
1422                    if (!f.casHash(fh | LOCKED, fh)) {
1423                        f.hash = fh;
1424                        synchronized (f) { f.notifyAll(); };
1425                    }
1297                  }
1298 <                if (count != 0) {
1298 >                if (len != 0) {
1299                      if (oldVal != null)
1300                          return oldVal;
1430                    if (tab.length <= 64)
1431                        count = 2;
1301                      break;
1302                  }
1303              }
1304          }
1305 <        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();
1305 >        addCount(1L, len);
1306          return null;
1307      }
1308  
1309      /** Implementation for computeIfAbsent */
1310 <    private final Object internalComputeIfAbsent(K k,
1311 <                                                 Fun<? super K, ?> mf) {
1310 >    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1311 >        (K k, Function<? super K, ? extends V> mf) {
1312 >        if (k == null || mf == null)
1313 >            throw new NullPointerException();
1314          int h = spread(k.hashCode());
1315 <        Object val = null;
1316 <        int count = 0;
1317 <        for (Node[] tab = table;;) {
1318 <            Node f; int i, fh; Object fk, fv;
1315 >        V val = null;
1316 >        int len = 0;
1317 >        for (Node<V>[] tab = table;;) {
1318 >            Node<V> f; int i; Object fk;
1319              if (tab == null)
1320                  tab = initTable();
1321              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1322 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1323 <                if (casTabAt(tab, i, null, node)) {
1324 <                    count = 1;
1325 <                    try {
1326 <                        if ((val = mf.apply(k)) != null)
1327 <                            node.val = val;
1328 <                    } finally {
1329 <                        if (val == null)
1330 <                            setTabAt(tab, i, null);
1331 <                        if (!node.casHash(fh, h)) {
1564 <                            node.hash = h;
1565 <                            synchronized (node) { node.notifyAll(); };
1322 >                Node<V> node = new Node<V>(h, k, null, null);
1323 >                synchronized (node) {
1324 >                    if (casTabAt(tab, i, null, node)) {
1325 >                        len = 1;
1326 >                        try {
1327 >                            if ((val = mf.apply(k)) != null)
1328 >                                node.val = val;
1329 >                        } finally {
1330 >                            if (val == null)
1331 >                                setTabAt(tab, i, null);
1332                          }
1333                      }
1334                  }
1335 <                if (count != 0)
1335 >                if (len != 0)
1336                      break;
1337              }
1338 <            else if ((fh = f.hash) == MOVED) {
1338 >            else if (f.hash < 0) {
1339                  if ((fk = f.key) instanceof TreeBin) {
1340 <                    TreeBin t = (TreeBin)fk;
1340 >                    TreeBin<V> t = (TreeBin<V>)fk;
1341                      boolean added = false;
1342                      t.acquire(0);
1343                      try {
1344                          if (tabAt(tab, i) == f) {
1345 <                            count = 1;
1346 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1345 >                            len = 1;
1346 >                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1347                              if (p != null)
1348                                  val = p.val;
1349                              else if ((val = mf.apply(k)) != null) {
1350                                  added = true;
1351 <                                count = 2;
1351 >                                len = 2;
1352                                  t.putTreeNode(h, k, val);
1353                              }
1354                          }
1355                      } finally {
1356                          t.release(0);
1357                      }
1358 <                    if (count != 0) {
1358 >                    if (len != 0) {
1359                          if (!added)
1360                              return val;
1361                          break;
1362                      }
1363                  }
1364                  else
1365 <                    tab = (Node[])fk;
1365 >                    tab = (Node<V>[])fk;
1366              }
1601            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1602                     ((fk = f.key) == k || k.equals(fk)))
1603                return fv;
1367              else {
1368 <                Node g = f.next;
1369 <                if (g != null) {
1370 <                    for (Node e = g;;) {
1371 <                        Object ek, ev;
1372 <                        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);
1368 >                for (Node<V> e = f; e != null; e = e.next) { // prescan
1369 >                    Object ek; V ev;
1370 >                    if (e.hash == h && (ev = e.val) != null &&
1371 >                        ((ek = e.key) == k || k.equals(ek)))
1372 >                        return ev;
1373                  }
1374 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1375 <                    boolean added = false;
1376 <                    try {
1377 <                        if (tabAt(tab, i) == f) {
1378 <                            count = 1;
1379 <                            for (Node e = f;; ++count) {
1380 <                                Object ek, ev;
1381 <                                if ((e.hash & HASH_BITS) == h &&
1382 <                                    (ev = e.val) != null &&
1383 <                                    ((ek = e.key) == k || k.equals(ek))) {
1384 <                                    val = ev;
1385 <                                    break;
1386 <                                }
1387 <                                Node last = e;
1388 <                                if ((e = e.next) == null) {
1389 <                                    if ((val = mf.apply(k)) != null) {
1390 <                                        added = true;
1391 <                                        last.next = new Node(h, k, val, null);
1392 <                                        if (count >= TREE_THRESHOLD)
1641 <                                            replaceWithTreeBin(tab, i, k);
1642 <                                    }
1643 <                                    break;
1374 >                boolean added = false;
1375 >                synchronized (f) {
1376 >                    if (tabAt(tab, i) == f) {
1377 >                        len = 1;
1378 >                        for (Node<V> e = f;; ++len) {
1379 >                            Object ek; V ev;
1380 >                            if (e.hash == h &&
1381 >                                (ev = e.val) != null &&
1382 >                                ((ek = e.key) == k || k.equals(ek))) {
1383 >                                val = ev;
1384 >                                break;
1385 >                            }
1386 >                            Node<V> last = e;
1387 >                            if ((e = e.next) == null) {
1388 >                                if ((val = mf.apply(k)) != null) {
1389 >                                    added = true;
1390 >                                    last.next = new Node<V>(h, k, val, null);
1391 >                                    if (len >= TREE_THRESHOLD)
1392 >                                        replaceWithTreeBin(tab, i, k);
1393                                  }
1394 +                                break;
1395                              }
1396                          }
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;
1397                      }
1398                  }
1399 +                if (len != 0) {
1400 +                    if (!added)
1401 +                        return val;
1402 +                    break;
1403 +                }
1404              }
1405          }
1406 <        if (val != null) {
1407 <            counter.add(1L);
1665 <            if (count > 1)
1666 <                checkForResize();
1667 <        }
1406 >        if (val != null)
1407 >            addCount(1L, len);
1408          return val;
1409      }
1410  
1411      /** Implementation for compute */
1412 <    @SuppressWarnings("unchecked") private final Object internalCompute
1413 <        (K k, boolean onlyIfPresent, BiFun<? super K, ? super V, ? extends V> mf) {
1412 >    @SuppressWarnings("unchecked") private final V internalCompute
1413 >        (K k, boolean onlyIfPresent,
1414 >         BiFunction<? super K, ? super V, ? extends V> mf) {
1415 >        if (k == null || mf == null)
1416 >            throw new NullPointerException();
1417          int h = spread(k.hashCode());
1418 <        Object val = null;
1418 >        V val = null;
1419          int delta = 0;
1420 <        int count = 0;
1421 <        for (Node[] tab = table;;) {
1422 <            Node f; int i, fh; Object fk;
1420 >        int len = 0;
1421 >        for (Node<V>[] tab = table;;) {
1422 >            Node<V> f; int i, fh; Object fk;
1423              if (tab == null)
1424                  tab = initTable();
1425              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1426                  if (onlyIfPresent)
1427                      break;
1428 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1429 <                if (casTabAt(tab, i, null, node)) {
1430 <                    try {
1431 <                        count = 1;
1432 <                        if ((val = mf.apply(k, null)) != null) {
1433 <                            node.val = val;
1434 <                            delta = 1;
1435 <                        }
1436 <                    } finally {
1437 <                        if (delta == 0)
1438 <                            setTabAt(tab, i, null);
1439 <                        if (!node.casHash(fh, h)) {
1697 <                            node.hash = h;
1698 <                            synchronized (node) { node.notifyAll(); };
1428 >                Node<V> node = new Node<V>(h, k, null, null);
1429 >                synchronized (node) {
1430 >                    if (casTabAt(tab, i, null, node)) {
1431 >                        try {
1432 >                            len = 1;
1433 >                            if ((val = mf.apply(k, null)) != null) {
1434 >                                node.val = val;
1435 >                                delta = 1;
1436 >                            }
1437 >                        } finally {
1438 >                            if (delta == 0)
1439 >                                setTabAt(tab, i, null);
1440                          }
1441                      }
1442                  }
1443 <                if (count != 0)
1443 >                if (len != 0)
1444                      break;
1445              }
1446 <            else if ((fh = f.hash) == MOVED) {
1446 >            else if ((fh = f.hash) < 0) {
1447                  if ((fk = f.key) instanceof TreeBin) {
1448 <                    TreeBin t = (TreeBin)fk;
1448 >                    TreeBin<V> t = (TreeBin<V>)fk;
1449                      t.acquire(0);
1450                      try {
1451                          if (tabAt(tab, i) == f) {
1452 <                            count = 1;
1453 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1454 <                            Object pv = (p == null) ? null : p.val;
1455 <                            if ((val = mf.apply(k, (V)pv)) != null) {
1452 >                            len = 1;
1453 >                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1454 >                            if (p == null && onlyIfPresent)
1455 >                                break;
1456 >                            V pv = (p == null) ? null : p.val;
1457 >                            if ((val = mf.apply(k, pv)) != null) {
1458                                  if (p != null)
1459                                      p.val = val;
1460                                  else {
1461 <                                    count = 2;
1461 >                                    len = 2;
1462                                      delta = 1;
1463                                      t.putTreeNode(h, k, val);
1464                                  }
# Line 1728 | Line 1471 | public class ConcurrentHashMap<K, V>
1471                      } finally {
1472                          t.release(0);
1473                      }
1474 <                    if (count != 0)
1474 >                    if (len != 0)
1475                          break;
1476                  }
1477                  else
1478 <                    tab = (Node[])fk;
1736 <            }
1737 <            else if ((fh & LOCKED) != 0) {
1738 <                checkForResize();
1739 <                f.tryAwaitLock(tab, i);
1478 >                    tab = (Node<V>[])fk;
1479              }
1480 <            else if (f.casHash(fh, fh | LOCKED)) {
1481 <                try {
1480 >            else {
1481 >                synchronized (f) {
1482                      if (tabAt(tab, i) == f) {
1483 <                        count = 1;
1484 <                        for (Node e = f, pred = null;; ++count) {
1485 <                            Object ek, ev;
1486 <                            if ((e.hash & HASH_BITS) == h &&
1483 >                        len = 1;
1484 >                        for (Node<V> e = f, pred = null;; ++len) {
1485 >                            Object ek; V ev;
1486 >                            if (e.hash == h &&
1487                                  (ev = e.val) != null &&
1488                                  ((ek = e.key) == k || k.equals(ek))) {
1489 <                                val = mf.apply(k, (V)ev);
1489 >                                val = mf.apply(k, ev);
1490                                  if (val != null)
1491                                      e.val = val;
1492                                  else {
1493                                      delta = -1;
1494 <                                    Node en = e.next;
1494 >                                    Node<V> en = e.next;
1495                                      if (pred != null)
1496                                          pred.next = en;
1497                                      else
# Line 1762 | Line 1501 | public class ConcurrentHashMap<K, V>
1501                              }
1502                              pred = e;
1503                              if ((e = e.next) == null) {
1504 <                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1505 <                                    pred.next = new Node(h, k, val, null);
1504 >                                if (!onlyIfPresent &&
1505 >                                    (val = mf.apply(k, null)) != null) {
1506 >                                    pred.next = new Node<V>(h, k, val, null);
1507                                      delta = 1;
1508 <                                    if (count >= TREE_THRESHOLD)
1508 >                                    if (len >= TREE_THRESHOLD)
1509                                          replaceWithTreeBin(tab, i, k);
1510                                  }
1511                                  break;
1512                              }
1513                          }
1514                      }
1775                } finally {
1776                    if (!f.casHash(fh | LOCKED, fh)) {
1777                        f.hash = fh;
1778                        synchronized (f) { f.notifyAll(); };
1779                    }
1515                  }
1516 <                if (count != 0) {
1782 <                    if (tab.length <= 64)
1783 <                        count = 2;
1516 >                if (len != 0)
1517                      break;
1785                }
1518              }
1519          }
1520 <        if (delta != 0) {
1521 <            counter.add((long)delta);
1790 <            if (count > 1)
1791 <                checkForResize();
1792 <        }
1520 >        if (delta != 0)
1521 >            addCount((long)delta, len);
1522          return val;
1523      }
1524  
1525      /** Implementation for merge */
1526 <    @SuppressWarnings("unchecked") private final Object internalMerge
1527 <        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1526 >    @SuppressWarnings("unchecked") private final V internalMerge
1527 >        (K k, V v, BiFunction<? super V, ? super V, ? extends V> mf) {
1528 >        if (k == null || v == null || mf == null)
1529 >            throw new NullPointerException();
1530          int h = spread(k.hashCode());
1531 <        Object val = null;
1531 >        V val = null;
1532          int delta = 0;
1533 <        int count = 0;
1534 <        for (Node[] tab = table;;) {
1535 <            int i; Node f; int fh; Object fk, fv;
1533 >        int len = 0;
1534 >        for (Node<V>[] tab = table;;) {
1535 >            int i; Node<V> f; Object fk; V fv;
1536              if (tab == null)
1537                  tab = initTable();
1538              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1539 <                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1539 >                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
1540                      delta = 1;
1541                      val = v;
1542                      break;
1543                  }
1544              }
1545 <            else if ((fh = f.hash) == MOVED) {
1545 >            else if (f.hash < 0) {
1546                  if ((fk = f.key) instanceof TreeBin) {
1547 <                    TreeBin t = (TreeBin)fk;
1547 >                    TreeBin<V> t = (TreeBin<V>)fk;
1548                      t.acquire(0);
1549                      try {
1550                          if (tabAt(tab, i) == f) {
1551 <                            count = 1;
1552 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1553 <                            val = (p == null) ? v : mf.apply((V)p.val, v);
1551 >                            len = 1;
1552 >                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1553 >                            val = (p == null) ? v : mf.apply(p.val, v);
1554                              if (val != null) {
1555                                  if (p != null)
1556                                      p.val = val;
1557                                  else {
1558 <                                    count = 2;
1558 >                                    len = 2;
1559                                      delta = 1;
1560                                      t.putTreeNode(h, k, val);
1561                                  }
# Line 1837 | Line 1568 | public class ConcurrentHashMap<K, V>
1568                      } finally {
1569                          t.release(0);
1570                      }
1571 <                    if (count != 0)
1571 >                    if (len != 0)
1572                          break;
1573                  }
1574                  else
1575 <                    tab = (Node[])fk;
1845 <            }
1846 <            else if ((fh & LOCKED) != 0) {
1847 <                checkForResize();
1848 <                f.tryAwaitLock(tab, i);
1575 >                    tab = (Node<V>[])fk;
1576              }
1577 <            else if (f.casHash(fh, fh | LOCKED)) {
1578 <                try {
1577 >            else {
1578 >                synchronized (f) {
1579                      if (tabAt(tab, i) == f) {
1580 <                        count = 1;
1581 <                        for (Node e = f, pred = null;; ++count) {
1582 <                            Object ek, ev;
1583 <                            if ((e.hash & HASH_BITS) == h &&
1580 >                        len = 1;
1581 >                        for (Node<V> e = f, pred = null;; ++len) {
1582 >                            Object ek; V ev;
1583 >                            if (e.hash == h &&
1584                                  (ev = e.val) != null &&
1585                                  ((ek = e.key) == k || k.equals(ek))) {
1586 <                                val = mf.apply(v, (V)ev);
1586 >                                val = mf.apply(ev, v);
1587                                  if (val != null)
1588                                      e.val = val;
1589                                  else {
1590                                      delta = -1;
1591 <                                    Node en = e.next;
1591 >                                    Node<V> en = e.next;
1592                                      if (pred != null)
1593                                          pred.next = en;
1594                                      else
# Line 1872 | Line 1599 | public class ConcurrentHashMap<K, V>
1599                              pred = e;
1600                              if ((e = e.next) == null) {
1601                                  val = v;
1602 <                                pred.next = new Node(h, k, val, null);
1602 >                                pred.next = new Node<V>(h, k, val, null);
1603                                  delta = 1;
1604 <                                if (count >= TREE_THRESHOLD)
1604 >                                if (len >= TREE_THRESHOLD)
1605                                      replaceWithTreeBin(tab, i, k);
1606                                  break;
1607                              }
1608                          }
1609                      }
1883                } finally {
1884                    if (!f.casHash(fh | LOCKED, fh)) {
1885                        f.hash = fh;
1886                        synchronized (f) { f.notifyAll(); };
1887                    }
1610                  }
1611 <                if (count != 0) {
1890 <                    if (tab.length <= 64)
1891 <                        count = 2;
1611 >                if (len != 0)
1612                      break;
1893                }
1613              }
1614          }
1615 <        if (delta != 0) {
1616 <            counter.add((long)delta);
1898 <            if (count > 1)
1899 <                checkForResize();
1900 <        }
1615 >        if (delta != 0)
1616 >            addCount((long)delta, len);
1617          return val;
1618      }
1619  
1620      /** Implementation for putAll */
1621 <    private final void internalPutAll(Map<?, ?> m) {
1621 >    @SuppressWarnings("unchecked") private final void internalPutAll
1622 >        (Map<? extends K, ? extends V> m) {
1623          tryPresize(m.size());
1624          long delta = 0L;     // number of uncommitted additions
1625          boolean npe = false; // to throw exception on exit for nulls
1626          try {                // to clean up counts on other exceptions
1627 <            for (Map.Entry<?, ?> entry : m.entrySet()) {
1628 <                Object k, v;
1627 >            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
1628 >                Object k; V v;
1629                  if (entry == null || (k = entry.getKey()) == null ||
1630                      (v = entry.getValue()) == null) {
1631                      npe = true;
1632                      break;
1633                  }
1634                  int h = spread(k.hashCode());
1635 <                for (Node[] tab = table;;) {
1636 <                    int i; Node f; int fh; Object fk;
1635 >                for (Node<V>[] tab = table;;) {
1636 >                    int i; Node<V> f; int fh; Object fk;
1637                      if (tab == null)
1638                          tab = initTable();
1639                      else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1640 <                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1640 >                        if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
1641                              ++delta;
1642                              break;
1643                          }
1644                      }
1645 <                    else if ((fh = f.hash) == MOVED) {
1645 >                    else if ((fh = f.hash) < 0) {
1646                          if ((fk = f.key) instanceof TreeBin) {
1647 <                            TreeBin t = (TreeBin)fk;
1647 >                            TreeBin<V> t = (TreeBin<V>)fk;
1648                              boolean validated = false;
1649                              t.acquire(0);
1650                              try {
1651                                  if (tabAt(tab, i) == f) {
1652                                      validated = true;
1653 <                                    TreeNode p = t.getTreeNode(h, k, t.root);
1653 >                                    TreeNode<V> p = t.getTreeNode(h, k, t.root);
1654                                      if (p != null)
1655                                          p.val = v;
1656                                      else {
# Line 1948 | Line 1665 | public class ConcurrentHashMap<K, V>
1665                                  break;
1666                          }
1667                          else
1668 <                            tab = (Node[])fk;
1952 <                    }
1953 <                    else if ((fh & LOCKED) != 0) {
1954 <                        counter.add(delta);
1955 <                        delta = 0L;
1956 <                        checkForResize();
1957 <                        f.tryAwaitLock(tab, i);
1668 >                            tab = (Node<V>[])fk;
1669                      }
1670 <                    else if (f.casHash(fh, fh | LOCKED)) {
1671 <                        int count = 0;
1672 <                        try {
1670 >                    else {
1671 >                        int len = 0;
1672 >                        synchronized (f) {
1673                              if (tabAt(tab, i) == f) {
1674 <                                count = 1;
1675 <                                for (Node e = f;; ++count) {
1676 <                                    Object ek, ev;
1677 <                                    if ((e.hash & HASH_BITS) == h &&
1674 >                                len = 1;
1675 >                                for (Node<V> e = f;; ++len) {
1676 >                                    Object ek; V ev;
1677 >                                    if (e.hash == h &&
1678                                          (ev = e.val) != null &&
1679                                          ((ek = e.key) == k || k.equals(ek))) {
1680                                          e.val = v;
1681                                          break;
1682                                      }
1683 <                                    Node last = e;
1683 >                                    Node<V> last = e;
1684                                      if ((e = e.next) == null) {
1685                                          ++delta;
1686 <                                        last.next = new Node(h, k, v, null);
1687 <                                        if (count >= TREE_THRESHOLD)
1686 >                                        last.next = new Node<V>(h, k, v, null);
1687 >                                        if (len >= TREE_THRESHOLD)
1688                                              replaceWithTreeBin(tab, i, k);
1689                                          break;
1690                                      }
1691                                  }
1692                              }
1982                        } finally {
1983                            if (!f.casHash(fh | LOCKED, fh)) {
1984                                f.hash = fh;
1985                                synchronized (f) { f.notifyAll(); };
1986                            }
1693                          }
1694 <                        if (count != 0) {
1695 <                            if (count > 1) {
1696 <                                counter.add(delta);
1694 >                        if (len != 0) {
1695 >                            if (len > 1) {
1696 >                                addCount(delta, len);
1697                                  delta = 0L;
1992                                checkForResize();
1698                              }
1699                              break;
1700                          }
# Line 1997 | Line 1702 | public class ConcurrentHashMap<K, V>
1702                  }
1703              }
1704          } finally {
1705 <            if (delta != 0)
1706 <                counter.add(delta);
1705 >            if (delta != 0L)
1706 >                addCount(delta, 2);
1707          }
1708          if (npe)
1709              throw new NullPointerException();
1710      }
1711  
1712 +    /**
1713 +     * Implementation for clear. Steps through each bin, removing all
1714 +     * nodes.
1715 +     */
1716 +    @SuppressWarnings("unchecked") private final void internalClear() {
1717 +        long delta = 0L; // negative number of deletions
1718 +        int i = 0;
1719 +        Node<V>[] tab = table;
1720 +        while (tab != null && i < tab.length) {
1721 +            Node<V> f = tabAt(tab, i);
1722 +            if (f == null)
1723 +                ++i;
1724 +            else if (f.hash < 0) {
1725 +                Object fk;
1726 +                if ((fk = f.key) instanceof TreeBin) {
1727 +                    TreeBin<V> t = (TreeBin<V>)fk;
1728 +                    t.acquire(0);
1729 +                    try {
1730 +                        if (tabAt(tab, i) == f) {
1731 +                            for (Node<V> p = t.first; p != null; p = p.next) {
1732 +                                if (p.val != null) { // (currently always true)
1733 +                                    p.val = null;
1734 +                                    --delta;
1735 +                                }
1736 +                            }
1737 +                            t.first = null;
1738 +                            t.root = null;
1739 +                            ++i;
1740 +                        }
1741 +                    } finally {
1742 +                        t.release(0);
1743 +                    }
1744 +                }
1745 +                else
1746 +                    tab = (Node<V>[])fk;
1747 +            }
1748 +            else {
1749 +                synchronized (f) {
1750 +                    if (tabAt(tab, i) == f) {
1751 +                        for (Node<V> e = f; e != null; e = e.next) {
1752 +                            if (e.val != null) {  // (currently always true)
1753 +                                e.val = null;
1754 +                                --delta;
1755 +                            }
1756 +                        }
1757 +                        setTabAt(tab, i, null);
1758 +                        ++i;
1759 +                    }
1760 +                }
1761 +            }
1762 +        }
1763 +        if (delta != 0L)
1764 +            addCount(delta, -1);
1765 +    }
1766 +
1767      /* ---------------- Table Initialization and Resizing -------------- */
1768  
1769      /**
# Line 2023 | Line 1783 | public class ConcurrentHashMap<K, V>
1783      /**
1784       * Initializes table, using the size recorded in sizeCtl.
1785       */
1786 <    private final Node[] initTable() {
1787 <        Node[] tab; int sc;
1786 >    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
1787 >        Node<V>[] tab; int sc;
1788          while ((tab = table) == null) {
1789              if ((sc = sizeCtl) < 0)
1790                  Thread.yield(); // lost initialization race; just spin
1791 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1791 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1792                  try {
1793                      if ((tab = table) == null) {
1794                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1795 <                        tab = table = new Node[n];
1795 >                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
1796 >                        table = tab = (Node<V>[])tb;
1797                          sc = n - (n >>> 2);
1798                      }
1799                  } finally {
# Line 2045 | Line 1806 | public class ConcurrentHashMap<K, V>
1806      }
1807  
1808      /**
1809 <     * If table is too small and not already resizing, creates next
1810 <     * table and transfers bins.  Rechecks occupancy after a transfer
1811 <     * to see if another resize is already needed because resizings
1812 <     * are lagging additions.
1813 <     */
1814 <    private final void checkForResize() {
1815 <        Node[] tab; int n, sc;
1816 <        while ((tab = table) != null &&
1817 <               (n = tab.length) < MAXIMUM_CAPACITY &&
1818 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1819 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1820 <            try {
1821 <                if (tab == table) {
1822 <                    table = rebuild(tab);
1823 <                    sc = (n << 1) - (n >>> 1);
1809 >     * Adds to count, and if table is too small and not already
1810 >     * resizing, initiates transfer. If already resizing, helps
1811 >     * perform transfer if work is available.  Rechecks occupancy
1812 >     * after a transfer to see if another resize is already needed
1813 >     * because resizings are lagging additions.
1814 >     *
1815 >     * @param x the count to add
1816 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
1817 >     */
1818 >    private final void addCount(long x, int check) {
1819 >        Cell[] as; long b, s;
1820 >        if ((as = counterCells) != null ||
1821 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
1822 >            Cell a; long v; int m;
1823 >            boolean uncontended = true;
1824 >            if (as == null || (m = as.length - 1) < 0 ||
1825 >                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
1826 >                !(uncontended =
1827 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
1828 >                fullAddCount(x, uncontended);
1829 >                return;
1830 >            }
1831 >            if (check <= 1)
1832 >                return;
1833 >            s = sumCount();
1834 >        }
1835 >        if (check >= 0) {
1836 >            Node<V>[] tab, nt; int sc;
1837 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
1838 >                   tab.length < MAXIMUM_CAPACITY) {
1839 >                if (sc < 0) {
1840 >                    if (sc == -1 || transferIndex <= transferOrigin ||
1841 >                        (nt = nextTable) == null)
1842 >                        break;
1843 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
1844 >                        transfer(tab, nt);
1845                  }
1846 <            } finally {
1847 <                sizeCtl = sc;
1846 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
1847 >                    transfer(tab, null);
1848 >                s = sumCount();
1849              }
1850          }
1851      }
# Line 2072 | Line 1855 | public class ConcurrentHashMap<K, V>
1855       *
1856       * @param size number of elements (doesn't need to be perfectly accurate)
1857       */
1858 <    private final void tryPresize(int size) {
1858 >    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
1859          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1860              tableSizeFor(size + (size >>> 1) + 1);
1861          int sc;
1862          while ((sc = sizeCtl) >= 0) {
1863 <            Node[] tab = table; int n;
1863 >            Node<V>[] tab = table; int n;
1864              if (tab == null || (n = tab.length) == 0) {
1865                  n = (sc > c) ? sc : c;
1866 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1866 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1867                      try {
1868                          if (table == tab) {
1869 <                            table = new Node[n];
1869 >                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
1870 >                            table = (Node<V>[])tb;
1871                              sc = n - (n >>> 2);
1872                          }
1873                      } finally {
# Line 2093 | Line 1877 | public class ConcurrentHashMap<K, V>
1877              }
1878              else if (c <= sc || n >= MAXIMUM_CAPACITY)
1879                  break;
1880 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1881 <                try {
1882 <                    if (table == tab) {
2099 <                        table = rebuild(tab);
2100 <                        sc = (n << 1) - (n >>> 1);
2101 <                    }
2102 <                } finally {
2103 <                    sizeCtl = sc;
2104 <                }
2105 <            }
1880 >            else if (tab == table &&
1881 >                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
1882 >                transfer(tab, null);
1883          }
1884      }
1885  
1886 <    /*
1886 >    /**
1887       * Moves and/or copies the nodes in each bin to new table. See
1888       * above for explanation.
2112     *
2113     * @return the new table
1889       */
1890 <    private static final Node[] rebuild(Node[] tab) {
1891 <        int n = tab.length;
1892 <        Node[] nextTab = new Node[n << 1];
1893 <        Node fwd = new Node(MOVED, nextTab, null, null);
1894 <        int[] buffer = null;       // holds bins to revisit; null until needed
1895 <        Node rev = null;           // reverse forwarder; null until needed
1896 <        int nbuffered = 0;         // the number of bins in buffer list
1897 <        int bufferIndex = 0;       // buffer index of current buffered bin
1898 <        int bin = n - 1;           // current non-buffered bin or -1 if none
1899 <
1900 <        for (int i = bin;;) {      // start upwards sweep
1901 <            int fh; Node f;
1902 <            if ((f = tabAt(tab, i)) == null) {
1903 <                if (bin >= 0) {    // Unbuffered; no lock needed (or available)
1904 <                    if (!casTabAt(tab, i, f, fwd))
1905 <                        continue;
1906 <                }
1907 <                else {             // transiently use a locked forwarding node
1908 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
1909 <                    if (!casTabAt(tab, i, f, g))
1910 <                        continue;
1890 >    @SuppressWarnings("unchecked") private final void transfer
1891 >        (Node<V>[] tab, Node<V>[] nextTab) {
1892 >        int n = tab.length, stride;
1893 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
1894 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
1895 >        if (nextTab == null) {            // initiating
1896 >            try {
1897 >                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
1898 >                nextTab = (Node<V>[])tb;
1899 >            } catch (Throwable ex) {      // try to cope with OOME
1900 >                sizeCtl = Integer.MAX_VALUE;
1901 >                return;
1902 >            }
1903 >            nextTable = nextTab;
1904 >            transferOrigin = n;
1905 >            transferIndex = n;
1906 >            Node<V> rev = new Node<V>(MOVED, tab, null, null);
1907 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
1908 >                int nextk = (k > stride) ? k - stride : 0;
1909 >                for (int m = nextk; m < k; ++m)
1910 >                    nextTab[m] = rev;
1911 >                for (int m = n + nextk; m < n + k; ++m)
1912 >                    nextTab[m] = rev;
1913 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
1914 >            }
1915 >        }
1916 >        int nextn = nextTab.length;
1917 >        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
1918 >        boolean advance = true;
1919 >        for (int i = 0, bound = 0;;) {
1920 >            int nextIndex, nextBound; Node<V> f; Object fk;
1921 >            while (advance) {
1922 >                if (--i >= bound)
1923 >                    advance = false;
1924 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
1925 >                    i = -1;
1926 >                    advance = false;
1927 >                }
1928 >                else if (U.compareAndSwapInt
1929 >                         (this, TRANSFERINDEX, nextIndex,
1930 >                          nextBound = (nextIndex > stride ?
1931 >                                       nextIndex - stride : 0))) {
1932 >                    bound = nextBound;
1933 >                    i = nextIndex - 1;
1934 >                    advance = false;
1935 >                }
1936 >            }
1937 >            if (i < 0 || i >= n || i + n >= nextn) {
1938 >                for (int sc;;) {
1939 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
1940 >                        if (sc == -1) {
1941 >                            nextTable = null;
1942 >                            table = nextTab;
1943 >                            sizeCtl = (n << 1) - (n >>> 1);
1944 >                        }
1945 >                        return;
1946 >                    }
1947 >                }
1948 >            }
1949 >            else if ((f = tabAt(tab, i)) == null) {
1950 >                if (casTabAt(tab, i, null, fwd)) {
1951                      setTabAt(nextTab, i, null);
1952                      setTabAt(nextTab, i + n, null);
1953 <                    setTabAt(tab, i, fwd);
2139 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2140 <                        g.hash = MOVED;
2141 <                        synchronized (g) { g.notifyAll(); }
2142 <                    }
1953 >                    advance = true;
1954                  }
1955              }
1956 <            else if ((fh = f.hash) == MOVED) {
1957 <                Object fk = f.key;
1958 <                if (fk instanceof TreeBin) {
1959 <                    TreeBin t = (TreeBin)fk;
1960 <                    boolean validated = false;
1961 <                    t.acquire(0);
1962 <                    try {
1963 <                        if (tabAt(tab, i) == f) {
1964 <                            validated = true;
1965 <                            splitTreeBin(nextTab, i, t);
1966 <                            setTabAt(tab, i, fwd);
1956 >            else if (f.hash >= 0) {
1957 >                synchronized (f) {
1958 >                    if (tabAt(tab, i) == f) {
1959 >                        int runBit = f.hash & n;
1960 >                        Node<V> lastRun = f, lo = null, hi = null;
1961 >                        for (Node<V> p = f.next; p != null; p = p.next) {
1962 >                            int b = p.hash & n;
1963 >                            if (b != runBit) {
1964 >                                runBit = b;
1965 >                                lastRun = p;
1966 >                            }
1967                          }
1968 <                    } finally {
1969 <                        t.release(0);
1968 >                        if (runBit == 0)
1969 >                            lo = lastRun;
1970 >                        else
1971 >                            hi = lastRun;
1972 >                        for (Node<V> p = f; p != lastRun; p = p.next) {
1973 >                            int ph = p.hash;
1974 >                            Object pk = p.key; V pv = p.val;
1975 >                            if ((ph & n) == 0)
1976 >                                lo = new Node<V>(ph, pk, pv, lo);
1977 >                            else
1978 >                                hi = new Node<V>(ph, pk, pv, hi);
1979 >                        }
1980 >                        setTabAt(nextTab, i, lo);
1981 >                        setTabAt(nextTab, i + n, hi);
1982 >                        setTabAt(tab, i, fwd);
1983 >                        advance = true;
1984                      }
2160                    if (!validated)
2161                        continue;
1985                  }
1986              }
1987 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
1988 <                boolean validated = false;
1989 <                try {              // split to lo and hi lists; copying as needed
1987 >            else if ((fk = f.key) instanceof TreeBin) {
1988 >                TreeBin<V> t = (TreeBin<V>)fk;
1989 >                t.acquire(0);
1990 >                try {
1991                      if (tabAt(tab, i) == f) {
1992 <                        validated = true;
1993 <                        splitBin(nextTab, i, f);
1992 >                        TreeBin<V> lt = new TreeBin<V>();
1993 >                        TreeBin<V> ht = new TreeBin<V>();
1994 >                        int lc = 0, hc = 0;
1995 >                        for (Node<V> e = t.first; e != null; e = e.next) {
1996 >                            int h = e.hash;
1997 >                            Object k = e.key; V v = e.val;
1998 >                            if ((h & n) == 0) {
1999 >                                ++lc;
2000 >                                lt.putTreeNode(h, k, v);
2001 >                            }
2002 >                            else {
2003 >                                ++hc;
2004 >                                ht.putTreeNode(h, k, v);
2005 >                            }
2006 >                        }
2007 >                        Node<V> ln, hn; // throw away trees if too small
2008 >                        if (lc < TREE_THRESHOLD) {
2009 >                            ln = null;
2010 >                            for (Node<V> p = lt.first; p != null; p = p.next)
2011 >                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2012 >                        }
2013 >                        else
2014 >                            ln = new Node<V>(MOVED, lt, null, null);
2015 >                        setTabAt(nextTab, i, ln);
2016 >                        if (hc < TREE_THRESHOLD) {
2017 >                            hn = null;
2018 >                            for (Node<V> p = ht.first; p != null; p = p.next)
2019 >                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2020 >                        }
2021 >                        else
2022 >                            hn = new Node<V>(MOVED, ht, null, null);
2023 >                        setTabAt(nextTab, i + n, hn);
2024                          setTabAt(tab, i, fwd);
2025 +                        advance = true;
2026                      }
2027                  } finally {
2028 <                    if (!f.casHash(fh | LOCKED, fh)) {
2174 <                        f.hash = fh;
2175 <                        synchronized (f) { f.notifyAll(); };
2176 <                    }
2028 >                    t.release(0);
2029                  }
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];
2030              }
2031              else
2032 <                return nextTab;
2032 >                advance = true; // already processed
2033          }
2034      }
2035  
2036 <    /**
2215 <     * 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);
2243 <    }
2036 >    /* ---------------- Counter support -------------- */
2037  
2038 <    /**
2039 <     * Splits a tree bin into lo and hi parts; installs in given table.
2040 <     */
2041 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2042 <        int bit = nextTab.length >>> 1;
2043 <        TreeBin lt = new TreeBin();
2044 <        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);
2038 >    final long sumCount() {
2039 >        Cell[] as = counterCells; Cell a;
2040 >        long sum = baseCount;
2041 >        if (as != null) {
2042 >            for (int i = 0; i < as.length; ++i) {
2043 >                if ((a = as[i]) != null)
2044 >                    sum += a.value;
2045              }
2046          }
2047 <        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);
2047 >        return sum;
2048      }
2049  
2050 <    /**
2051 <     * Implementation for clear. Steps through each bin, removing all
2052 <     * nodes.
2053 <     */
2054 <    private final void internalClear() {
2055 <        long delta = 0L; // negative number of deletions
2056 <        int i = 0;
2057 <        Node[] tab = table;
2058 <        while (tab != null && i < tab.length) {
2059 <            int fh; Object fk;
2060 <            Node f = tabAt(tab, i);
2061 <            if (f == null)
2062 <                ++i;
2063 <            else if ((fh = f.hash) == MOVED) {
2064 <                if ((fk = f.key) instanceof TreeBin) {
2065 <                    TreeBin t = (TreeBin)fk;
2066 <                    t.acquire(0);
2067 <                    try {
2068 <                        if (tabAt(tab, i) == f) {
2069 <                            for (Node p = t.first; p != null; p = p.next) {
2070 <                                if (p.val != null) { // (currently always true)
2071 <                                    p.val = null;
2072 <                                    --delta;
2050 >    // See LongAdder version for explanation
2051 >    private final void fullAddCount(long x, boolean wasUncontended) {
2052 >        int h;
2053 >        if ((h = ThreadLocalRandom.getProbe()) == 0) {
2054 >            ThreadLocalRandom.localInit();      // force initialization
2055 >            h = ThreadLocalRandom.getProbe();
2056 >            wasUncontended = true;
2057 >        }
2058 >        boolean collide = false;                // True if last slot nonempty
2059 >        for (;;) {
2060 >            Cell[] as; Cell a; int n; long v;
2061 >            if ((as = counterCells) != null && (n = as.length) > 0) {
2062 >                if ((a = as[(n - 1) & h]) == null) {
2063 >                    if (cellsBusy == 0) {            // Try to attach new Cell
2064 >                        Cell r = new Cell(x); // Optimistic create
2065 >                        if (cellsBusy == 0 &&
2066 >                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2067 >                            boolean created = false;
2068 >                            try {               // Recheck under lock
2069 >                                Cell[] rs; int m, j;
2070 >                                if ((rs = counterCells) != null &&
2071 >                                    (m = rs.length) > 0 &&
2072 >                                    rs[j = (m - 1) & h] == null) {
2073 >                                    rs[j] = r;
2074 >                                    created = true;
2075                                  }
2076 +                            } finally {
2077 +                                cellsBusy = 0;
2078                              }
2079 <                            t.first = null;
2080 <                            t.root = null;
2081 <                            ++i;
2079 >                            if (created)
2080 >                                break;
2081 >                            continue;           // Slot is now non-empty
2082 >                        }
2083 >                    }
2084 >                    collide = false;
2085 >                }
2086 >                else if (!wasUncontended)       // CAS already known to fail
2087 >                    wasUncontended = true;      // Continue after rehash
2088 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2089 >                    break;
2090 >                else if (counterCells != as || n >= NCPU)
2091 >                    collide = false;            // At max size or stale
2092 >                else if (!collide)
2093 >                    collide = true;
2094 >                else if (cellsBusy == 0 &&
2095 >                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2096 >                    try {
2097 >                        if (counterCells == as) {// Expand table unless stale
2098 >                            Cell[] rs = new Cell[n << 1];
2099 >                            for (int i = 0; i < n; ++i)
2100 >                                rs[i] = as[i];
2101 >                            counterCells = rs;
2102                          }
2103                      } finally {
2104 <                        t.release(0);
2104 >                        cellsBusy = 0;
2105                      }
2106 +                    collide = false;
2107 +                    continue;                   // Retry with expanded table
2108                  }
2109 <                else
2318 <                    tab = (Node[])fk;
2109 >                h = ThreadLocalRandom.advanceProbe(h);
2110              }
2111 <            else if ((fh & LOCKED) != 0) {
2112 <                counter.add(delta); // opportunistically update count
2113 <                delta = 0L;
2114 <                f.tryAwaitLock(tab, i);
2115 <            }
2116 <            else if (f.casHash(fh, fh | LOCKED)) {
2117 <                try {
2118 <                    if (tabAt(tab, i) == f) {
2119 <                        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;
2111 >            else if (cellsBusy == 0 && counterCells == as &&
2112 >                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2113 >                boolean init = false;
2114 >                try {                           // Initialize table
2115 >                    if (counterCells == as) {
2116 >                        Cell[] rs = new Cell[2];
2117 >                        rs[h & 1] = new Cell(x);
2118 >                        counterCells = rs;
2119 >                        init = true;
2120                      }
2121                  } finally {
2122 <                    if (!f.casHash(fh | LOCKED, fh)) {
2339 <                        f.hash = fh;
2340 <                        synchronized (f) { f.notifyAll(); };
2341 <                    }
2122 >                    cellsBusy = 0;
2123                  }
2124 +                if (init)
2125 +                    break;
2126              }
2127 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2128 +                break;                          // Fall back on using base
2129          }
2345        if (delta != 0)
2346            counter.add(delta);
2130      }
2131  
2132      /* ----------------Table Traversal -------------- */
# Line 2386 | Line 2169 | public class ConcurrentHashMap<K, V>
2169       * across threads, iteration terminates if a bounds checks fails
2170       * for a table read.
2171       *
2172 <     * This class extends ForkJoinTask to streamline parallel
2173 <     * iteration in bulk operations (see BulkTask). This adds only an
2174 <     * int of space overhead, which is close enough to negligible in
2175 <     * cases where it is not needed to not worry about it.  Because
2176 <     * ForkJoinTask is Serializable, but iterators need not be, we
2177 <     * need to add warning suppressions.
2178 <     */
2179 <    @SuppressWarnings("serial") static class Traverser<K,V,R> extends ForkJoinTask<R> {
2180 <        final ConcurrentHashMap<K, V> map;
2181 <        Node next;           // the next entry to use
2182 <        Object nextKey;      // cached key field of next
2183 <        Object nextVal;      // cached val field of next
2184 <        Node[] tab;          // current table; updated if resized
2172 >     * This class supports both Spliterator-based traversal and
2173 >     * CountedCompleter-based bulk tasks. The same "batch" field is
2174 >     * used, but in slightly different ways, in the two cases.  For
2175 >     * Spliterators, it is a saturating (at Integer.MAX_VALUE)
2176 >     * estimate of element coverage. For CHM tasks, it is a pre-scaled
2177 >     * size that halves down to zero for leaf tasks, that is only
2178 >     * computed upon execution of the task. (Tasks can be submitted to
2179 >     * any pool, of any size, so we don't know scale factors until
2180 >     * running.)
2181 >     *
2182 >     * This class extends CountedCompleter to streamline parallel
2183 >     * iteration in bulk operations. This adds only a few fields of
2184 >     * space overhead, which is small enough in cases where it is not
2185 >     * needed to not worry about it.  Because CountedCompleter is
2186 >     * Serializable, but iterators need not be, we need to add warning
2187 >     * suppressions.
2188 >     */
2189 >    @SuppressWarnings("serial") static class Traverser<K,V,R>
2190 >        extends CountedCompleter<R> {
2191 >        final ConcurrentHashMap<K,V> map;
2192 >        Node<V> next;        // the next entry to use
2193 >        K nextKey;           // cached key field of next
2194 >        V nextVal;           // cached val field of next
2195 >        Node<V>[] tab;       // current table; updated if resized
2196          int index;           // index of bin to use next
2197          int baseIndex;       // current index of initial table
2198          int baseLimit;       // index bound for initial table
2199          int baseSize;        // initial table size
2200 <
2200 >        int batch;           // split control
2201          /** Creates iterator for all entries in the table. */
2202 <        Traverser(ConcurrentHashMap<K, V> map) {
2202 >        Traverser(ConcurrentHashMap<K,V> map) {
2203              this.map = map;
2204 +            Node<V>[] t;
2205 +            if ((t = tab = map.table) != null)
2206 +                baseLimit = baseSize = t.length;
2207          }
2208  
2209 <        /** Creates iterator for split() methods */
2210 <        Traverser(Traverser<K,V,?> it) {
2211 <            ConcurrentHashMap<K, V> m; Node[] t;
2212 <            if ((m = this.map = it.map) == null)
2213 <                t = null;
2214 <            else if ((t = it.tab) == null && // force parent tab initialization
2215 <                     (t = it.tab = m.table) != null)
2216 <                it.baseLimit = it.baseSize = t.length;
2217 <            this.tab = t;
2218 <            this.baseSize = it.baseSize;
2219 <            it.baseLimit = this.index = this.baseIndex =
2220 <                ((this.baseLimit = it.baseLimit) + it.baseIndex + 1) >>> 1;
2209 >        /** Task constructor */
2210 >        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it, int batch) {
2211 >            super(it);
2212 >            this.map = map;
2213 >            this.batch = batch; // -1 if unknown
2214 >            if (it == null) {
2215 >                Node<V>[] t;
2216 >                if ((t = tab = map.table) != null)
2217 >                    baseLimit = baseSize = t.length;
2218 >            }
2219 >            else { // split parent
2220 >                this.tab = it.tab;
2221 >                this.baseSize = it.baseSize;
2222 >                int hi = this.baseLimit = it.baseLimit;
2223 >                it.baseLimit = this.index = this.baseIndex =
2224 >                    (hi + it.baseIndex + 1) >>> 1;
2225 >            }
2226 >        }
2227 >
2228 >        /** Spliterator constructor */
2229 >        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it) {
2230 >            super(it);
2231 >            this.map = map;
2232 >            if (it == null) {
2233 >                Node<V>[] t;
2234 >                if ((t = tab = map.table) != null)
2235 >                    baseLimit = baseSize = t.length;
2236 >                long n = map.sumCount();
2237 >                batch = ((n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2238 >                         (int)n);
2239 >            }
2240 >            else {
2241 >                this.tab = it.tab;
2242 >                this.baseSize = it.baseSize;
2243 >                int hi = this.baseLimit = it.baseLimit;
2244 >                it.baseLimit = this.index = this.baseIndex =
2245 >                    (hi + it.baseIndex + 1) >>> 1;
2246 >                this.batch = it.batch >>>= 1;
2247 >            }
2248          }
2249  
2250          /**
2251           * Advances next; returns nextVal or null if terminated.
2252           * See above for explanation.
2253           */
2254 <        final Object advance() {
2255 <            Node e = next;
2256 <            Object ev = null;
2254 >        @SuppressWarnings("unchecked") final V advance() {
2255 >            Node<V> e = next;
2256 >            V ev = null;
2257              outer: do {
2258                  if (e != null)                  // advance past used/skipped node
2259                      e = e.next;
2260                  while (e == null) {             // get to next non-null bin
2261 <                    ConcurrentHashMap<K, V> m;
2262 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2261 >                    ConcurrentHashMap<K,V> m;
2262 >                    Node<V>[] t; int b, i, n; Object ek; //  must use locals
2263                      if ((t = tab) != null)
2264                          n = t.length;
2265                      else if ((m = map) != null && (t = tab = m.table) != null)
# Line 2445 | Line 2269 | public class ConcurrentHashMap<K, V>
2269                      if ((b = baseIndex) >= baseLimit ||
2270                          (i = index) < 0 || i >= n)
2271                          break outer;
2272 <                    if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2272 >                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2273                          if ((ek = e.key) instanceof TreeBin)
2274 <                            e = ((TreeBin)ek).first;
2274 >                            e = ((TreeBin<V>)ek).first;
2275                          else {
2276 <                            tab = (Node[])ek;
2276 >                            tab = (Node<V>[])ek;
2277                              continue;           // restarts due to null val
2278                          }
2279                      }                           // visit upper slots if present
2280                      index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2281                  }
2282 <                nextKey = e.key;
2282 >                nextKey = (K)e.key;
2283              } while ((ev = e.val) == null);    // skip deleted or special nodes
2284              next = e;
2285              return nextVal = ev;
2286          }
2287  
2288          public final void remove() {
2289 <            Object k = nextKey;
2289 >            K k = nextKey;
2290              if (k == null && (advance() == null || (k = nextKey) == null))
2291                  throw new IllegalStateException();
2292              map.internalReplace(k, null, null);
# Line 2473 | Line 2297 | public class ConcurrentHashMap<K, V>
2297          }
2298  
2299          public final boolean hasMoreElements() { return hasNext(); }
2300 <        public final void setRawResult(Object x) { }
2301 <        public R getRawResult() { return null; }
2302 <        public boolean exec() { return true; }
2300 >
2301 >        public void compute() { } // default no-op CountedCompleter body
2302 >
2303 >        /**
2304 >         * Returns a batch value > 0 if this task should (and must) be
2305 >         * split, if so, adding to pending count, and in any case
2306 >         * updating batch value. The initial batch value is approx
2307 >         * exp2 of the number of times (minus one) to split task by
2308 >         * two before executing leaf action. This value is faster to
2309 >         * compute and more convenient to use as a guide to splitting
2310 >         * than is the depth, since it is used while dividing by two
2311 >         * anyway.
2312 >         */
2313 >        final int preSplit() {
2314 >            int b;  ForkJoinPool pool;
2315 >            if ((b = batch) < 0) { // force initialization
2316 >                int sp = (((pool = getPool()) == null) ?
2317 >                          ForkJoinPool.getCommonPoolParallelism() :
2318 >                          pool.getParallelism()) << 3; // slack of 8
2319 >                long n = map.sumCount();
2320 >                b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2321 >            }
2322 >            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2323 >            if ((batch = b) > 0)
2324 >                addToPendingCount(1);
2325 >            return b;
2326 >        }
2327 >
2328 >        // spliterator support
2329 >
2330 >        public long estimateSize() {
2331 >            return batch;
2332 >        }
2333      }
2334  
2335      /* ---------------- Public operations -------------- */
# Line 2484 | Line 2338 | public class ConcurrentHashMap<K, V>
2338       * Creates a new, empty map with the default initial table size (16).
2339       */
2340      public ConcurrentHashMap() {
2487        this.counter = new LongAdder();
2341      }
2342  
2343      /**
# Line 2503 | Line 2356 | public class ConcurrentHashMap<K, V>
2356          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2357                     MAXIMUM_CAPACITY :
2358                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2506        this.counter = new LongAdder();
2359          this.sizeCtl = cap;
2360      }
2361  
# Line 2513 | Line 2365 | public class ConcurrentHashMap<K, V>
2365       * @param m the map
2366       */
2367      public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2516        this.counter = new LongAdder();
2368          this.sizeCtl = DEFAULT_CAPACITY;
2369          internalPutAll(m);
2370      }
# Line 2564 | Line 2415 | public class ConcurrentHashMap<K, V>
2415          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2416          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2417              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2567        this.counter = new LongAdder();
2418          this.sizeCtl = cap;
2419      }
2420  
# Line 2575 | Line 2425 | public class ConcurrentHashMap<K, V>
2425       * @return the new set
2426       */
2427      public static <K> KeySetView<K,Boolean> newKeySet() {
2428 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(),
2429 <                                      Boolean.TRUE);
2428 >        return new KeySetView<K,Boolean>
2429 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2430      }
2431  
2432      /**
# Line 2590 | Line 2440 | public class ConcurrentHashMap<K, V>
2440       * @return the new set
2441       */
2442      public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2443 <        return new KeySetView<K,Boolean>(new ConcurrentHashMap<K,Boolean>(initialCapacity),
2444 <                                      Boolean.TRUE);
2443 >        return new KeySetView<K,Boolean>
2444 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2445      }
2446  
2447      /**
2448       * {@inheritDoc}
2449       */
2450      public boolean isEmpty() {
2451 <        return counter.sum() <= 0L; // ignore transient negative values
2451 >        return sumCount() <= 0L; // ignore transient negative values
2452      }
2453  
2454      /**
2455       * {@inheritDoc}
2456       */
2457      public int size() {
2458 <        long n = counter.sum();
2458 >        long n = sumCount();
2459          return ((n < 0L) ? 0 :
2460                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2461                  (int)n);
# Line 2615 | Line 2465 | public class ConcurrentHashMap<K, V>
2465       * Returns the number of mappings. This method should be used
2466       * instead of {@link #size} because a ConcurrentHashMap may
2467       * contain more mappings than can be represented as an int. The
2468 <     * value returned is a snapshot; the actual count may differ if
2469 <     * there are ongoing concurrent insertions or removals.
2468 >     * value returned is an estimate; the actual count may differ if
2469 >     * there are concurrent insertions or removals.
2470       *
2471       * @return the number of mappings
2472       */
2473      public long mappingCount() {
2474 <        long n = counter.sum();
2474 >        long n = sumCount();
2475          return (n < 0L) ? 0L : n; // ignore transient negative values
2476      }
2477  
# Line 2636 | Line 2486 | public class ConcurrentHashMap<K, V>
2486       *
2487       * @throws NullPointerException if the specified key is null
2488       */
2489 <    @SuppressWarnings("unchecked") public V get(Object key) {
2490 <        if (key == null)
2641 <            throw new NullPointerException();
2642 <        return (V)internalGet(key);
2489 >    public V get(Object key) {
2490 >        return internalGet(key);
2491      }
2492  
2493      /**
# Line 2652 | Line 2500 | public class ConcurrentHashMap<K, V>
2500       * @return the mapping for the key, if present; else the defaultValue
2501       * @throws NullPointerException if the specified key is null
2502       */
2503 <    @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) {
2504 <        if (key == null)
2505 <            throw new NullPointerException();
2658 <        V v = (V) internalGet(key);
2659 <        return v == null ? defaultValue : v;
2503 >    public V getValueOrDefault(Object key, V defaultValue) {
2504 >        V v;
2505 >        return (v = internalGet(key)) == null ? defaultValue : v;
2506      }
2507  
2508      /**
# Line 2669 | Line 2515 | public class ConcurrentHashMap<K, V>
2515       * @throws NullPointerException if the specified key is null
2516       */
2517      public boolean containsKey(Object key) {
2672        if (key == null)
2673            throw new NullPointerException();
2518          return internalGet(key) != null;
2519      }
2520  
# Line 2687 | Line 2531 | public class ConcurrentHashMap<K, V>
2531      public boolean containsValue(Object value) {
2532          if (value == null)
2533              throw new NullPointerException();
2534 <        Object v;
2534 >        V v;
2535          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2536          while ((v = it.advance()) != null) {
2537              if (v == value || value.equals(v))
# Line 2699 | Line 2543 | public class ConcurrentHashMap<K, V>
2543      /**
2544       * Legacy method testing if some key maps into the specified value
2545       * in this table.  This method is identical in functionality to
2546 <     * {@link #containsValue}, and exists solely to ensure
2546 >     * {@link #containsValue(Object)}, and exists solely to ensure
2547       * full compatibility with class {@link java.util.Hashtable},
2548       * which supported this method prior to introduction of the
2549       * Java Collections framework.
# Line 2711 | Line 2555 | public class ConcurrentHashMap<K, V>
2555       *         {@code false} otherwise
2556       * @throws NullPointerException if the specified value is null
2557       */
2558 <    public boolean contains(Object value) {
2558 >    @Deprecated public boolean contains(Object value) {
2559          return containsValue(value);
2560      }
2561  
# Line 2719 | Line 2563 | public class ConcurrentHashMap<K, V>
2563       * Maps the specified key to the specified value in this table.
2564       * Neither the key nor the value can be null.
2565       *
2566 <     * <p> The value can be retrieved by calling the {@code get} method
2566 >     * <p>The value can be retrieved by calling the {@code get} method
2567       * with a key that is equal to the original key.
2568       *
2569       * @param key key with which the specified value is to be associated
# Line 2728 | Line 2572 | public class ConcurrentHashMap<K, V>
2572       *         {@code null} if there was no mapping for {@code key}
2573       * @throws NullPointerException if the specified key or value is null
2574       */
2575 <    @SuppressWarnings("unchecked") public V put(K key, V value) {
2576 <        if (key == null || value == null)
2733 <            throw new NullPointerException();
2734 <        return (V)internalPut(key, value);
2575 >    public V put(K key, V value) {
2576 >        return internalPut(key, value, false);
2577      }
2578  
2579      /**
# Line 2741 | Line 2583 | public class ConcurrentHashMap<K, V>
2583       *         or {@code null} if there was no mapping for the key
2584       * @throws NullPointerException if the specified key or value is null
2585       */
2586 <    @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) {
2587 <        if (key == null || value == null)
2746 <            throw new NullPointerException();
2747 <        return (V)internalPutIfAbsent(key, value);
2586 >    public V putIfAbsent(K key, V value) {
2587 >        return internalPut(key, value, true);
2588      }
2589  
2590      /**
# Line 2759 | Line 2599 | public class ConcurrentHashMap<K, V>
2599      }
2600  
2601      /**
2602 <     * If the specified key is not already associated with a value,
2603 <     * computes its value using the given mappingFunction and enters
2604 <     * it into the map unless null.  This is equivalent to
2605 <     * <pre> {@code
2606 <     * if (map.containsKey(key))
2607 <     *   return map.get(key);
2608 <     * value = mappingFunction.apply(key);
2609 <     * if (value != null)
2610 <     *   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>
2602 >     * If the specified key is not already associated with a value (or
2603 >     * is mapped to {@code null}), attempts to compute its value using
2604 >     * the given mapping function and enters it into this map unless
2605 >     * {@code null}. The entire method invocation is performed
2606 >     * atomically, so the function is applied at most once per key.
2607 >     * Some attempted update operations on this map by other threads
2608 >     * may be blocked while computation is in progress, so the
2609 >     * computation should be short and simple, and must not attempt to
2610 >     * update any other mappings of this Map.
2611       *
2612       * @param key key with which the specified value is to be associated
2613       * @param mappingFunction the function to compute a value
# Line 2797 | Line 2621 | public class ConcurrentHashMap<K, V>
2621       * @throws RuntimeException or Error if the mappingFunction does so,
2622       *         in which case the mapping is left unestablished
2623       */
2624 <    @SuppressWarnings("unchecked") public V computeIfAbsent
2625 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
2626 <        if (key == null || mappingFunction == null)
2803 <            throw new NullPointerException();
2804 <        return (V)internalComputeIfAbsent(key, mappingFunction);
2624 >    public V computeIfAbsent
2625 >        (K key, Function<? super K, ? extends V> mappingFunction) {
2626 >        return internalComputeIfAbsent(key, mappingFunction);
2627      }
2628  
2629      /**
2630 <     * If the given key is present, computes a new mapping value given a key and
2631 <     * its current mapped value. This is equivalent to
2632 <     *  <pre> {@code
2633 <     *   if (map.containsKey(key)) {
2812 <     *     value = remappingFunction.apply(key, map.get(key));
2813 <     *     if (value != null)
2814 <     *       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
2630 >     * If the value for the specified key is present and non-null,
2631 >     * attempts to compute a new mapping given the key and its current
2632 >     * mapped value.  The entire method invocation is performed
2633 >     * atomically.  Some attempted update operations on this map by
2634       * other threads may be blocked while computation is in progress,
2635       * so the computation should be short and simple, and must not
2636 <     * attempt to update any other mappings of this Map. For example,
2828 <     * to either create or append new messages to a value mapping:
2636 >     * attempt to update any other mappings of this Map.
2637       *
2638       * @param key key with which the specified value is to be associated
2639       * @param remappingFunction the function to compute a value
# Line 2838 | Line 2646 | public class ConcurrentHashMap<K, V>
2646       * @throws RuntimeException or Error if the remappingFunction does so,
2647       *         in which case the mapping is unchanged
2648       */
2649 <    @SuppressWarnings("unchecked") public V computeIfPresent
2650 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2651 <        if (key == null || remappingFunction == null)
2844 <            throw new NullPointerException();
2845 <        return (V)internalCompute(key, true, remappingFunction);
2649 >    public V computeIfPresent
2650 >        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2651 >        return internalCompute(key, true, remappingFunction);
2652      }
2653  
2654      /**
2655 <     * Computes a new mapping value given a key and
2656 <     * its current mapped value (or {@code null} if there is no current
2657 <     * mapping). This is equivalent to
2658 <     *  <pre> {@code
2659 <     *   value = remappingFunction.apply(key, map.get(key));
2660 <     *   if (value != null)
2661 <     *     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>
2655 >     * Attempts to compute a mapping for the specified key and its
2656 >     * current mapped value (or {@code null} if there is no current
2657 >     * mapping). The entire method invocation is performed atomically.
2658 >     * Some attempted update operations on this map by other threads
2659 >     * may be blocked while computation is in progress, so the
2660 >     * computation should be short and simple, and must not attempt to
2661 >     * update any other mappings of this Map.
2662       *
2663       * @param key key with which the specified value is to be associated
2664       * @param remappingFunction the function to compute a value
# Line 2885 | Line 2671 | public class ConcurrentHashMap<K, V>
2671       * @throws RuntimeException or Error if the remappingFunction does so,
2672       *         in which case the mapping is unchanged
2673       */
2674 <    @SuppressWarnings("unchecked") public V compute
2675 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2676 <        if (key == null || remappingFunction == null)
2891 <            throw new NullPointerException();
2892 <        return (V)internalCompute(key, false, remappingFunction);
2674 >    public V compute
2675 >        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2676 >        return internalCompute(key, false, remappingFunction);
2677      }
2678  
2679      /**
2680 <     * If the specified key is not already associated
2681 <     * with a value, associate it with the given value.
2682 <     * Otherwise, replace the value with the results of
2683 <     * the given remapping function. This is equivalent to:
2684 <     *  <pre> {@code
2685 <     *   if (!map.containsKey(key))
2686 <     *     map.put(value);
2687 <     *   else {
2688 <     *     newValue = remappingFunction.apply(map.get(key), value);
2689 <     *     if (value != null)
2690 <     *       map.put(key, value);
2691 <     *     else
2692 <     *       map.remove(key);
2693 <     *   }
2694 <     * }</pre>
2695 <     * except that the action is performed atomically.  If the
2696 <     * function returns {@code null}, the mapping is removed.  If the
2697 <     * 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.
2680 >     * If the specified key is not already associated with a
2681 >     * (non-null) value, associates it with the given value.
2682 >     * Otherwise, replaces the value with the results of the given
2683 >     * remapping function, or removes if {@code null}. The entire
2684 >     * method invocation is performed atomically.  Some attempted
2685 >     * update operations on this map by other threads may be blocked
2686 >     * while computation is in progress, so the computation should be
2687 >     * short and simple, and must not attempt to update any other
2688 >     * mappings of this Map.
2689 >     *
2690 >     * @param key key with which the specified value is to be associated
2691 >     * @param value the value to use if absent
2692 >     * @param remappingFunction the function to recompute a value if present
2693 >     * @return the new value associated with the specified key, or null if none
2694 >     * @throws NullPointerException if the specified key or the
2695 >     *         remappingFunction is null
2696 >     * @throws RuntimeException or Error if the remappingFunction does so,
2697 >     *         in which case the mapping is unchanged
2698       */
2699 <    @SuppressWarnings("unchecked") public V merge
2700 <        (K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2701 <        if (key == null || value == null || remappingFunction == null)
2702 <            throw new NullPointerException();
2924 <        return (V)internalMerge(key, value, remappingFunction);
2699 >    public V merge
2700 >        (K key, V value,
2701 >         BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2702 >        return internalMerge(key, value, remappingFunction);
2703      }
2704  
2705      /**
# Line 2933 | Line 2711 | public class ConcurrentHashMap<K, V>
2711       *         {@code null} if there was no mapping for {@code key}
2712       * @throws NullPointerException if the specified key is null
2713       */
2714 <    @SuppressWarnings("unchecked") public V remove(Object key) {
2715 <        if (key == null)
2938 <            throw new NullPointerException();
2939 <        return (V)internalReplace(key, null, null);
2714 >    public V remove(Object key) {
2715 >        return internalReplace(key, null, null);
2716      }
2717  
2718      /**
# Line 2947 | Line 2723 | public class ConcurrentHashMap<K, V>
2723      public boolean remove(Object key, Object value) {
2724          if (key == null)
2725              throw new NullPointerException();
2726 <        if (value == null)
2951 <            return false;
2952 <        return internalReplace(key, null, value) != null;
2726 >        return value != null && internalReplace(key, null, value) != null;
2727      }
2728  
2729      /**
# Line 2970 | Line 2744 | public class ConcurrentHashMap<K, V>
2744       *         or {@code null} if there was no mapping for the key
2745       * @throws NullPointerException if the specified key or value is null
2746       */
2747 <    @SuppressWarnings("unchecked") public V replace(K key, V value) {
2747 >    public V replace(K key, V value) {
2748          if (key == null || value == null)
2749              throw new NullPointerException();
2750 <        return (V)internalReplace(key, value, null);
2750 >        return internalReplace(key, value, null);
2751      }
2752  
2753      /**
# Line 2998 | Line 2772 | public class ConcurrentHashMap<K, V>
2772      /**
2773       * Returns a {@link Set} view of the keys in this map, using the
2774       * given common mapped value for any additions (i.e., {@link
2775 <     * Collection#add} and {@link Collection#addAll}). This is of
2776 <     * course only appropriate if it is acceptable to use the same
2777 <     * value for all additions from this view.
2775 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2776 >     * This is of course only appropriate if it is acceptable to use
2777 >     * the same value for all additions from this view.
2778       *
2779 <     * @param mappedValue the mapped value to use for any
3006 <     * additions.
2779 >     * @param mappedValue the mapped value to use for any additions
2780       * @return the set view
2781       * @throws NullPointerException if the mappedValue is null
2782       */
# Line 3017 | Line 2790 | public class ConcurrentHashMap<K, V>
2790       * Returns a {@link Collection} view of the values contained in this map.
2791       * The collection is backed by the map, so changes to the map are
2792       * reflected in the collection, and vice-versa.
2793 +     *
2794 +     * @return the collection view
2795       */
2796      public ValuesView<K,V> values() {
2797          ValuesView<K,V> vs = values;
# Line 3038 | Line 2813 | public class ConcurrentHashMap<K, V>
2813       * and guarantees to traverse elements as they existed upon
2814       * construction of the iterator, and may (but is not guaranteed to)
2815       * reflect any modifications subsequent to construction.
2816 +     *
2817 +     * @return the set view
2818       */
2819      public Set<Map.Entry<K,V>> entrySet() {
2820          EntrySetView<K,V> es = entrySet;
# Line 3065 | Line 2842 | public class ConcurrentHashMap<K, V>
2842      }
2843  
2844      /**
3068     * Returns a partitionable iterator of the keys in this map.
3069     *
3070     * @return a partitionable iterator of the keys in this map
3071     */
3072    public Spliterator<K> keySpliterator() {
3073        return new KeyIterator<K,V>(this);
3074    }
3075
3076    /**
3077     * Returns a partitionable iterator of the values in this map.
3078     *
3079     * @return a partitionable iterator of the values in this map
3080     */
3081    public Spliterator<V> valueSpliterator() {
3082        return new ValueIterator<K,V>(this);
3083    }
3084
3085    /**
3086     * Returns a partitionable iterator of the entries in this map.
3087     *
3088     * @return a partitionable iterator of the entries in this map
3089     */
3090    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
3091        return new EntryIterator<K,V>(this);
3092    }
3093
3094    /**
2845       * Returns the hash code value for this {@link Map}, i.e.,
2846       * the sum of, for each key-value pair in the map,
2847       * {@code key.hashCode() ^ value.hashCode()}.
# Line 3101 | Line 2851 | public class ConcurrentHashMap<K, V>
2851      public int hashCode() {
2852          int h = 0;
2853          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2854 <        Object v;
2854 >        V v;
2855          while ((v = it.advance()) != null) {
2856              h += it.nextKey.hashCode() ^ v.hashCode();
2857          }
# Line 3123 | Line 2873 | public class ConcurrentHashMap<K, V>
2873          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2874          StringBuilder sb = new StringBuilder();
2875          sb.append('{');
2876 <        Object v;
2876 >        V v;
2877          if ((v = it.advance()) != null) {
2878              for (;;) {
2879 <                Object k = it.nextKey;
2879 >                K k = it.nextKey;
2880                  sb.append(k == this ? "(this Map)" : k);
2881                  sb.append('=');
2882                  sb.append(v == this ? "(this Map)" : v);
# Line 3154 | Line 2904 | public class ConcurrentHashMap<K, V>
2904                  return false;
2905              Map<?,?> m = (Map<?,?>) o;
2906              Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2907 <            Object val;
2907 >            V val;
2908              while ((val = it.advance()) != null) {
2909                  Object v = m.get(it.nextKey);
2910                  if (v == null || (v != val && !v.equals(val)))
# Line 3174 | Line 2924 | public class ConcurrentHashMap<K, V>
2924  
2925      /* ----------------Iterators -------------- */
2926  
2927 <    @SuppressWarnings("serial") static final class KeyIterator<K,V> extends Traverser<K,V,Object>
2928 <        implements Spliterator<K>, Enumeration<K> {
2929 <        KeyIterator(ConcurrentHashMap<K, V> map) { super(map); }
2930 <        KeyIterator(Traverser<K,V,Object> it) {
2931 <            super(it);
2927 >    @SuppressWarnings("serial") static final class KeyIterator<K,V>
2928 >        extends Traverser<K,V,Object>
2929 >        implements Spliterator<K>, Iterator<K>, Enumeration<K> {
2930 >        KeyIterator(ConcurrentHashMap<K,V> map) { super(map); }
2931 >        KeyIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
2932 >            super(map, it);
2933 >        }
2934 >        public KeyIterator<K,V> trySplit() {
2935 >            if (tab != null && baseIndex == baseLimit)
2936 >                return null;
2937 >            return new KeyIterator<K,V>(map, this);
2938          }
2939 <        public KeyIterator<K,V> split() {
3184 <            if (nextKey != null)
3185 <                throw new IllegalStateException();
3186 <            return new KeyIterator<K,V>(this);
3187 <        }
3188 <        @SuppressWarnings("unchecked") public final K next() {
2939 >        public final K next() {
2940              if (nextVal == null && advance() == null)
2941                  throw new NoSuchElementException();
2942 <            Object k = nextKey;
2942 >            K k = nextKey;
2943              nextVal = null;
2944 <            return (K) k;
2944 >            return k;
2945          }
2946  
2947          public final K nextElement() { return next(); }
2948 +
2949 +        public Iterator<K> iterator() { return this; }
2950 +
2951 +        public void forEach(Consumer<? super K> action) {
2952 +            if (action == null) throw new NullPointerException();
2953 +            while (advance() != null)
2954 +                action.accept(nextKey);
2955 +        }
2956 +
2957 +        public boolean tryAdvance(Consumer<? super K> block) {
2958 +            if (block == null) throw new NullPointerException();
2959 +            if (advance() == null)
2960 +                return false;
2961 +            block.accept(nextKey);
2962 +            return true;
2963 +        }
2964 +
2965 +        public int characteristics() {
2966 +            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
2967 +                Spliterator.NONNULL;
2968 +        }
2969 +
2970      }
2971  
2972 <    @SuppressWarnings("serial") static final class ValueIterator<K,V> extends Traverser<K,V,Object>
2973 <        implements Spliterator<V>, Enumeration<V> {
2974 <        ValueIterator(ConcurrentHashMap<K, V> map) { super(map); }
2975 <        ValueIterator(Traverser<K,V,Object> it) {
2976 <            super(it);
2972 >    @SuppressWarnings("serial") static final class ValueIterator<K,V>
2973 >        extends Traverser<K,V,Object>
2974 >        implements Spliterator<V>, Iterator<V>, Enumeration<V> {
2975 >        ValueIterator(ConcurrentHashMap<K,V> map) { super(map); }
2976 >        ValueIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
2977 >            super(map, it);
2978          }
2979 <        public ValueIterator<K,V> split() {
2980 <            if (nextKey != null)
2981 <                throw new IllegalStateException();
2982 <            return new ValueIterator<K,V>(this);
2979 >        public ValueIterator<K,V> trySplit() {
2980 >            if (tab != null && baseIndex == baseLimit)
2981 >                return null;
2982 >            return new ValueIterator<K,V>(map, this);
2983          }
2984  
2985 <        @SuppressWarnings("unchecked") public final V next() {
2986 <            Object v;
2985 >        public final V next() {
2986 >            V v;
2987              if ((v = nextVal) == null && (v = advance()) == null)
2988                  throw new NoSuchElementException();
2989              nextVal = null;
2990 <            return (V) v;
2990 >            return v;
2991          }
2992  
2993          public final V nextElement() { return next(); }
2994 +
2995 +        public Iterator<V> iterator() { return this; }
2996 +
2997 +        public void forEach(Consumer<? super V> action) {
2998 +            if (action == null) throw new NullPointerException();
2999 +            V v;
3000 +            while ((v = advance()) != null)
3001 +                action.accept(v);
3002 +        }
3003 +
3004 +        public boolean tryAdvance(Consumer<? super V> block) {
3005 +            V v;
3006 +            if (block == null) throw new NullPointerException();
3007 +            if ((v = advance()) == null)
3008 +                return false;
3009 +            block.accept(v);
3010 +            return true;
3011 +        }
3012 +
3013 +        public int characteristics() {
3014 +            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3015 +        }
3016      }
3017  
3018 <    @SuppressWarnings("serial") static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3019 <        implements Spliterator<Map.Entry<K,V>> {
3020 <        EntryIterator(ConcurrentHashMap<K, V> map) { super(map); }
3021 <        EntryIterator(Traverser<K,V,Object> it) {
3022 <            super(it);
3018 >    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3019 >        extends Traverser<K,V,Object>
3020 >        implements Spliterator<Map.Entry<K,V>>, Iterator<Map.Entry<K,V>> {
3021 >        EntryIterator(ConcurrentHashMap<K,V> map) { super(map); }
3022 >        EntryIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3023 >            super(map, it);
3024          }
3025 <        public EntryIterator<K,V> split() {
3026 <            if (nextKey != null)
3027 <                throw new IllegalStateException();
3028 <            return new EntryIterator<K,V>(this);
3025 >        public EntryIterator<K,V> trySplit() {
3026 >            if (tab != null && baseIndex == baseLimit)
3027 >                return null;
3028 >            return new EntryIterator<K,V>(map, this);
3029          }
3030  
3031 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3032 <            Object v;
3031 >        public final Map.Entry<K,V> next() {
3032 >            V v;
3033              if ((v = nextVal) == null && (v = advance()) == null)
3034                  throw new NoSuchElementException();
3035 <            Object k = nextKey;
3035 >            K k = nextKey;
3036              nextVal = null;
3037 <            return new MapEntry<K,V>((K)k, (V)v, map);
3037 >            return new MapEntry<K,V>(k, v, map);
3038 >        }
3039 >
3040 >        public Iterator<Map.Entry<K,V>> iterator() { return this; }
3041 >
3042 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
3043 >            if (action == null) throw new NullPointerException();
3044 >            V v;
3045 >            while ((v = advance()) != null)
3046 >                action.accept(entryFor(nextKey, v));
3047 >        }
3048 >
3049 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> block) {
3050 >            V v;
3051 >            if (block == null) throw new NullPointerException();
3052 >            if ((v = advance()) == null)
3053 >                return false;
3054 >            block.accept(entryFor(nextKey, v));
3055 >            return true;
3056 >        }
3057 >
3058 >        public int characteristics() {
3059 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3060 >                Spliterator.NONNULL;
3061          }
3062      }
3063  
3064      /**
3065       * Exported Entry for iterators
3066       */
3067 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3067 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3068          final K key; // non-null
3069          V val;       // non-null
3070 <        final ConcurrentHashMap<K, V> map;
3071 <        MapEntry(K key, V val, ConcurrentHashMap<K, V> map) {
3070 >        final ConcurrentHashMap<K,V> map;
3071 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3072              this.key = key;
3073              this.val = val;
3074              this.map = map;
# Line 3284 | Line 3104 | public class ConcurrentHashMap<K, V>
3104          }
3105      }
3106  
3107 +    /**
3108 +     * Returns exportable snapshot entry for the given key and value
3109 +     * when write-through can't or shouldn't be used.
3110 +     */
3111 +    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3112 +        return new AbstractMap.SimpleEntry<K,V>(k, v);
3113 +    }
3114 +
3115      /* ---------------- Serialization Support -------------- */
3116  
3117      /**
# Line 3305 | Line 3133 | public class ConcurrentHashMap<K, V>
3133       * for each key-value mapping, followed by a null pair.
3134       * The key-value mappings are emitted in no particular order.
3135       */
3136 <    @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s)
3136 >    @SuppressWarnings("unchecked") private void writeObject
3137 >        (java.io.ObjectOutputStream s)
3138          throws java.io.IOException {
3139          if (segments == null) { // for serialization compatibility
3140              segments = (Segment<K,V>[])
# Line 3315 | Line 3144 | public class ConcurrentHashMap<K, V>
3144          }
3145          s.defaultWriteObject();
3146          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3147 <        Object v;
3147 >        V v;
3148          while ((v = it.advance()) != null) {
3149              s.writeObject(it.nextKey);
3150              s.writeObject(v);
# Line 3329 | Line 3158 | public class ConcurrentHashMap<K, V>
3158       * Reconstitutes the instance from a stream (that is, deserializes it).
3159       * @param s the stream
3160       */
3161 <    @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
3161 >    @SuppressWarnings("unchecked") private void readObject
3162 >        (java.io.ObjectInputStream s)
3163          throws java.io.IOException, ClassNotFoundException {
3164          s.defaultReadObject();
3165          this.segments = null; // unneeded
3336        // initialize transient final field
3337        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
3166  
3167          // Create all nodes, then place in table once size is known
3168          long size = 0L;
3169 <        Node p = null;
3169 >        Node<V> p = null;
3170          for (;;) {
3171              K k = (K) s.readObject();
3172              V v = (V) s.readObject();
3173              if (k != null && v != null) {
3174                  int h = spread(k.hashCode());
3175 <                p = new Node(h, k, v, p);
3175 >                p = new Node<V>(h, k, v, p);
3176                  ++size;
3177              }
3178              else
# Line 3362 | Line 3190 | public class ConcurrentHashMap<K, V>
3190              int sc = sizeCtl;
3191              boolean collide = false;
3192              if (n > sc &&
3193 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3193 >                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3194                  try {
3195                      if (table == null) {
3196                          init = true;
3197 <                        Node[] tab = new Node[n];
3197 >                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3198 >                        Node<V>[] tab = (Node<V>[])rt;
3199                          int mask = n - 1;
3200                          while (p != null) {
3201                              int j = p.hash & mask;
3202 <                            Node next = p.next;
3203 <                            Node q = p.next = tabAt(tab, j);
3202 >                            Node<V> next = p.next;
3203 >                            Node<V> q = p.next = tabAt(tab, j);
3204                              setTabAt(tab, j, p);
3205                              if (!collide && q != null && q.hash == p.hash)
3206                                  collide = true;
3207                              p = next;
3208                          }
3209                          table = tab;
3210 <                        counter.add(size);
3210 >                        addCount(size, -1);
3211                          sc = n - (n >>> 2);
3212                      }
3213                  } finally {
3214                      sizeCtl = sc;
3215                  }
3216                  if (collide) { // rescan and convert to TreeBins
3217 <                    Node[] tab = table;
3217 >                    Node<V>[] tab = table;
3218                      for (int i = 0; i < tab.length; ++i) {
3219                          int c = 0;
3220 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3220 >                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3221                              if (++c > TREE_THRESHOLD &&
3222                                  (e.key instanceof Comparable)) {
3223                                  replaceWithTreeBin(tab, i, e.key);
# Line 3400 | Line 3229 | public class ConcurrentHashMap<K, V>
3229              }
3230              if (!init) { // Can only happen if unsafely published.
3231                  while (p != null) {
3232 <                    internalPut(p.key, p.val);
3232 >                    internalPut((K)p.key, p.val, false);
3233                      p = p.next;
3234                  }
3235              }
3236          }
3237      }
3238  
3410
3239      // -------------------------------------------------------
3240  
3241 <    // Sams
3414 <    /** Interface describing a void action of one argument */
3415 <    public interface Action<A> { void apply(A a); }
3416 <    /** Interface describing a void action of two arguments */
3417 <    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); }
3241 >    // Sequential bulk operations
3242  
3243 +    /**
3244 +     * Performs the given action for each (key, value).
3245 +     *
3246 +     * @param action the action
3247 +     */
3248 +    public void forEachSequentially
3249 +        (BiConsumer<? super K, ? super V> action) {
3250 +        if (action == null) throw new NullPointerException();
3251 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3252 +        V v;
3253 +        while ((v = it.advance()) != null)
3254 +            action.accept(it.nextKey, v);
3255 +    }
3256  
3257 <    // -------------------------------------------------------
3257 >    /**
3258 >     * Performs the given action for each non-null transformation
3259 >     * of each (key, value).
3260 >     *
3261 >     * @param transformer a function returning the transformation
3262 >     * for an element, or null if there is no transformation (in
3263 >     * which case the action is not applied)
3264 >     * @param action the action
3265 >     */
3266 >    public <U> void forEachSequentially
3267 >        (BiFunction<? super K, ? super V, ? extends U> transformer,
3268 >         Consumer<? super U> action) {
3269 >        if (transformer == null || action == null)
3270 >            throw new NullPointerException();
3271 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3272 >        V v; U u;
3273 >        while ((v = it.advance()) != null) {
3274 >            if ((u = transformer.apply(it.nextKey, v)) != null)
3275 >                action.accept(u);
3276 >        }
3277 >    }
3278 >
3279 >    /**
3280 >     * Returns a non-null result from applying the given search
3281 >     * function on each (key, value), or null if none.
3282 >     *
3283 >     * @param searchFunction a function returning a non-null
3284 >     * result on success, else null
3285 >     * @return a non-null result from applying the given search
3286 >     * function on each (key, value), or null if none
3287 >     */
3288 >    public <U> U searchSequentially
3289 >        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3290 >        if (searchFunction == null) throw new NullPointerException();
3291 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3292 >        V v; U u;
3293 >        while ((v = it.advance()) != null) {
3294 >            if ((u = searchFunction.apply(it.nextKey, v)) != null)
3295 >                return u;
3296 >        }
3297 >        return null;
3298 >    }
3299 >
3300 >    /**
3301 >     * Returns the result of accumulating the given transformation
3302 >     * of all (key, value) pairs using the given reducer to
3303 >     * combine values, or null if none.
3304 >     *
3305 >     * @param transformer a function returning the transformation
3306 >     * for an element, or null if there is no transformation (in
3307 >     * which case it is not combined)
3308 >     * @param reducer a commutative associative combining function
3309 >     * @return the result of accumulating the given transformation
3310 >     * of all (key, value) pairs
3311 >     */
3312 >    public <U> U reduceSequentially
3313 >        (BiFunction<? super K, ? super V, ? extends U> transformer,
3314 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3315 >        if (transformer == null || reducer == null)
3316 >            throw new NullPointerException();
3317 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3318 >        U r = null, u; V v;
3319 >        while ((v = it.advance()) != null) {
3320 >            if ((u = transformer.apply(it.nextKey, v)) != null)
3321 >                r = (r == null) ? u : reducer.apply(r, u);
3322 >        }
3323 >        return r;
3324 >    }
3325 >
3326 >    /**
3327 >     * Returns the result of accumulating the given transformation
3328 >     * of all (key, value) pairs using the given reducer to
3329 >     * combine values, and the given basis as an identity value.
3330 >     *
3331 >     * @param transformer a function returning the transformation
3332 >     * for an element
3333 >     * @param basis the identity (initial default value) for the reduction
3334 >     * @param reducer a commutative associative combining function
3335 >     * @return the result of accumulating the given transformation
3336 >     * of all (key, value) pairs
3337 >     */
3338 >    public double reduceToDoubleSequentially
3339 >        (ToDoubleBiFunction<? super K, ? super V> transformer,
3340 >         double basis,
3341 >         DoubleBinaryOperator reducer) {
3342 >        if (transformer == null || reducer == null)
3343 >            throw new NullPointerException();
3344 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3345 >        double r = basis; V v;
3346 >        while ((v = it.advance()) != null)
3347 >            r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey, v));
3348 >        return r;
3349 >    }
3350 >
3351 >    /**
3352 >     * Returns the result of accumulating the given transformation
3353 >     * of all (key, value) pairs using the given reducer to
3354 >     * combine values, and the given basis as an identity value.
3355 >     *
3356 >     * @param transformer a function returning the transformation
3357 >     * for an element
3358 >     * @param basis the identity (initial default value) for the reduction
3359 >     * @param reducer a commutative associative combining function
3360 >     * @return the result of accumulating the given transformation
3361 >     * of all (key, value) pairs
3362 >     */
3363 >    public long reduceToLongSequentially
3364 >        (ToLongBiFunction<? super K, ? super V> transformer,
3365 >         long basis,
3366 >         LongBinaryOperator reducer) {
3367 >        if (transformer == null || reducer == null)
3368 >            throw new NullPointerException();
3369 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3370 >        long r = basis; V v;
3371 >        while ((v = it.advance()) != null)
3372 >            r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey, v));
3373 >        return r;
3374 >    }
3375 >
3376 >    /**
3377 >     * Returns the result of accumulating the given transformation
3378 >     * of all (key, value) pairs using the given reducer to
3379 >     * combine values, and the given basis as an identity value.
3380 >     *
3381 >     * @param transformer a function returning the transformation
3382 >     * for an element
3383 >     * @param basis the identity (initial default value) for the reduction
3384 >     * @param reducer a commutative associative combining function
3385 >     * @return the result of accumulating the given transformation
3386 >     * of all (key, value) pairs
3387 >     */
3388 >    public int reduceToIntSequentially
3389 >        (ToIntBiFunction<? super K, ? super V> transformer,
3390 >         int basis,
3391 >         IntBinaryOperator reducer) {
3392 >        if (transformer == null || reducer == null)
3393 >            throw new NullPointerException();
3394 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3395 >        int r = basis; V v;
3396 >        while ((v = it.advance()) != null)
3397 >            r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey, v));
3398 >        return r;
3399 >    }
3400 >
3401 >    /**
3402 >     * Performs the given action for each key.
3403 >     *
3404 >     * @param action the action
3405 >     */
3406 >    public void forEachKeySequentially
3407 >        (Consumer<? super K> action) {
3408 >        if (action == null) throw new NullPointerException();
3409 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3410 >        while (it.advance() != null)
3411 >            action.accept(it.nextKey);
3412 >    }
3413 >
3414 >    /**
3415 >     * Performs the given action for each non-null transformation
3416 >     * of each key.
3417 >     *
3418 >     * @param transformer a function returning the transformation
3419 >     * for an element, or null if there is no transformation (in
3420 >     * which case the action is not applied)
3421 >     * @param action the action
3422 >     */
3423 >    public <U> void forEachKeySequentially
3424 >        (Function<? super K, ? extends U> transformer,
3425 >         Consumer<? super U> action) {
3426 >        if (transformer == null || action == null)
3427 >            throw new NullPointerException();
3428 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3429 >        U u;
3430 >        while (it.advance() != null) {
3431 >            if ((u = transformer.apply(it.nextKey)) != null)
3432 >                action.accept(u);
3433 >        }
3434 >        ForkJoinTasks.forEachKey
3435 >            (this, transformer, action).invoke();
3436 >    }
3437 >
3438 >    /**
3439 >     * Returns a non-null result from applying the given search
3440 >     * function on each key, or null if none.
3441 >     *
3442 >     * @param searchFunction a function returning a non-null
3443 >     * result on success, else null
3444 >     * @return a non-null result from applying the given search
3445 >     * function on each key, or null if none
3446 >     */
3447 >    public <U> U searchKeysSequentially
3448 >        (Function<? super K, ? extends U> searchFunction) {
3449 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3450 >        U u;
3451 >        while (it.advance() != null) {
3452 >            if ((u = searchFunction.apply(it.nextKey)) != null)
3453 >                return u;
3454 >        }
3455 >        return null;
3456 >    }
3457 >
3458 >    /**
3459 >     * Returns the result of accumulating all keys using the given
3460 >     * reducer to combine values, or null if none.
3461 >     *
3462 >     * @param reducer a commutative associative combining function
3463 >     * @return the result of accumulating all keys using the given
3464 >     * reducer to combine values, or null if none
3465 >     */
3466 >    public K reduceKeysSequentially
3467 >        (BiFunction<? super K, ? super K, ? extends K> reducer) {
3468 >        if (reducer == null) throw new NullPointerException();
3469 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3470 >        K r = null;
3471 >        while (it.advance() != null) {
3472 >            K u = it.nextKey;
3473 >            r = (r == null) ? u : reducer.apply(r, u);
3474 >        }
3475 >        return r;
3476 >    }
3477 >
3478 >    /**
3479 >     * Returns the result of accumulating the given transformation
3480 >     * of all keys using the given reducer to combine values, or
3481 >     * null if none.
3482 >     *
3483 >     * @param transformer a function returning the transformation
3484 >     * for an element, or null if there is no transformation (in
3485 >     * which case it is not combined)
3486 >     * @param reducer a commutative associative combining function
3487 >     * @return the result of accumulating the given transformation
3488 >     * of all keys
3489 >     */
3490 >    public <U> U reduceKeysSequentially
3491 >        (Function<? super K, ? extends U> transformer,
3492 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3493 >        if (transformer == null || reducer == null)
3494 >            throw new NullPointerException();
3495 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3496 >        U r = null, u;
3497 >        while (it.advance() != null) {
3498 >            if ((u = transformer.apply(it.nextKey)) != null)
3499 >                r = (r == null) ? u : reducer.apply(r, u);
3500 >        }
3501 >        return r;
3502 >    }
3503 >
3504 >    /**
3505 >     * Returns the result of accumulating the given transformation
3506 >     * of all keys using the given reducer to combine values, and
3507 >     * the given basis as an identity value.
3508 >     *
3509 >     * @param transformer a function returning the transformation
3510 >     * for an element
3511 >     * @param basis the identity (initial default value) for the reduction
3512 >     * @param reducer a commutative associative combining function
3513 >     * @return the result of accumulating the given transformation
3514 >     * of all keys
3515 >     */
3516 >    public double reduceKeysToDoubleSequentially
3517 >        (ToDoubleFunction<? super K> transformer,
3518 >         double basis,
3519 >         DoubleBinaryOperator reducer) {
3520 >        if (transformer == null || reducer == null)
3521 >            throw new NullPointerException();
3522 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3523 >        double r = basis;
3524 >        while (it.advance() != null)
3525 >            r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey));
3526 >        return r;
3527 >    }
3528 >
3529 >    /**
3530 >     * Returns the result of accumulating the given transformation
3531 >     * of all keys using the given reducer to combine values, and
3532 >     * the given basis as an identity value.
3533 >     *
3534 >     * @param transformer a function returning the transformation
3535 >     * for an element
3536 >     * @param basis the identity (initial default value) for the reduction
3537 >     * @param reducer a commutative associative combining function
3538 >     * @return the result of accumulating the given transformation
3539 >     * of all keys
3540 >     */
3541 >    public long reduceKeysToLongSequentially
3542 >        (ToLongFunction<? super K> transformer,
3543 >         long basis,
3544 >         LongBinaryOperator reducer) {
3545 >        if (transformer == null || reducer == null)
3546 >            throw new NullPointerException();
3547 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3548 >        long r = basis;
3549 >        while (it.advance() != null)
3550 >            r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey));
3551 >        return r;
3552 >    }
3553 >
3554 >    /**
3555 >     * Returns the result of accumulating the given transformation
3556 >     * of all keys using the given reducer to combine values, and
3557 >     * the given basis as an identity value.
3558 >     *
3559 >     * @param transformer a function returning the transformation
3560 >     * for an element
3561 >     * @param basis the identity (initial default value) for the reduction
3562 >     * @param reducer a commutative associative combining function
3563 >     * @return the result of accumulating the given transformation
3564 >     * of all keys
3565 >     */
3566 >    public int reduceKeysToIntSequentially
3567 >        (ToIntFunction<? super K> transformer,
3568 >         int basis,
3569 >         IntBinaryOperator reducer) {
3570 >        if (transformer == null || reducer == null)
3571 >            throw new NullPointerException();
3572 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3573 >        int r = basis;
3574 >        while (it.advance() != null)
3575 >            r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey));
3576 >        return r;
3577 >    }
3578 >
3579 >    /**
3580 >     * Performs the given action for each value.
3581 >     *
3582 >     * @param action the action
3583 >     */
3584 >    public void forEachValueSequentially(Consumer<? super V> action) {
3585 >        if (action == null) throw new NullPointerException();
3586 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3587 >        V v;
3588 >        while ((v = it.advance()) != null)
3589 >            action.accept(v);
3590 >    }
3591 >
3592 >    /**
3593 >     * Performs the given action for each non-null transformation
3594 >     * of each value.
3595 >     *
3596 >     * @param transformer a function returning the transformation
3597 >     * for an element, or null if there is no transformation (in
3598 >     * which case the action is not applied)
3599 >     * @param action the action
3600 >     */
3601 >    public <U> void forEachValueSequentially
3602 >        (Function<? super V, ? extends U> transformer,
3603 >         Consumer<? super U> action) {
3604 >        if (transformer == null || action == null)
3605 >            throw new NullPointerException();
3606 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3607 >        V v; U u;
3608 >        while ((v = it.advance()) != null) {
3609 >            if ((u = transformer.apply(v)) != null)
3610 >                action.accept(u);
3611 >        }
3612 >    }
3613 >
3614 >    /**
3615 >     * Returns a non-null result from applying the given search
3616 >     * function on each value, or null if none.
3617 >     *
3618 >     * @param searchFunction a function returning a non-null
3619 >     * result on success, else null
3620 >     * @return a non-null result from applying the given search
3621 >     * function on each value, or null if none
3622 >     */
3623 >    public <U> U searchValuesSequentially
3624 >        (Function<? super V, ? extends U> searchFunction) {
3625 >        if (searchFunction == null) throw new NullPointerException();
3626 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3627 >        V v; U u;
3628 >        while ((v = it.advance()) != null) {
3629 >            if ((u = searchFunction.apply(v)) != null)
3630 >                return u;
3631 >        }
3632 >        return null;
3633 >    }
3634 >
3635 >    /**
3636 >     * Returns the result of accumulating all values using the
3637 >     * given reducer to combine values, or null if none.
3638 >     *
3639 >     * @param reducer a commutative associative combining function
3640 >     * @return the result of accumulating all values
3641 >     */
3642 >    public V reduceValuesSequentially
3643 >        (BiFunction<? super V, ? super V, ? extends V> reducer) {
3644 >        if (reducer == null) throw new NullPointerException();
3645 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3646 >        V r = null; V v;
3647 >        while ((v = it.advance()) != null)
3648 >            r = (r == null) ? v : reducer.apply(r, v);
3649 >        return r;
3650 >    }
3651 >
3652 >    /**
3653 >     * Returns the result of accumulating the given transformation
3654 >     * of all values using the given reducer to combine values, or
3655 >     * null if none.
3656 >     *
3657 >     * @param transformer a function returning the transformation
3658 >     * for an element, or null if there is no transformation (in
3659 >     * which case it is not combined)
3660 >     * @param reducer a commutative associative combining function
3661 >     * @return the result of accumulating the given transformation
3662 >     * of all values
3663 >     */
3664 >    public <U> U reduceValuesSequentially
3665 >        (Function<? super V, ? extends U> transformer,
3666 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3667 >        if (transformer == null || reducer == null)
3668 >            throw new NullPointerException();
3669 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3670 >        U r = null, u; V v;
3671 >        while ((v = it.advance()) != null) {
3672 >            if ((u = transformer.apply(v)) != null)
3673 >                r = (r == null) ? u : reducer.apply(r, u);
3674 >        }
3675 >        return r;
3676 >    }
3677 >
3678 >    /**
3679 >     * Returns the result of accumulating the given transformation
3680 >     * of all values using the given reducer to combine values,
3681 >     * and the given basis as an identity value.
3682 >     *
3683 >     * @param transformer a function returning the transformation
3684 >     * for an element
3685 >     * @param basis the identity (initial default value) for the reduction
3686 >     * @param reducer a commutative associative combining function
3687 >     * @return the result of accumulating the given transformation
3688 >     * of all values
3689 >     */
3690 >    public double reduceValuesToDoubleSequentially
3691 >        (ToDoubleFunction<? super V> transformer,
3692 >         double basis,
3693 >         DoubleBinaryOperator reducer) {
3694 >        if (transformer == null || reducer == null)
3695 >            throw new NullPointerException();
3696 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3697 >        double r = basis; V v;
3698 >        while ((v = it.advance()) != null)
3699 >            r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
3700 >        return r;
3701 >    }
3702 >
3703 >    /**
3704 >     * Returns the result of accumulating the given transformation
3705 >     * of all values using the given reducer to combine values,
3706 >     * and the given basis as an identity value.
3707 >     *
3708 >     * @param transformer a function returning the transformation
3709 >     * for an element
3710 >     * @param basis the identity (initial default value) for the reduction
3711 >     * @param reducer a commutative associative combining function
3712 >     * @return the result of accumulating the given transformation
3713 >     * of all values
3714 >     */
3715 >    public long reduceValuesToLongSequentially
3716 >        (ToLongFunction<? super V> transformer,
3717 >         long basis,
3718 >         LongBinaryOperator reducer) {
3719 >        if (transformer == null || reducer == null)
3720 >            throw new NullPointerException();
3721 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3722 >        long r = basis; V v;
3723 >        while ((v = it.advance()) != null)
3724 >            r = reducer.applyAsLong(r, transformer.applyAsLong(v));
3725 >        return r;
3726 >    }
3727 >
3728 >    /**
3729 >     * Returns the result of accumulating the given transformation
3730 >     * of all values using the given reducer to combine values,
3731 >     * and the given basis as an identity value.
3732 >     *
3733 >     * @param transformer a function returning the transformation
3734 >     * for an element
3735 >     * @param basis the identity (initial default value) for the reduction
3736 >     * @param reducer a commutative associative combining function
3737 >     * @return the result of accumulating the given transformation
3738 >     * of all values
3739 >     */
3740 >    public int reduceValuesToIntSequentially
3741 >        (ToIntFunction<? super V> transformer,
3742 >         int basis,
3743 >         IntBinaryOperator reducer) {
3744 >        if (transformer == null || reducer == null)
3745 >            throw new NullPointerException();
3746 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3747 >        int r = basis; V v;
3748 >        while ((v = it.advance()) != null)
3749 >            r = reducer.applyAsInt(r, transformer.applyAsInt(v));
3750 >        return r;
3751 >    }
3752 >
3753 >    /**
3754 >     * Performs the given action for each entry.
3755 >     *
3756 >     * @param action the action
3757 >     */
3758 >    public void forEachEntrySequentially
3759 >        (Consumer<? super Map.Entry<K,V>> action) {
3760 >        if (action == null) throw new NullPointerException();
3761 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3762 >        V v;
3763 >        while ((v = it.advance()) != null)
3764 >            action.accept(entryFor(it.nextKey, v));
3765 >    }
3766 >
3767 >    /**
3768 >     * Performs the given action for each non-null transformation
3769 >     * of each entry.
3770 >     *
3771 >     * @param transformer a function returning the transformation
3772 >     * for an element, or null if there is no transformation (in
3773 >     * which case the action is not applied)
3774 >     * @param action the action
3775 >     */
3776 >    public <U> void forEachEntrySequentially
3777 >        (Function<Map.Entry<K,V>, ? extends U> transformer,
3778 >         Consumer<? super U> action) {
3779 >        if (transformer == null || action == null)
3780 >            throw new NullPointerException();
3781 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3782 >        V v; U u;
3783 >        while ((v = it.advance()) != null) {
3784 >            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3785 >                action.accept(u);
3786 >        }
3787 >    }
3788 >
3789 >    /**
3790 >     * Returns a non-null result from applying the given search
3791 >     * function on each entry, or null if none.
3792 >     *
3793 >     * @param searchFunction a function returning a non-null
3794 >     * result on success, else null
3795 >     * @return a non-null result from applying the given search
3796 >     * function on each entry, or null if none
3797 >     */
3798 >    public <U> U searchEntriesSequentially
3799 >        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
3800 >        if (searchFunction == null) throw new NullPointerException();
3801 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3802 >        V v; U u;
3803 >        while ((v = it.advance()) != null) {
3804 >            if ((u = searchFunction.apply(entryFor(it.nextKey, v))) != null)
3805 >                return u;
3806 >        }
3807 >        return null;
3808 >    }
3809 >
3810 >    /**
3811 >     * Returns the result of accumulating all entries using the
3812 >     * given reducer to combine values, or null if none.
3813 >     *
3814 >     * @param reducer a commutative associative combining function
3815 >     * @return the result of accumulating all entries
3816 >     */
3817 >    public Map.Entry<K,V> reduceEntriesSequentially
3818 >        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3819 >        if (reducer == null) throw new NullPointerException();
3820 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3821 >        Map.Entry<K,V> r = null; V v;
3822 >        while ((v = it.advance()) != null) {
3823 >            Map.Entry<K,V> u = entryFor(it.nextKey, v);
3824 >            r = (r == null) ? u : reducer.apply(r, u);
3825 >        }
3826 >        return r;
3827 >    }
3828 >
3829 >    /**
3830 >     * Returns the result of accumulating the given transformation
3831 >     * of all entries using the given reducer to combine values,
3832 >     * or null if none.
3833 >     *
3834 >     * @param transformer a function returning the transformation
3835 >     * for an element, or null if there is no transformation (in
3836 >     * which case it is not combined)
3837 >     * @param reducer a commutative associative combining function
3838 >     * @return the result of accumulating the given transformation
3839 >     * of all entries
3840 >     */
3841 >    public <U> U reduceEntriesSequentially
3842 >        (Function<Map.Entry<K,V>, ? extends U> transformer,
3843 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3844 >        if (transformer == null || reducer == null)
3845 >            throw new NullPointerException();
3846 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3847 >        U r = null, u; V v;
3848 >        while ((v = it.advance()) != null) {
3849 >            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3850 >                r = (r == null) ? u : reducer.apply(r, u);
3851 >        }
3852 >        return r;
3853 >    }
3854 >
3855 >    /**
3856 >     * Returns the result of accumulating the given transformation
3857 >     * of all entries using the given reducer to combine values,
3858 >     * and the given basis as an identity value.
3859 >     *
3860 >     * @param transformer a function returning the transformation
3861 >     * for an element
3862 >     * @param basis the identity (initial default value) for the reduction
3863 >     * @param reducer a commutative associative combining function
3864 >     * @return the result of accumulating the given transformation
3865 >     * of all entries
3866 >     */
3867 >    public double reduceEntriesToDoubleSequentially
3868 >        (ToDoubleFunction<Map.Entry<K,V>> transformer,
3869 >         double basis,
3870 >         DoubleBinaryOperator reducer) {
3871 >        if (transformer == null || reducer == null)
3872 >            throw new NullPointerException();
3873 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3874 >        double r = basis; V v;
3875 >        while ((v = it.advance()) != null)
3876 >            r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(it.nextKey, v)));
3877 >        return r;
3878 >    }
3879 >
3880 >    /**
3881 >     * Returns the result of accumulating the given transformation
3882 >     * of all entries using the given reducer to combine values,
3883 >     * and the given basis as an identity value.
3884 >     *
3885 >     * @param transformer a function returning the transformation
3886 >     * for an element
3887 >     * @param basis the identity (initial default value) for the reduction
3888 >     * @param reducer a commutative associative combining function
3889 >     * @return the result of accumulating the given transformation
3890 >     * of all entries
3891 >     */
3892 >    public long reduceEntriesToLongSequentially
3893 >        (ToLongFunction<Map.Entry<K,V>> transformer,
3894 >         long basis,
3895 >         LongBinaryOperator reducer) {
3896 >        if (transformer == null || reducer == null)
3897 >            throw new NullPointerException();
3898 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3899 >        long r = basis; V v;
3900 >        while ((v = it.advance()) != null)
3901 >            r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(it.nextKey, v)));
3902 >        return r;
3903 >    }
3904 >
3905 >    /**
3906 >     * Returns the result of accumulating the given transformation
3907 >     * of all entries using the given reducer to combine values,
3908 >     * and the given basis as an identity value.
3909 >     *
3910 >     * @param transformer a function returning the transformation
3911 >     * for an element
3912 >     * @param basis the identity (initial default value) for the reduction
3913 >     * @param reducer a commutative associative combining function
3914 >     * @return the result of accumulating the given transformation
3915 >     * of all entries
3916 >     */
3917 >    public int reduceEntriesToIntSequentially
3918 >        (ToIntFunction<Map.Entry<K,V>> transformer,
3919 >         int basis,
3920 >         IntBinaryOperator reducer) {
3921 >        if (transformer == null || reducer == null)
3922 >            throw new NullPointerException();
3923 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3924 >        int r = basis; V v;
3925 >        while ((v = it.advance()) != null)
3926 >            r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(it.nextKey, v)));
3927 >        return r;
3928 >    }
3929 >
3930 >    // Parallel bulk operations
3931  
3932      /**
3933       * Performs the given action for each (key, value).
3934       *
3935       * @param action the action
3936       */
3937 <    public void forEach(BiAction<K,V> action) {
3937 >    public void forEachInParallel(BiConsumer<? super K,? super V> action) {
3938          ForkJoinTasks.forEach
3939              (this, action).invoke();
3940      }
# Line 3464 | Line 3944 | public class ConcurrentHashMap<K, V>
3944       * of each (key, value).
3945       *
3946       * @param transformer a function returning the transformation
3947 <     * for an element, or null of there is no transformation (in
3948 <     * which case the action is not applied).
3947 >     * for an element, or null if there is no transformation (in
3948 >     * which case the action is not applied)
3949       * @param action the action
3950       */
3951 <    public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3952 <                            Action<U> action) {
3951 >    public <U> void forEachInParallel
3952 >        (BiFunction<? super K, ? super V, ? extends U> transformer,
3953 >                            Consumer<? super U> action) {
3954          ForkJoinTasks.forEach
3955              (this, transformer, action).invoke();
3956      }
# Line 3486 | Line 3967 | public class ConcurrentHashMap<K, V>
3967       * @return a non-null result from applying the given search
3968       * function on each (key, value), or null if none
3969       */
3970 <    public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3970 >    public <U> U searchInParallel
3971 >        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3972          return ForkJoinTasks.search
3973              (this, searchFunction).invoke();
3974      }
# Line 3497 | Line 3979 | public class ConcurrentHashMap<K, V>
3979       * combine values, or null if none.
3980       *
3981       * @param transformer a function returning the transformation
3982 <     * for an element, or null of there is no transformation (in
3983 <     * which case it is not combined).
3982 >     * for an element, or null if there is no transformation (in
3983 >     * which case it is not combined)
3984       * @param reducer a commutative associative combining function
3985       * @return the result of accumulating the given transformation
3986       * of all (key, value) pairs
3987       */
3988 <    public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3989 <                        BiFun<? super U, ? super U, ? extends U> reducer) {
3988 >    public <U> U reduceInParallel
3989 >        (BiFunction<? super K, ? super V, ? extends U> transformer,
3990 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3991          return ForkJoinTasks.reduce
3992              (this, transformer, reducer).invoke();
3993      }
# Line 3521 | Line 4004 | public class ConcurrentHashMap<K, V>
4004       * @return the result of accumulating the given transformation
4005       * of all (key, value) pairs
4006       */
4007 <    public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
4008 <                                 double basis,
4009 <                                 DoubleByDoubleToDouble reducer) {
4007 >    public double reduceToDoubleInParallel
4008 >        (ToDoubleBiFunction<? super K, ? super V> transformer,
4009 >         double basis,
4010 >         DoubleBinaryOperator reducer) {
4011          return ForkJoinTasks.reduceToDouble
4012              (this, transformer, basis, reducer).invoke();
4013      }
# Line 3540 | Line 4024 | public class ConcurrentHashMap<K, V>
4024       * @return the result of accumulating the given transformation
4025       * of all (key, value) pairs
4026       */
4027 <    public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
4028 <                             long basis,
4029 <                             LongByLongToLong reducer) {
4027 >    public long reduceToLongInParallel
4028 >        (ToLongBiFunction<? super K, ? super V> transformer,
4029 >         long basis,
4030 >         LongBinaryOperator reducer) {
4031          return ForkJoinTasks.reduceToLong
4032              (this, transformer, basis, reducer).invoke();
4033      }
# Line 3559 | Line 4044 | public class ConcurrentHashMap<K, V>
4044       * @return the result of accumulating the given transformation
4045       * of all (key, value) pairs
4046       */
4047 <    public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
4048 <                           int basis,
4049 <                           IntByIntToInt reducer) {
4047 >    public int reduceToIntInParallel
4048 >        (ToIntBiFunction<? super K, ? super V> transformer,
4049 >         int basis,
4050 >         IntBinaryOperator reducer) {
4051          return ForkJoinTasks.reduceToInt
4052              (this, transformer, basis, reducer).invoke();
4053      }
# Line 3571 | Line 4057 | public class ConcurrentHashMap<K, V>
4057       *
4058       * @param action the action
4059       */
4060 <    public void forEachKey(Action<K> action) {
4060 >    public void forEachKeyInParallel(Consumer<? super K> action) {
4061          ForkJoinTasks.forEachKey
4062              (this, action).invoke();
4063      }
# Line 3581 | Line 4067 | public class ConcurrentHashMap<K, V>
4067       * of each key.
4068       *
4069       * @param transformer a function returning the transformation
4070 <     * for an element, or null of there is no transformation (in
4071 <     * which case the action is not applied).
4070 >     * for an element, or null if there is no transformation (in
4071 >     * which case the action is not applied)
4072       * @param action the action
4073       */
4074 <    public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
4075 <                               Action<U> action) {
4074 >    public <U> void forEachKeyInParallel
4075 >        (Function<? super K, ? extends U> transformer,
4076 >         Consumer<? super U> action) {
4077          ForkJoinTasks.forEachKey
4078              (this, transformer, action).invoke();
4079      }
# Line 3603 | Line 4090 | public class ConcurrentHashMap<K, V>
4090       * @return a non-null result from applying the given search
4091       * function on each key, or null if none
4092       */
4093 <    public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
4093 >    public <U> U searchKeysInParallel
4094 >        (Function<? super K, ? extends U> searchFunction) {
4095          return ForkJoinTasks.searchKeys
4096              (this, searchFunction).invoke();
4097      }
# Line 3616 | Line 4104 | public class ConcurrentHashMap<K, V>
4104       * @return the result of accumulating all keys using the given
4105       * reducer to combine values, or null if none
4106       */
4107 <    public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
4107 >    public K reduceKeysInParallel
4108 >        (BiFunction<? super K, ? super K, ? extends K> reducer) {
4109          return ForkJoinTasks.reduceKeys
4110              (this, reducer).invoke();
4111      }
# Line 3627 | Line 4116 | public class ConcurrentHashMap<K, V>
4116       * null if none.
4117       *
4118       * @param transformer a function returning the transformation
4119 <     * for an element, or null of there is no transformation (in
4120 <     * which case it is not combined).
4119 >     * for an element, or null if there is no transformation (in
4120 >     * which case it is not combined)
4121       * @param reducer a commutative associative combining function
4122       * @return the result of accumulating the given transformation
4123       * of all keys
4124       */
4125 <    public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
4126 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
4125 >    public <U> U reduceKeysInParallel
4126 >        (Function<? super K, ? extends U> transformer,
4127 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
4128          return ForkJoinTasks.reduceKeys
4129              (this, transformer, reducer).invoke();
4130      }
# Line 3648 | Line 4138 | public class ConcurrentHashMap<K, V>
4138       * for an element
4139       * @param basis the identity (initial default value) for the reduction
4140       * @param reducer a commutative associative combining function
4141 <     * @return  the result of accumulating the given transformation
4141 >     * @return the result of accumulating the given transformation
4142       * of all keys
4143       */
4144 <    public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
4145 <                                     double basis,
4146 <                                     DoubleByDoubleToDouble reducer) {
4144 >    public double reduceKeysToDoubleInParallel
4145 >        (ToDoubleFunction<? super K> transformer,
4146 >         double basis,
4147 >         DoubleBinaryOperator reducer) {
4148          return ForkJoinTasks.reduceKeysToDouble
4149              (this, transformer, basis, reducer).invoke();
4150      }
# Line 3670 | Line 4161 | public class ConcurrentHashMap<K, V>
4161       * @return the result of accumulating the given transformation
4162       * of all keys
4163       */
4164 <    public long reduceKeysToLong(ObjectToLong<? super K> transformer,
4165 <                                 long basis,
4166 <                                 LongByLongToLong reducer) {
4164 >    public long reduceKeysToLongInParallel
4165 >        (ToLongFunction<? super K> transformer,
4166 >         long basis,
4167 >         LongBinaryOperator reducer) {
4168          return ForkJoinTasks.reduceKeysToLong
4169              (this, transformer, basis, reducer).invoke();
4170      }
# Line 3689 | Line 4181 | public class ConcurrentHashMap<K, V>
4181       * @return the result of accumulating the given transformation
4182       * of all keys
4183       */
4184 <    public int reduceKeysToInt(ObjectToInt<? super K> transformer,
4185 <                               int basis,
4186 <                               IntByIntToInt reducer) {
4184 >    public int reduceKeysToIntInParallel
4185 >        (ToIntFunction<? super K> transformer,
4186 >         int basis,
4187 >         IntBinaryOperator reducer) {
4188          return ForkJoinTasks.reduceKeysToInt
4189              (this, transformer, basis, reducer).invoke();
4190      }
# Line 3701 | Line 4194 | public class ConcurrentHashMap<K, V>
4194       *
4195       * @param action the action
4196       */
4197 <    public void forEachValue(Action<V> action) {
4197 >    public void forEachValueInParallel(Consumer<? super V> action) {
4198          ForkJoinTasks.forEachValue
4199              (this, action).invoke();
4200      }
# Line 3711 | Line 4204 | public class ConcurrentHashMap<K, V>
4204       * of each value.
4205       *
4206       * @param transformer a function returning the transformation
4207 <     * for an element, or null of there is no transformation (in
4208 <     * which case the action is not applied).
4207 >     * for an element, or null if there is no transformation (in
4208 >     * which case the action is not applied)
4209 >     * @param action the action
4210       */
4211 <    public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
4212 <                                 Action<U> action) {
4211 >    public <U> void forEachValueInParallel
4212 >        (Function<? super V, ? extends U> transformer,
4213 >         Consumer<? super U> action) {
4214          ForkJoinTasks.forEachValue
4215              (this, transformer, action).invoke();
4216      }
# Line 3731 | Line 4226 | public class ConcurrentHashMap<K, V>
4226       * result on success, else null
4227       * @return a non-null result from applying the given search
4228       * function on each value, or null if none
3734     *
4229       */
4230 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
4230 >    public <U> U searchValuesInParallel
4231 >        (Function<? super V, ? extends U> searchFunction) {
4232          return ForkJoinTasks.searchValues
4233              (this, searchFunction).invoke();
4234      }
# Line 3743 | Line 4238 | public class ConcurrentHashMap<K, V>
4238       * given reducer to combine values, or null if none.
4239       *
4240       * @param reducer a commutative associative combining function
4241 <     * @return  the result of accumulating all values
4241 >     * @return the result of accumulating all values
4242       */
4243 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
4243 >    public V reduceValuesInParallel
4244 >        (BiFunction<? super V, ? super V, ? extends V> reducer) {
4245          return ForkJoinTasks.reduceValues
4246              (this, reducer).invoke();
4247      }
# Line 3756 | Line 4252 | public class ConcurrentHashMap<K, V>
4252       * null if none.
4253       *
4254       * @param transformer a function returning the transformation
4255 <     * for an element, or null of there is no transformation (in
4256 <     * which case it is not combined).
4255 >     * for an element, or null if there is no transformation (in
4256 >     * which case it is not combined)
4257       * @param reducer a commutative associative combining function
4258       * @return the result of accumulating the given transformation
4259       * of all values
4260       */
4261 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
4262 <                              BiFun<? super U, ? super U, ? extends U> reducer) {
4261 >    public <U> U reduceValuesInParallel
4262 >        (Function<? super V, ? extends U> transformer,
4263 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
4264          return ForkJoinTasks.reduceValues
4265              (this, transformer, reducer).invoke();
4266      }
# Line 3780 | Line 4277 | public class ConcurrentHashMap<K, V>
4277       * @return the result of accumulating the given transformation
4278       * of all values
4279       */
4280 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
4281 <                                       double basis,
4282 <                                       DoubleByDoubleToDouble reducer) {
4280 >    public double reduceValuesToDoubleInParallel
4281 >        (ToDoubleFunction<? super V> transformer,
4282 >         double basis,
4283 >         DoubleBinaryOperator reducer) {
4284          return ForkJoinTasks.reduceValuesToDouble
4285              (this, transformer, basis, reducer).invoke();
4286      }
# Line 3799 | Line 4297 | public class ConcurrentHashMap<K, V>
4297       * @return the result of accumulating the given transformation
4298       * of all values
4299       */
4300 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
4301 <                                   long basis,
4302 <                                   LongByLongToLong reducer) {
4300 >    public long reduceValuesToLongInParallel
4301 >        (ToLongFunction<? super V> transformer,
4302 >         long basis,
4303 >         LongBinaryOperator reducer) {
4304          return ForkJoinTasks.reduceValuesToLong
4305              (this, transformer, basis, reducer).invoke();
4306      }
# Line 3818 | Line 4317 | public class ConcurrentHashMap<K, V>
4317       * @return the result of accumulating the given transformation
4318       * of all values
4319       */
4320 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4321 <                                 int basis,
4322 <                                 IntByIntToInt reducer) {
4320 >    public int reduceValuesToIntInParallel
4321 >        (ToIntFunction<? super V> transformer,
4322 >         int basis,
4323 >         IntBinaryOperator reducer) {
4324          return ForkJoinTasks.reduceValuesToInt
4325              (this, transformer, basis, reducer).invoke();
4326      }
# Line 3830 | Line 4330 | public class ConcurrentHashMap<K, V>
4330       *
4331       * @param action the action
4332       */
4333 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
4333 >    public void forEachEntryInParallel(Consumer<? super Map.Entry<K,V>> action) {
4334          ForkJoinTasks.forEachEntry
4335              (this, action).invoke();
4336      }
# Line 3840 | Line 4340 | public class ConcurrentHashMap<K, V>
4340       * of each entry.
4341       *
4342       * @param transformer a function returning the transformation
4343 <     * for an element, or null of there is no transformation (in
4344 <     * which case the action is not applied).
4343 >     * for an element, or null if there is no transformation (in
4344 >     * which case the action is not applied)
4345       * @param action the action
4346       */
4347 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4348 <                                 Action<U> action) {
4347 >    public <U> void forEachEntryInParallel
4348 >        (Function<Map.Entry<K,V>, ? extends U> transformer,
4349 >         Consumer<? super U> action) {
4350          ForkJoinTasks.forEachEntry
4351              (this, transformer, action).invoke();
4352      }
# Line 3862 | Line 4363 | public class ConcurrentHashMap<K, V>
4363       * @return a non-null result from applying the given search
4364       * function on each entry, or null if none
4365       */
4366 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4366 >    public <U> U searchEntriesInParallel
4367 >        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4368          return ForkJoinTasks.searchEntries
4369              (this, searchFunction).invoke();
4370      }
# Line 3874 | Line 4376 | public class ConcurrentHashMap<K, V>
4376       * @param reducer a commutative associative combining function
4377       * @return the result of accumulating all entries
4378       */
4379 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4379 >    public Map.Entry<K,V> reduceEntriesInParallel
4380 >        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4381          return ForkJoinTasks.reduceEntries
4382              (this, reducer).invoke();
4383      }
# Line 3885 | Line 4388 | public class ConcurrentHashMap<K, V>
4388       * or null if none.
4389       *
4390       * @param transformer a function returning the transformation
4391 <     * for an element, or null of there is no transformation (in
4392 <     * which case it is not combined).
4391 >     * for an element, or null if there is no transformation (in
4392 >     * which case it is not combined)
4393       * @param reducer a commutative associative combining function
4394       * @return the result of accumulating the given transformation
4395       * of all entries
4396       */
4397 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4398 <                               BiFun<? super U, ? super U, ? extends U> reducer) {
4397 >    public <U> U reduceEntriesInParallel
4398 >        (Function<Map.Entry<K,V>, ? extends U> transformer,
4399 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
4400          return ForkJoinTasks.reduceEntries
4401              (this, transformer, reducer).invoke();
4402      }
# Line 3909 | Line 4413 | public class ConcurrentHashMap<K, V>
4413       * @return the result of accumulating the given transformation
4414       * of all entries
4415       */
4416 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4417 <                                        double basis,
4418 <                                        DoubleByDoubleToDouble reducer) {
4416 >    public double reduceEntriesToDoubleInParallel
4417 >        (ToDoubleFunction<Map.Entry<K,V>> transformer,
4418 >         double basis,
4419 >         DoubleBinaryOperator reducer) {
4420          return ForkJoinTasks.reduceEntriesToDouble
4421              (this, transformer, basis, reducer).invoke();
4422      }
# Line 3925 | Line 4430 | public class ConcurrentHashMap<K, V>
4430       * for an element
4431       * @param basis the identity (initial default value) for the reduction
4432       * @param reducer a commutative associative combining function
4433 <     * @return  the result of accumulating the given transformation
4433 >     * @return the result of accumulating the given transformation
4434       * of all entries
4435       */
4436 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4437 <                                    long basis,
4438 <                                    LongByLongToLong reducer) {
4436 >    public long reduceEntriesToLongInParallel
4437 >        (ToLongFunction<Map.Entry<K,V>> transformer,
4438 >         long basis,
4439 >         LongBinaryOperator reducer) {
4440          return ForkJoinTasks.reduceEntriesToLong
4441              (this, transformer, basis, reducer).invoke();
4442      }
# Line 3947 | Line 4453 | public class ConcurrentHashMap<K, V>
4453       * @return the result of accumulating the given transformation
4454       * of all entries
4455       */
4456 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4457 <                                  int basis,
4458 <                                  IntByIntToInt reducer) {
4456 >    public int reduceEntriesToIntInParallel
4457 >        (ToIntFunction<Map.Entry<K,V>> transformer,
4458 >         int basis,
4459 >         IntBinaryOperator reducer) {
4460          return ForkJoinTasks.reduceEntriesToInt
4461              (this, transformer, basis, reducer).invoke();
4462      }
4463  
4464 +
4465      /* ----------------Views -------------- */
4466  
4467      /**
4468       * Base class for views.
4469       */
4470 <    static abstract class CHMView<K, V> {
4471 <        final ConcurrentHashMap<K, V> map;
4472 <        CHMView(ConcurrentHashMap<K, V> map)  { this.map = map; }
4470 >    abstract static class CHMCollectionView<K,V,E>
4471 >            implements Collection<E>, java.io.Serializable {
4472 >        private static final long serialVersionUID = 7249069246763182397L;
4473 >        final ConcurrentHashMap<K,V> map;
4474 >        CHMCollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4475  
4476          /**
4477           * Returns the map backing this view.
# Line 3970 | Line 4480 | public class ConcurrentHashMap<K, V>
4480           */
4481          public ConcurrentHashMap<K,V> getMap() { return map; }
4482  
4483 <        public final int size()                 { return map.size(); }
4484 <        public final boolean isEmpty()          { return map.isEmpty(); }
4485 <        public final void clear()               { map.clear(); }
4483 >        /**
4484 >         * Removes all of the elements from this view, by removing all
4485 >         * the mappings from the map backing this view.
4486 >         */
4487 >        public final void clear()      { map.clear(); }
4488 >        public final int size()        { return map.size(); }
4489 >        public final boolean isEmpty() { return map.isEmpty(); }
4490  
4491          // implementations below rely on concrete classes supplying these
4492 <        abstract public Iterator<?> iterator();
4493 <        abstract public boolean contains(Object o);
4494 <        abstract public boolean remove(Object o);
4492 >        // abstract methods
4493 >        /**
4494 >         * Returns a "weakly consistent" iterator that will never
4495 >         * throw {@link ConcurrentModificationException}, and
4496 >         * guarantees to traverse elements as they existed upon
4497 >         * construction of the iterator, and may (but is not
4498 >         * guaranteed to) reflect any modifications subsequent to
4499 >         * construction.
4500 >         */
4501 >        public abstract Iterator<E> iterator();
4502 >        public abstract boolean contains(Object o);
4503 >        public abstract boolean remove(Object o);
4504  
4505          private static final String oomeMsg = "Required array size too large";
4506  
4507          public final Object[] toArray() {
4508              long sz = map.mappingCount();
4509 <            if (sz > (long)(MAX_ARRAY_SIZE))
4509 >            if (sz > MAX_ARRAY_SIZE)
4510                  throw new OutOfMemoryError(oomeMsg);
4511              int n = (int)sz;
4512              Object[] r = new Object[n];
4513              int i = 0;
4514 <            Iterator<?> it = iterator();
3992 <            while (it.hasNext()) {
4514 >            for (E e : this) {
4515                  if (i == n) {
4516                      if (n >= MAX_ARRAY_SIZE)
4517                          throw new OutOfMemoryError(oomeMsg);
# Line 3999 | Line 4521 | public class ConcurrentHashMap<K, V>
4521                          n += (n >>> 1) + 1;
4522                      r = Arrays.copyOf(r, n);
4523                  }
4524 <                r[i++] = it.next();
4524 >                r[i++] = e;
4525              }
4526              return (i == n) ? r : Arrays.copyOf(r, i);
4527          }
4528  
4529 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4529 >        @SuppressWarnings("unchecked")
4530 >        public final <T> T[] toArray(T[] a) {
4531              long sz = map.mappingCount();
4532 <            if (sz > (long)(MAX_ARRAY_SIZE))
4532 >            if (sz > MAX_ARRAY_SIZE)
4533                  throw new OutOfMemoryError(oomeMsg);
4534              int m = (int)sz;
4535              T[] r = (a.length >= m) ? a :
# Line 4014 | Line 4537 | public class ConcurrentHashMap<K, V>
4537                  .newInstance(a.getClass().getComponentType(), m);
4538              int n = r.length;
4539              int i = 0;
4540 <            Iterator<?> it = iterator();
4018 <            while (it.hasNext()) {
4540 >            for (E e : this) {
4541                  if (i == n) {
4542                      if (n >= MAX_ARRAY_SIZE)
4543                          throw new OutOfMemoryError(oomeMsg);
# Line 4025 | Line 4547 | public class ConcurrentHashMap<K, V>
4547                          n += (n >>> 1) + 1;
4548                      r = Arrays.copyOf(r, n);
4549                  }
4550 <                r[i++] = (T)it.next();
4550 >                r[i++] = (T)e;
4551              }
4552              if (a == r && i < n) {
4553                  r[i] = null; // null-terminate
# Line 4034 | Line 4556 | public class ConcurrentHashMap<K, V>
4556              return (i == n) ? r : Arrays.copyOf(r, i);
4557          }
4558  
4559 <        public final int hashCode() {
4560 <            int h = 0;
4561 <            for (Iterator<?> it = iterator(); it.hasNext();)
4562 <                h += it.next().hashCode();
4563 <            return h;
4564 <        }
4565 <
4559 >        /**
4560 >         * Returns a string representation of this collection.
4561 >         * The string representation consists of the string representations
4562 >         * of the collection's elements in the order they are returned by
4563 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4564 >         * Adjacent elements are separated by the characters {@code ", "}
4565 >         * (comma and space).  Elements are converted to strings as by
4566 >         * {@link String#valueOf(Object)}.
4567 >         *
4568 >         * @return a string representation of this collection
4569 >         */
4570          public final String toString() {
4571              StringBuilder sb = new StringBuilder();
4572              sb.append('[');
4573 <            Iterator<?> it = iterator();
4573 >            Iterator<E> it = iterator();
4574              if (it.hasNext()) {
4575                  for (;;) {
4576                      Object e = it.next();
# Line 4059 | Line 4585 | public class ConcurrentHashMap<K, V>
4585  
4586          public final boolean containsAll(Collection<?> c) {
4587              if (c != this) {
4588 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4063 <                    Object e = it.next();
4588 >                for (Object e : c) {
4589                      if (e == null || !contains(e))
4590                          return false;
4591                  }
# Line 4070 | Line 4595 | public class ConcurrentHashMap<K, V>
4595  
4596          public final boolean removeAll(Collection<?> c) {
4597              boolean modified = false;
4598 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4598 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4599                  if (c.contains(it.next())) {
4600                      it.remove();
4601                      modified = true;
# Line 4081 | Line 4606 | public class ConcurrentHashMap<K, V>
4606  
4607          public final boolean retainAll(Collection<?> c) {
4608              boolean modified = false;
4609 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4609 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4610                  if (!c.contains(it.next())) {
4611                      it.remove();
4612                      modified = true;
# Line 4092 | Line 4617 | public class ConcurrentHashMap<K, V>
4617  
4618      }
4619  
4620 +    abstract static class CHMSetView<K,V,E>
4621 +            extends CHMCollectionView<K,V,E>
4622 +            implements Set<E>, java.io.Serializable {
4623 +        private static final long serialVersionUID = 7249069246763182397L;
4624 +        CHMSetView(ConcurrentHashMap<K,V> map) { super(map); }
4625 +
4626 +        // Implement Set API
4627 +
4628 +        /**
4629 +         * Implements {@link Set#hashCode()}.
4630 +         * @return the hash code value for this set
4631 +         */
4632 +        public final int hashCode() {
4633 +            int h = 0;
4634 +            for (E e : this)
4635 +                h += e.hashCode();
4636 +            return h;
4637 +        }
4638 +
4639 +        /**
4640 +         * Implements {@link Set#equals(Object)}.
4641 +         * @param o object to be compared for equality with this set
4642 +         * @return {@code true} if the specified object is equal to this set
4643 +        */
4644 +        public final boolean equals(Object o) {
4645 +            Set<?> c;
4646 +            return ((o instanceof Set) &&
4647 +                    ((c = (Set<?>)o) == this ||
4648 +                     (containsAll(c) && c.containsAll(this))));
4649 +        }
4650 +    }
4651 +
4652      /**
4653       * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4654       * which additions may optionally be enabled by mapping to a
4655 <     * common value.  This class cannot be directly instantiated. See
4656 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4657 <     * {@link #newKeySet(int)}.
4658 <     */
4659 <    public static class KeySetView<K,V> extends CHMView<K,V> implements Set<K>, java.io.Serializable {
4655 >     * common value.  This class cannot be directly instantiated.
4656 >     * See {@link #keySet() keySet()},
4657 >     * {@link #keySet(Object) keySet(V)},
4658 >     * {@link #newKeySet() newKeySet()},
4659 >     * {@link #newKeySet(int) newKeySet(int)}.
4660 >     */
4661 >    public static class KeySetView<K,V>
4662 >            extends CHMSetView<K,V,K>
4663 >            implements Set<K>, java.io.Serializable {
4664          private static final long serialVersionUID = 7249069246763182397L;
4665          private final V value;
4666 <        KeySetView(ConcurrentHashMap<K, V> map, V value) {  // non-public
4666 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4667              super(map);
4668              this.value = value;
4669          }
# Line 4112 | Line 4673 | public class ConcurrentHashMap<K, V>
4673           * or {@code null} if additions are not supported.
4674           *
4675           * @return the default mapped value for additions, or {@code null}
4676 <         * if not supported.
4676 >         * if not supported
4677           */
4678          public V getMappedValue() { return value; }
4679  
4680 <        // implement Set API
4681 <
4680 >        /**
4681 >         * {@inheritDoc}
4682 >         * @throws NullPointerException if the specified key is null
4683 >         */
4684          public boolean contains(Object o) { return map.containsKey(o); }
4122        public boolean remove(Object o)   { return map.remove(o) != null; }
4685  
4686          /**
4687 <         * Returns a "weakly consistent" iterator that will never
4688 <         * throw {@link ConcurrentModificationException}, and
4689 <         * guarantees to traverse elements as they existed upon
4690 <         * construction of the iterator, and may (but is not
4691 <         * guaranteed to) reflect any modifications subsequent to
4692 <         * construction.
4687 >         * Removes the key from this map view, by removing the key (and its
4688 >         * corresponding value) from the backing map.  This method does
4689 >         * nothing if the key is not in the map.
4690 >         *
4691 >         * @param  o the key to be removed from the backing map
4692 >         * @return {@code true} if the backing map contained the specified key
4693 >         * @throws NullPointerException if the specified key is null
4694 >         */
4695 >        public boolean remove(Object o) { return map.remove(o) != null; }
4696 >
4697 >        /**
4698 >         * @return an iterator over the keys of the backing map
4699 >         */
4700 >        public Iterator<K> iterator() { return new KeyIterator<K,V>(map); }
4701 >
4702 >        /**
4703 >         * Adds the specified key to this set view by mapping the key to
4704 >         * the default mapped value in the backing map, if defined.
4705           *
4706 <         * @return an iterator over the keys of this map
4706 >         * @param e key to be added
4707 >         * @return {@code true} if this set changed as a result of the call
4708 >         * @throws NullPointerException if the specified key is null
4709 >         * @throws UnsupportedOperationException if no default mapped value
4710 >         * for additions was provided
4711           */
4134        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4712          public boolean add(K e) {
4713              V v;
4714              if ((v = value) == null)
4715                  throw new UnsupportedOperationException();
4716 <            if (e == null)
4140 <                throw new NullPointerException();
4141 <            return map.internalPutIfAbsent(e, v) == null;
4716 >            return map.internalPut(e, v, true) == null;
4717          }
4718 +
4719 +        /**
4720 +         * Adds all of the elements in the specified collection to this set,
4721 +         * as if by calling {@link #add} on each one.
4722 +         *
4723 +         * @param c the elements to be inserted into this set
4724 +         * @return {@code true} if this set changed as a result of the call
4725 +         * @throws NullPointerException if the collection or any of its
4726 +         * elements are {@code null}
4727 +         * @throws UnsupportedOperationException if no default mapped value
4728 +         * for additions was provided
4729 +         */
4730          public boolean addAll(Collection<? extends K> c) {
4731              boolean added = false;
4732              V v;
4733              if ((v = value) == null)
4734                  throw new UnsupportedOperationException();
4735              for (K e : c) {
4736 <                if (e == null)
4150 <                    throw new NullPointerException();
4151 <                if (map.internalPutIfAbsent(e, v) == null)
4736 >                if (map.internalPut(e, v, true) == null)
4737                      added = true;
4738              }
4739              return added;
4740          }
4156        public boolean equals(Object o) {
4157            Set<?> c;
4158            return ((o instanceof Set) &&
4159                    ((c = (Set<?>)o) == this ||
4160                     (containsAll(c) && c.containsAll(this))));
4161        }
4162
4163        /**
4164         * Performs the given action for each key.
4165         *
4166         * @param action the action
4167         */
4168        public void forEach(Action<K> action) {
4169            ForkJoinTasks.forEachKey
4170                (map, action).invoke();
4171        }
4172
4173        /**
4174         * Performs the given action for each non-null transformation
4175         * of each key.
4176         *
4177         * @param transformer a function returning the transformation
4178         * for an element, or null of there is no transformation (in
4179         * which case the action is not applied).
4180         * @param action the action
4181         */
4182        public <U> void forEach(Fun<? super K, ? extends U> transformer,
4183                                Action<U> action) {
4184            ForkJoinTasks.forEachKey
4185                (map, transformer, action).invoke();
4186        }
4187
4188        /**
4189         * Returns a non-null result from applying the given search
4190         * function on each key, or null if none. Upon success,
4191         * further element processing is suppressed and the results of
4192         * any other parallel invocations of the search function are
4193         * ignored.
4194         *
4195         * @param searchFunction a function returning a non-null
4196         * result on success, else null
4197         * @return a non-null result from applying the given search
4198         * function on each key, or null if none
4199         */
4200        public <U> U search(Fun<? super K, ? extends U> searchFunction) {
4201            return ForkJoinTasks.searchKeys
4202                (map, searchFunction).invoke();
4203        }
4204
4205        /**
4206         * Returns the result of accumulating all keys using the given
4207         * reducer to combine values, or null if none.
4208         *
4209         * @param reducer a commutative associative combining function
4210         * @return the result of accumulating all keys using the given
4211         * reducer to combine values, or null if none
4212         */
4213        public K reduce(BiFun<? super K, ? super K, ? extends K> reducer) {
4214            return ForkJoinTasks.reduceKeys
4215                (map, reducer).invoke();
4216        }
4217
4218        /**
4219         * Returns the result of accumulating the given transformation
4220         * of all keys using the given reducer to combine values, and
4221         * the given basis as an identity value.
4222         *
4223         * @param transformer a function returning the transformation
4224         * for an element
4225         * @param basis the identity (initial default value) for the reduction
4226         * @param reducer a commutative associative combining function
4227         * @return  the result of accumulating the given transformation
4228         * of all keys
4229         */
4230        public double reduceToDouble(ObjectToDouble<? super K> transformer,
4231                                     double basis,
4232                                     DoubleByDoubleToDouble reducer) {
4233            return ForkJoinTasks.reduceKeysToDouble
4234                (map, transformer, basis, reducer).invoke();
4235        }
4236
4741  
4742 <        /**
4743 <         * 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();
4742 >        public Stream<K> stream() {
4743 >            return Streams.stream(new KeyIterator<>(map, null));
4744          }
4745 <
4746 <        /**
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();
4745 >        public Stream<K> parallelStream() {
4746 >            return Streams.parallelStream(new KeyIterator<K,V>(map, null));
4747          }
4275
4748      }
4749  
4750      /**
4751       * A view of a ConcurrentHashMap as a {@link Collection} of
4752       * values, in which additions are disabled. This class cannot be
4753 <     * directly instantiated. See {@link #values},
4753 >     * directly instantiated. See {@link #values()}.
4754       *
4755       * <p>The view's {@code iterator} is a "weakly consistent" iterator
4756       * that will never throw {@link ConcurrentModificationException},
# Line 4286 | Line 4758 | public class ConcurrentHashMap<K, V>
4758       * construction of the iterator, and may (but is not guaranteed to)
4759       * reflect any modifications subsequent to construction.
4760       */
4761 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4762 <        implements Collection<V> {
4763 <        ValuesView(ConcurrentHashMap<K, V> map)   { super(map); }
4764 <        public final boolean contains(Object o) { return map.containsValue(o); }
4761 >    public static final class ValuesView<K,V>
4762 >            extends CHMCollectionView<K,V,V>
4763 >            implements Collection<V>, java.io.Serializable {
4764 >        private static final long serialVersionUID = 2249069246763182397L;
4765 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4766 >        public final boolean contains(Object o) {
4767 >            return map.containsValue(o);
4768 >        }
4769          public final boolean remove(Object o) {
4770              if (o != null) {
4771 <                Iterator<V> it = new ValueIterator<K,V>(map);
4296 <                while (it.hasNext()) {
4771 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4772                      if (o.equals(it.next())) {
4773                          it.remove();
4774                          return true;
# Line 4304 | Line 4779 | public class ConcurrentHashMap<K, V>
4779          }
4780  
4781          /**
4782 <         * 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
4782 >         * @return an iterator over the values of the backing map
4783           */
4784          public final Iterator<V> iterator() {
4785              return new ValueIterator<K,V>(map);
4786          }
4787 +
4788 +        /** Always throws {@link UnsupportedOperationException}. */
4789          public final boolean add(V e) {
4790              throw new UnsupportedOperationException();
4791          }
4792 +        /** Always throws {@link UnsupportedOperationException}. */
4793          public final boolean addAll(Collection<? extends V> c) {
4794              throw new UnsupportedOperationException();
4795          }
4796  
4797 <        /**
4798 <         * Performs the given action for each value.
4328 <         *
4329 <         * @param action the action
4330 <         */
4331 <        public void forEach(Action<V> action) {
4332 <            ForkJoinTasks.forEachValue
4333 <                (map, action).invoke();
4797 >        public Stream<V> stream() {
4798 >            return Streams.stream(new ValueIterator<K,V>(map, null));
4799          }
4800  
4801 <        /**
4802 <         * Performs the given action for each non-null transformation
4338 <         * of each value.
4339 <         *
4340 <         * @param transformer a function returning the transformation
4341 <         * for an element, or null of there is no transformation (in
4342 <         * which case the action is not applied).
4343 <         */
4344 <        public <U> void forEach(Fun<? super V, ? extends U> transformer,
4345 <                                     Action<U> action) {
4346 <            ForkJoinTasks.forEachValue
4347 <                (map, transformer, action).invoke();
4348 <        }
4349 <
4350 <        /**
4351 <         * Returns a non-null result from applying the given search
4352 <         * function on each value, or null if none.  Upon success,
4353 <         * further element processing is suppressed and the results of
4354 <         * any other parallel invocations of the search function are
4355 <         * ignored.
4356 <         *
4357 <         * @param searchFunction a function returning a non-null
4358 <         * result on success, else null
4359 <         * @return a non-null result from applying the given search
4360 <         * function on each value, or null if none
4361 <         *
4362 <         */
4363 <        public <U> U search(Fun<? super V, ? extends U> searchFunction) {
4364 <            return ForkJoinTasks.searchValues
4365 <                (map, searchFunction).invoke();
4366 <        }
4367 <
4368 <        /**
4369 <         * Returns the result of accumulating all values using the
4370 <         * given reducer to combine values, or null if none.
4371 <         *
4372 <         * @param reducer a commutative associative combining function
4373 <         * @return  the result of accumulating all values
4374 <         */
4375 <        public V reduce(BiFun<? super V, ? super V, ? extends V> reducer) {
4376 <            return ForkJoinTasks.reduceValues
4377 <                (map, reducer).invoke();
4378 <        }
4379 <
4380 <        /**
4381 <         * Returns the result of accumulating the given transformation
4382 <         * of all values using the given reducer to combine values, or
4383 <         * null if none.
4384 <         *
4385 <         * @param transformer a function returning the transformation
4386 <         * for an element, or null of there is no transformation (in
4387 <         * which case it is not combined).
4388 <         * @param reducer a commutative associative combining function
4389 <         * @return the result of accumulating the given transformation
4390 <         * of all values
4391 <         */
4392 <        public <U> U reduce(Fun<? super V, ? extends U> transformer,
4393 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
4394 <            return ForkJoinTasks.reduceValues
4395 <                (map, transformer, reducer).invoke();
4396 <        }
4397 <
4398 <        /**
4399 <         * Returns the result of accumulating the given transformation
4400 <         * of all values using the given reducer to combine values,
4401 <         * and the given basis as an identity value.
4402 <         *
4403 <         * @param transformer a function returning the transformation
4404 <         * for an element
4405 <         * @param basis the identity (initial default value) for the reduction
4406 <         * @param reducer a commutative associative combining function
4407 <         * @return the result of accumulating the given transformation
4408 <         * of all values
4409 <         */
4410 <        public double reduceToDouble(ObjectToDouble<? super V> transformer,
4411 <                                     double basis,
4412 <                                     DoubleByDoubleToDouble reducer) {
4413 <            return ForkJoinTasks.reduceValuesToDouble
4414 <                (map, transformer, basis, reducer).invoke();
4415 <        }
4416 <
4417 <        /**
4418 <         * Returns the result of accumulating the given transformation
4419 <         * of all values using the given reducer to combine values,
4420 <         * and the given basis as an identity value.
4421 <         *
4422 <         * @param transformer a function returning the transformation
4423 <         * for an element
4424 <         * @param basis the identity (initial default value) for the reduction
4425 <         * @param reducer a commutative associative combining function
4426 <         * @return the result of accumulating the given transformation
4427 <         * of all values
4428 <         */
4429 <        public long reduceToLong(ObjectToLong<? super V> transformer,
4430 <                                 long basis,
4431 <                                 LongByLongToLong reducer) {
4432 <            return ForkJoinTasks.reduceValuesToLong
4433 <                (map, transformer, basis, reducer).invoke();
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();
4801 >        public Stream<V> parallelStream() {
4802 >            return Streams.parallelStream(new ValueIterator<K,V>(map, null));
4803          }
4804  
4805      }
# Line 4457 | Line 4807 | public class ConcurrentHashMap<K, V>
4807      /**
4808       * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4809       * entries.  This class cannot be directly instantiated. See
4810 <     * {@link #entrySet}.
4810 >     * {@link #entrySet()}.
4811       */
4812 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4813 <        implements Set<Map.Entry<K,V>> {
4814 <        EntrySetView(ConcurrentHashMap<K, V> map) { super(map); }
4812 >    public static final class EntrySetView<K,V>
4813 >            extends CHMSetView<K,V,Map.Entry<K,V>>
4814 >            implements Set<Map.Entry<K,V>>, java.io.Serializable {
4815 >        private static final long serialVersionUID = 2249069246763182397L;
4816 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4817 >
4818          public final boolean contains(Object o) {
4819              Object k, v, r; Map.Entry<?,?> e;
4820              return ((o instanceof Map.Entry) &&
# Line 4479 | Line 4832 | public class ConcurrentHashMap<K, V>
4832          }
4833  
4834          /**
4835 <         * 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
4835 >         * @return an iterator over the entries of the backing map
4836           */
4837          public final Iterator<Map.Entry<K,V>> iterator() {
4838              return new EntryIterator<K,V>(map);
4839          }
4840  
4841 +        /**
4842 +         * Adds the specified mapping to this view.
4843 +         *
4844 +         * @param e mapping to be added
4845 +         * @return {@code true} if this set changed as a result of the call
4846 +         * @throws NullPointerException if the entry, its key, or its
4847 +         * value is null
4848 +         */
4849          public final boolean add(Entry<K,V> e) {
4850 <            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;
4850 >            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4851          }
4852 +        /**
4853 +         * Adds all of the mappings in the specified collection to this
4854 +         * set, as if by calling {@link #add(Map.Entry)} on each one.
4855 +         * @param c the mappings to be inserted into this set
4856 +         * @return {@code true} if this set changed as a result of the call
4857 +         * @throws NullPointerException if the collection or any of its
4858 +         * entries, keys, or values are null
4859 +         */
4860          public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4861              boolean added = false;
4862              for (Entry<K,V> e : c) {
# Line 4507 | Line 4865 | public class ConcurrentHashMap<K, V>
4865              }
4866              return added;
4867          }
4510        public boolean equals(Object o) {
4511            Set<?> c;
4512            return ((o instanceof Set) &&
4513                    ((c = (Set<?>)o) == this ||
4514                     (containsAll(c) && c.containsAll(this))));
4515        }
4516
4517        /**
4518         * Performs the given action for each entry.
4519         *
4520         * @param action the action
4521         */
4522        public void forEach(Action<Map.Entry<K,V>> action) {
4523            ForkJoinTasks.forEachEntry
4524                (map, action).invoke();
4525        }
4526
4527        /**
4528         * Performs the given action for each non-null transformation
4529         * of each entry.
4530         *
4531         * @param transformer a function returning the transformation
4532         * for an element, or null of there is no transformation (in
4533         * which case the action is not applied).
4534         * @param action the action
4535         */
4536        public <U> void forEach(Fun<Map.Entry<K,V>, ? extends U> transformer,
4537                                Action<U> action) {
4538            ForkJoinTasks.forEachEntry
4539                (map, transformer, action).invoke();
4540        }
4868  
4869 <        /**
4870 <         * 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();
4869 >        public Stream<Map.Entry<K,V>> stream() {
4870 >            return Streams.stream(new EntryIterator<K,V>(map, null));
4871          }
4872  
4873 <        /**
4874 <         * 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();
4873 >        public Stream<Map.Entry<K,V>> parallelStream() {
4874 >            return Streams.parallelStream(new EntryIterator<K,V>(map, null));
4875          }
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
4876      }
4877  
4878      // ---------------------------------------------------------------------
# Line 4669 | Line 4899 | public class ConcurrentHashMap<K, V>
4899           */
4900          public static <K,V> ForkJoinTask<Void> forEach
4901              (ConcurrentHashMap<K,V> map,
4902 <             BiAction<K,V> action) {
4902 >             BiConsumer<? super K, ? super V> action) {
4903              if (action == null) throw new NullPointerException();
4904 <            return new ForEachMappingTask<K,V>(map, null, -1, null, action);
4904 >            return new ForEachMappingTask<K,V>(map, null, -1, action);
4905          }
4906  
4907          /**
# Line 4687 | Line 4917 | public class ConcurrentHashMap<K, V>
4917           */
4918          public static <K,V,U> ForkJoinTask<Void> forEach
4919              (ConcurrentHashMap<K,V> map,
4920 <             BiFun<? super K, ? super V, ? extends U> transformer,
4921 <             Action<U> action) {
4920 >             BiFunction<? super K, ? super V, ? extends U> transformer,
4921 >             Consumer<? super U> action) {
4922              if (transformer == null || action == null)
4923                  throw new NullPointerException();
4924              return new ForEachTransformedMappingTask<K,V,U>
4925 <                (map, null, -1, null, transformer, action);
4925 >                (map, null, -1, transformer, action);
4926          }
4927  
4928          /**
# Line 4709 | Line 4939 | public class ConcurrentHashMap<K, V>
4939           */
4940          public static <K,V,U> ForkJoinTask<U> search
4941              (ConcurrentHashMap<K,V> map,
4942 <             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4942 >             BiFunction<? super K, ? super V, ? extends U> searchFunction) {
4943              if (searchFunction == null) throw new NullPointerException();
4944              return new SearchMappingsTask<K,V,U>
4945 <                (map, null, -1, null, searchFunction,
4945 >                (map, null, -1, searchFunction,
4946                   new AtomicReference<U>());
4947          }
4948  
# Line 4724 | Line 4954 | public class ConcurrentHashMap<K, V>
4954           * @param map the map
4955           * @param transformer a function returning the transformation
4956           * for an element, or null if there is no transformation (in
4957 <         * which case it is not combined).
4957 >         * which case it is not combined)
4958           * @param reducer a commutative associative combining function
4959           * @return the task
4960           */
4961          public static <K,V,U> ForkJoinTask<U> reduce
4962              (ConcurrentHashMap<K,V> map,
4963 <             BiFun<? super K, ? super V, ? extends U> transformer,
4964 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4963 >             BiFunction<? super K, ? super V, ? extends U> transformer,
4964 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
4965              if (transformer == null || reducer == null)
4966                  throw new NullPointerException();
4967              return new MapReduceMappingsTask<K,V,U>
# Line 4753 | Line 4983 | public class ConcurrentHashMap<K, V>
4983           */
4984          public static <K,V> ForkJoinTask<Double> reduceToDouble
4985              (ConcurrentHashMap<K,V> map,
4986 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
4986 >             ToDoubleBiFunction<? super K, ? super V> transformer,
4987               double basis,
4988 <             DoubleByDoubleToDouble reducer) {
4988 >             DoubleBinaryOperator reducer) {
4989              if (transformer == null || reducer == null)
4990                  throw new NullPointerException();
4991              return new MapReduceMappingsToDoubleTask<K,V>
# Line 4777 | Line 5007 | public class ConcurrentHashMap<K, V>
5007           */
5008          public static <K,V> ForkJoinTask<Long> reduceToLong
5009              (ConcurrentHashMap<K,V> map,
5010 <             ObjectByObjectToLong<? super K, ? super V> transformer,
5010 >             ToLongBiFunction<? super K, ? super V> transformer,
5011               long basis,
5012 <             LongByLongToLong reducer) {
5012 >             LongBinaryOperator reducer) {
5013              if (transformer == null || reducer == null)
5014                  throw new NullPointerException();
5015              return new MapReduceMappingsToLongTask<K,V>
# Line 4792 | Line 5022 | public class ConcurrentHashMap<K, V>
5022           * using the given reducer to combine values, and the given
5023           * basis as an identity value.
5024           *
5025 +         * @param map the map
5026           * @param transformer a function returning the transformation
5027           * for an element
5028           * @param basis the identity (initial default value) for the reduction
# Line 4800 | Line 5031 | public class ConcurrentHashMap<K, V>
5031           */
5032          public static <K,V> ForkJoinTask<Integer> reduceToInt
5033              (ConcurrentHashMap<K,V> map,
5034 <             ObjectByObjectToInt<? super K, ? super V> transformer,
5034 >             ToIntBiFunction<? super K, ? super V> transformer,
5035               int basis,
5036 <             IntByIntToInt reducer) {
5036 >             IntBinaryOperator reducer) {
5037              if (transformer == null || reducer == null)
5038                  throw new NullPointerException();
5039              return new MapReduceMappingsToIntTask<K,V>
# Line 4819 | Line 5050 | public class ConcurrentHashMap<K, V>
5050           */
5051          public static <K,V> ForkJoinTask<Void> forEachKey
5052              (ConcurrentHashMap<K,V> map,
5053 <             Action<K> action) {
5053 >             Consumer<? super K> action) {
5054              if (action == null) throw new NullPointerException();
5055 <            return new ForEachKeyTask<K,V>(map, null, -1, null, action);
5055 >            return new ForEachKeyTask<K,V>(map, null, -1, action);
5056          }
5057  
5058          /**
# Line 4837 | Line 5068 | public class ConcurrentHashMap<K, V>
5068           */
5069          public static <K,V,U> ForkJoinTask<Void> forEachKey
5070              (ConcurrentHashMap<K,V> map,
5071 <             Fun<? super K, ? extends U> transformer,
5072 <             Action<U> action) {
5071 >             Function<? super K, ? extends U> transformer,
5072 >             Consumer<? super U> action) {
5073              if (transformer == null || action == null)
5074                  throw new NullPointerException();
5075              return new ForEachTransformedKeyTask<K,V,U>
5076 <                (map, null, -1, null, transformer, action);
5076 >                (map, null, -1, transformer, action);
5077          }
5078  
5079          /**
# Line 4859 | Line 5090 | public class ConcurrentHashMap<K, V>
5090           */
5091          public static <K,V,U> ForkJoinTask<U> searchKeys
5092              (ConcurrentHashMap<K,V> map,
5093 <             Fun<? super K, ? extends U> searchFunction) {
5093 >             Function<? super K, ? extends U> searchFunction) {
5094              if (searchFunction == null) throw new NullPointerException();
5095              return new SearchKeysTask<K,V,U>
5096 <                (map, null, -1, null, searchFunction,
5096 >                (map, null, -1, searchFunction,
5097                   new AtomicReference<U>());
5098          }
5099  
# Line 4877 | Line 5108 | public class ConcurrentHashMap<K, V>
5108           */
5109          public static <K,V> ForkJoinTask<K> reduceKeys
5110              (ConcurrentHashMap<K,V> map,
5111 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5111 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
5112              if (reducer == null) throw new NullPointerException();
5113              return new ReduceKeysTask<K,V>
5114                  (map, null, -1, null, reducer);
# Line 4891 | Line 5122 | public class ConcurrentHashMap<K, V>
5122           * @param map the map
5123           * @param transformer a function returning the transformation
5124           * for an element, or null if there is no transformation (in
5125 <         * which case it is not combined).
5125 >         * which case it is not combined)
5126           * @param reducer a commutative associative combining function
5127           * @return the task
5128           */
5129          public static <K,V,U> ForkJoinTask<U> reduceKeys
5130              (ConcurrentHashMap<K,V> map,
5131 <             Fun<? super K, ? extends U> transformer,
5132 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5131 >             Function<? super K, ? extends U> transformer,
5132 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5133              if (transformer == null || reducer == null)
5134                  throw new NullPointerException();
5135              return new MapReduceKeysTask<K,V,U>
# Line 4920 | Line 5151 | public class ConcurrentHashMap<K, V>
5151           */
5152          public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5153              (ConcurrentHashMap<K,V> map,
5154 <             ObjectToDouble<? super K> transformer,
5154 >             ToDoubleFunction<? super K> transformer,
5155               double basis,
5156 <             DoubleByDoubleToDouble reducer) {
5156 >             DoubleBinaryOperator reducer) {
5157              if (transformer == null || reducer == null)
5158                  throw new NullPointerException();
5159              return new MapReduceKeysToDoubleTask<K,V>
# Line 4944 | Line 5175 | public class ConcurrentHashMap<K, V>
5175           */
5176          public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5177              (ConcurrentHashMap<K,V> map,
5178 <             ObjectToLong<? super K> transformer,
5178 >             ToLongFunction<? super K> transformer,
5179               long basis,
5180 <             LongByLongToLong reducer) {
5180 >             LongBinaryOperator reducer) {
5181              if (transformer == null || reducer == null)
5182                  throw new NullPointerException();
5183              return new MapReduceKeysToLongTask<K,V>
# Line 4968 | Line 5199 | public class ConcurrentHashMap<K, V>
5199           */
5200          public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5201              (ConcurrentHashMap<K,V> map,
5202 <             ObjectToInt<? super K> transformer,
5202 >             ToIntFunction<? super K> transformer,
5203               int basis,
5204 <             IntByIntToInt reducer) {
5204 >             IntBinaryOperator reducer) {
5205              if (transformer == null || reducer == null)
5206                  throw new NullPointerException();
5207              return new MapReduceKeysToIntTask<K,V>
# Line 4983 | Line 5214 | public class ConcurrentHashMap<K, V>
5214           *
5215           * @param map the map
5216           * @param action the action
5217 +         * @return the task
5218           */
5219          public static <K,V> ForkJoinTask<Void> forEachValue
5220              (ConcurrentHashMap<K,V> map,
5221 <             Action<V> action) {
5221 >             Consumer<? super V> action) {
5222              if (action == null) throw new NullPointerException();
5223 <            return new ForEachValueTask<K,V>(map, null, -1, null, action);
5223 >            return new ForEachValueTask<K,V>(map, null, -1, action);
5224          }
5225  
5226          /**
# Line 5000 | Line 5232 | public class ConcurrentHashMap<K, V>
5232           * for an element, or null if there is no transformation (in
5233           * which case the action is not applied)
5234           * @param action the action
5235 +         * @return the task
5236           */
5237          public static <K,V,U> ForkJoinTask<Void> forEachValue
5238              (ConcurrentHashMap<K,V> map,
5239 <             Fun<? super V, ? extends U> transformer,
5240 <             Action<U> action) {
5239 >             Function<? super V, ? extends U> transformer,
5240 >             Consumer<? super U> action) {
5241              if (transformer == null || action == null)
5242                  throw new NullPointerException();
5243              return new ForEachTransformedValueTask<K,V,U>
5244 <                (map, null, -1, null, transformer, action);
5244 >                (map, null, -1, transformer, action);
5245          }
5246  
5247          /**
# Line 5025 | Line 5258 | public class ConcurrentHashMap<K, V>
5258           */
5259          public static <K,V,U> ForkJoinTask<U> searchValues
5260              (ConcurrentHashMap<K,V> map,
5261 <             Fun<? super V, ? extends U> searchFunction) {
5261 >             Function<? super V, ? extends U> searchFunction) {
5262              if (searchFunction == null) throw new NullPointerException();
5263              return new SearchValuesTask<K,V,U>
5264 <                (map, null, -1, null, searchFunction,
5264 >                (map, null, -1, searchFunction,
5265                   new AtomicReference<U>());
5266          }
5267  
# Line 5043 | Line 5276 | public class ConcurrentHashMap<K, V>
5276           */
5277          public static <K,V> ForkJoinTask<V> reduceValues
5278              (ConcurrentHashMap<K,V> map,
5279 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5279 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
5280              if (reducer == null) throw new NullPointerException();
5281              return new ReduceValuesTask<K,V>
5282                  (map, null, -1, null, reducer);
# Line 5057 | Line 5290 | public class ConcurrentHashMap<K, V>
5290           * @param map the map
5291           * @param transformer a function returning the transformation
5292           * for an element, or null if there is no transformation (in
5293 <         * which case it is not combined).
5293 >         * which case it is not combined)
5294           * @param reducer a commutative associative combining function
5295           * @return the task
5296           */
5297          public static <K,V,U> ForkJoinTask<U> reduceValues
5298              (ConcurrentHashMap<K,V> map,
5299 <             Fun<? super V, ? extends U> transformer,
5300 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5299 >             Function<? super V, ? extends U> transformer,
5300 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5301              if (transformer == null || reducer == null)
5302                  throw new NullPointerException();
5303              return new MapReduceValuesTask<K,V,U>
# Line 5086 | Line 5319 | public class ConcurrentHashMap<K, V>
5319           */
5320          public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5321              (ConcurrentHashMap<K,V> map,
5322 <             ObjectToDouble<? super V> transformer,
5322 >             ToDoubleFunction<? super V> transformer,
5323               double basis,
5324 <             DoubleByDoubleToDouble reducer) {
5324 >             DoubleBinaryOperator reducer) {
5325              if (transformer == null || reducer == null)
5326                  throw new NullPointerException();
5327              return new MapReduceValuesToDoubleTask<K,V>
# Line 5110 | Line 5343 | public class ConcurrentHashMap<K, V>
5343           */
5344          public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5345              (ConcurrentHashMap<K,V> map,
5346 <             ObjectToLong<? super V> transformer,
5346 >             ToLongFunction<? super V> transformer,
5347               long basis,
5348 <             LongByLongToLong reducer) {
5348 >             LongBinaryOperator reducer) {
5349              if (transformer == null || reducer == null)
5350                  throw new NullPointerException();
5351              return new MapReduceValuesToLongTask<K,V>
# Line 5134 | Line 5367 | public class ConcurrentHashMap<K, V>
5367           */
5368          public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5369              (ConcurrentHashMap<K,V> map,
5370 <             ObjectToInt<? super V> transformer,
5370 >             ToIntFunction<? super V> transformer,
5371               int basis,
5372 <             IntByIntToInt reducer) {
5372 >             IntBinaryOperator reducer) {
5373              if (transformer == null || reducer == null)
5374                  throw new NullPointerException();
5375              return new MapReduceValuesToIntTask<K,V>
# Line 5149 | Line 5382 | public class ConcurrentHashMap<K, V>
5382           *
5383           * @param map the map
5384           * @param action the action
5385 +         * @return the task
5386           */
5387          public static <K,V> ForkJoinTask<Void> forEachEntry
5388              (ConcurrentHashMap<K,V> map,
5389 <             Action<Map.Entry<K,V>> action) {
5389 >             Consumer<? super Map.Entry<K,V>> action) {
5390              if (action == null) throw new NullPointerException();
5391 <            return new ForEachEntryTask<K,V>(map, null, -1, null, action);
5391 >            return new ForEachEntryTask<K,V>(map, null, -1, action);
5392          }
5393  
5394          /**
# Line 5166 | Line 5400 | public class ConcurrentHashMap<K, V>
5400           * for an element, or null if there is no transformation (in
5401           * which case the action is not applied)
5402           * @param action the action
5403 +         * @return the task
5404           */
5405          public static <K,V,U> ForkJoinTask<Void> forEachEntry
5406              (ConcurrentHashMap<K,V> map,
5407 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5408 <             Action<U> action) {
5407 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5408 >             Consumer<? super U> action) {
5409              if (transformer == null || action == null)
5410                  throw new NullPointerException();
5411              return new ForEachTransformedEntryTask<K,V,U>
5412 <                (map, null, -1, null, transformer, action);
5412 >                (map, null, -1, transformer, action);
5413          }
5414  
5415          /**
# Line 5191 | Line 5426 | public class ConcurrentHashMap<K, V>
5426           */
5427          public static <K,V,U> ForkJoinTask<U> searchEntries
5428              (ConcurrentHashMap<K,V> map,
5429 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5429 >             Function<Map.Entry<K,V>, ? extends U> searchFunction) {
5430              if (searchFunction == null) throw new NullPointerException();
5431              return new SearchEntriesTask<K,V,U>
5432 <                (map, null, -1, null, searchFunction,
5432 >                (map, null, -1, searchFunction,
5433                   new AtomicReference<U>());
5434          }
5435  
# Line 5209 | Line 5444 | public class ConcurrentHashMap<K, V>
5444           */
5445          public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5446              (ConcurrentHashMap<K,V> map,
5447 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5447 >             BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5448              if (reducer == null) throw new NullPointerException();
5449              return new ReduceEntriesTask<K,V>
5450                  (map, null, -1, null, reducer);
# Line 5223 | Line 5458 | public class ConcurrentHashMap<K, V>
5458           * @param map the map
5459           * @param transformer a function returning the transformation
5460           * for an element, or null if there is no transformation (in
5461 <         * which case it is not combined).
5461 >         * which case it is not combined)
5462           * @param reducer a commutative associative combining function
5463           * @return the task
5464           */
5465          public static <K,V,U> ForkJoinTask<U> reduceEntries
5466              (ConcurrentHashMap<K,V> map,
5467 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5468 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5467 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5468 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5469              if (transformer == null || reducer == null)
5470                  throw new NullPointerException();
5471              return new MapReduceEntriesTask<K,V,U>
# Line 5252 | Line 5487 | public class ConcurrentHashMap<K, V>
5487           */
5488          public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5489              (ConcurrentHashMap<K,V> map,
5490 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5490 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5491               double basis,
5492 <             DoubleByDoubleToDouble reducer) {
5492 >             DoubleBinaryOperator reducer) {
5493              if (transformer == null || reducer == null)
5494                  throw new NullPointerException();
5495              return new MapReduceEntriesToDoubleTask<K,V>
# Line 5276 | Line 5511 | public class ConcurrentHashMap<K, V>
5511           */
5512          public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
5513              (ConcurrentHashMap<K,V> map,
5514 <             ObjectToLong<Map.Entry<K,V>> transformer,
5514 >             ToLongFunction<Map.Entry<K,V>> transformer,
5515               long basis,
5516 <             LongByLongToLong reducer) {
5516 >             LongBinaryOperator reducer) {
5517              if (transformer == null || reducer == null)
5518                  throw new NullPointerException();
5519              return new MapReduceEntriesToLongTask<K,V>
# Line 5300 | Line 5535 | public class ConcurrentHashMap<K, V>
5535           */
5536          public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
5537              (ConcurrentHashMap<K,V> map,
5538 <             ObjectToInt<Map.Entry<K,V>> transformer,
5538 >             ToIntFunction<Map.Entry<K,V>> transformer,
5539               int basis,
5540 <             IntByIntToInt reducer) {
5540 >             IntBinaryOperator reducer) {
5541              if (transformer == null || reducer == null)
5542                  throw new NullPointerException();
5543              return new MapReduceEntriesToIntTask<K,V>
# Line 5312 | Line 5547 | public class ConcurrentHashMap<K, V>
5547  
5548      // -------------------------------------------------------
5549  
5315    /**
5316     * Base for FJ tasks for bulk operations. This adds a variant of
5317     * 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
5429     */
5430    @SuppressWarnings("serial") static abstract class BulkAction<K,V,R> extends BulkTask<K,V,R> {
5431        BulkAction<K,V,?> nextTask;
5432        BulkAction(ConcurrentHashMap<K,V> map, BulkTask<K,V,?> parent,
5433                   int batch, BulkAction<K,V,?> nextTask) {
5434            super(map, parent, batch);
5435            this.nextTask = nextTask;
5436        }
5437
5438        /**
5439         * Try to complete task and upward parents. Upon hitting
5440         * non-completed parent, if a non-FJ task, try to help out the
5441         * computation.
5442         */
5443        final void tryComplete(BulkAction<K,V,?> subtasks) {
5444            BulkTask<K,V,?> a = this, s = a;
5445            for (int c;;) {
5446                if ((c = a.pending) == 0) {
5447                    if ((a = (s = a).parent) == null) {
5448                        s.quietlyComplete();
5449                        break;
5450                    }
5451                }
5452                else if (a.casPending(c, c - 1)) {
5453                    if (subtasks != null && !inForkJoinPool()) {
5454                        while ((s = a.parent) != null)
5455                            a = s;
5456                        while (!a.isDone()) {
5457                            BulkAction<K,V,?> next = subtasks.nextTask;
5458                            if (subtasks.tryUnfork())
5459                                subtasks.exec();
5460                            if ((subtasks = next) == null)
5461                                break;
5462                        }
5463                    }
5464                    break;
5465                }
5466            }
5467        }
5468
5469    }
5470
5550      /*
5551       * Task classes. Coded in a regular but ugly format/style to
5552       * simplify checks that each variant differs in the right way from
5553 <     * others.
5553 >     * others. The null screenings exist because compilers cannot tell
5554 >     * that we've already null-checked task arguments, so we force
5555 >     * simplest hoisted bypass to help avoid convoluted traps.
5556       */
5557  
5558      @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
5559 <        extends BulkAction<K,V,Void> {
5560 <        final Action<K> action;
5559 >        extends Traverser<K,V,Void> {
5560 >        final Consumer<? super K> action;
5561          ForEachKeyTask
5562 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5563 <             ForEachKeyTask<K,V> nextTask,
5564 <             Action<K> action) {
5484 <            super(m, p, b, nextTask);
5562 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5563 >             Consumer<? super K> action) {
5564 >            super(m, p, b);
5565              this.action = action;
5566          }
5567 <        @SuppressWarnings("unchecked") public final boolean exec() {
5568 <            final Action<K> action = this.action;
5569 <            if (action == null)
5570 <                return abortOnNullFunction();
5571 <            ForEachKeyTask<K,V> subtasks = null;
5492 <            try {
5493 <                int b = batch(), c;
5494 <                while (b > 1 && baseIndex != baseLimit) {
5495 <                    do {} while (!casPending(c = pending, c+1));
5496 <                    (subtasks = new ForEachKeyTask<K,V>
5497 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5498 <                }
5567 >        public final void compute() {
5568 >            final Consumer<? super K> action;
5569 >            if ((action = this.action) != null) {
5570 >                for (int b; (b = preSplit()) > 0;)
5571 >                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
5572                  while (advance() != null)
5573 <                    action.apply((K)nextKey);
5574 <            } catch (Throwable ex) {
5502 <                return tryCompleteComputation(ex);
5573 >                    action.accept(nextKey);
5574 >                propagateCompletion();
5575              }
5504            tryComplete(subtasks);
5505            return false;
5576          }
5577      }
5578  
5579      @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
5580 <        extends BulkAction<K,V,Void> {
5581 <        final Action<V> action;
5580 >        extends Traverser<K,V,Void> {
5581 >        final Consumer<? super V> action;
5582          ForEachValueTask
5583 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5584 <             ForEachValueTask<K,V> nextTask,
5585 <             Action<V> action) {
5516 <            super(m, p, b, nextTask);
5583 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5584 >             Consumer<? super V> action) {
5585 >            super(m, p, b);
5586              this.action = action;
5587          }
5588 <        @SuppressWarnings("unchecked") public final boolean exec() {
5589 <            final Action<V> action = this.action;
5590 <            if (action == null)
5591 <                return abortOnNullFunction();
5592 <            ForEachValueTask<K,V> subtasks = null;
5593 <            try {
5525 <                int b = batch(), c;
5526 <                while (b > 1 && baseIndex != baseLimit) {
5527 <                    do {} while (!casPending(c = pending, c+1));
5528 <                    (subtasks = new ForEachValueTask<K,V>
5529 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5530 <                }
5531 <                Object v;
5588 >        public final void compute() {
5589 >            final Consumer<? super V> action;
5590 >            if ((action = this.action) != null) {
5591 >                for (int b; (b = preSplit()) > 0;)
5592 >                    new ForEachValueTask<K,V>(map, this, b, action).fork();
5593 >                V v;
5594                  while ((v = advance()) != null)
5595 <                    action.apply((V)v);
5596 <            } catch (Throwable ex) {
5535 <                return tryCompleteComputation(ex);
5595 >                    action.accept(v);
5596 >                propagateCompletion();
5597              }
5537            tryComplete(subtasks);
5538            return false;
5598          }
5599      }
5600  
5601      @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
5602 <        extends BulkAction<K,V,Void> {
5603 <        final Action<Entry<K,V>> action;
5602 >        extends Traverser<K,V,Void> {
5603 >        final Consumer<? super Entry<K,V>> action;
5604          ForEachEntryTask
5605 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5606 <             ForEachEntryTask<K,V> nextTask,
5607 <             Action<Entry<K,V>> action) {
5549 <            super(m, p, b, nextTask);
5605 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5606 >             Consumer<? super Entry<K,V>> action) {
5607 >            super(m, p, b);
5608              this.action = action;
5609          }
5610 <        @SuppressWarnings("unchecked") public final boolean exec() {
5611 <            final Action<Entry<K,V>> action = this.action;
5612 <            if (action == null)
5613 <                return abortOnNullFunction();
5614 <            ForEachEntryTask<K,V> subtasks = null;
5615 <            try {
5558 <                int b = batch(), c;
5559 <                while (b > 1 && baseIndex != baseLimit) {
5560 <                    do {} while (!casPending(c = pending, c+1));
5561 <                    (subtasks = new ForEachEntryTask<K,V>
5562 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5563 <                }
5564 <                Object v;
5610 >        public final void compute() {
5611 >            final Consumer<? super Entry<K,V>> action;
5612 >            if ((action = this.action) != null) {
5613 >                for (int b; (b = preSplit()) > 0;)
5614 >                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
5615 >                V v;
5616                  while ((v = advance()) != null)
5617 <                    action.apply(entryFor((K)nextKey, (V)v));
5618 <            } catch (Throwable ex) {
5568 <                return tryCompleteComputation(ex);
5617 >                    action.accept(entryFor(nextKey, v));
5618 >                propagateCompletion();
5619              }
5570            tryComplete(subtasks);
5571            return false;
5620          }
5621      }
5622  
5623      @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5624 <        extends BulkAction<K,V,Void> {
5625 <        final BiAction<K,V> action;
5624 >        extends Traverser<K,V,Void> {
5625 >        final BiConsumer<? super K, ? super V> action;
5626          ForEachMappingTask
5627 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5628 <             ForEachMappingTask<K,V> nextTask,
5629 <             BiAction<K,V> action) {
5582 <            super(m, p, b, nextTask);
5627 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5628 >             BiConsumer<? super K,? super V> action) {
5629 >            super(m, p, b);
5630              this.action = action;
5631          }
5632 <        @SuppressWarnings("unchecked") public final boolean exec() {
5633 <            final BiAction<K,V> action = this.action;
5634 <            if (action == null)
5635 <                return abortOnNullFunction();
5636 <            ForEachMappingTask<K,V> subtasks = null;
5637 <            try {
5591 <                int b = batch(), c;
5592 <                while (b > 1 && baseIndex != baseLimit) {
5593 <                    do {} while (!casPending(c = pending, c+1));
5594 <                    (subtasks = new ForEachMappingTask<K,V>
5595 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5596 <                }
5597 <                Object v;
5632 >        public final void compute() {
5633 >            final BiConsumer<? super K, ? super V> action;
5634 >            if ((action = this.action) != null) {
5635 >                for (int b; (b = preSplit()) > 0;)
5636 >                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
5637 >                V v;
5638                  while ((v = advance()) != null)
5639 <                    action.apply((K)nextKey, (V)v);
5640 <            } catch (Throwable ex) {
5601 <                return tryCompleteComputation(ex);
5639 >                    action.accept(nextKey, v);
5640 >                propagateCompletion();
5641              }
5603            tryComplete(subtasks);
5604            return false;
5642          }
5643      }
5644  
5645      @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5646 <        extends BulkAction<K,V,Void> {
5647 <        final Fun<? super K, ? extends U> transformer;
5648 <        final Action<U> action;
5646 >        extends Traverser<K,V,Void> {
5647 >        final Function<? super K, ? extends U> transformer;
5648 >        final Consumer<? super U> action;
5649          ForEachTransformedKeyTask
5650 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5651 <             ForEachTransformedKeyTask<K,V,U> nextTask,
5652 <             Fun<? super K, ? extends U> transformer,
5653 <             Action<U> action) {
5654 <            super(m, p, b, nextTask);
5655 <            this.transformer = transformer;
5656 <            this.action = action;
5657 <
5658 <        }
5659 <        @SuppressWarnings("unchecked") public final boolean exec() {
5660 <            final Fun<? super K, ? extends U> transformer =
5661 <                this.transformer;
5662 <            final Action<U> action = this.action;
5626 <            if (transformer == null || action == null)
5627 <                return abortOnNullFunction();
5628 <            ForEachTransformedKeyTask<K,V,U> subtasks = null;
5629 <            try {
5630 <                int b = batch(), c;
5631 <                while (b > 1 && baseIndex != baseLimit) {
5632 <                    do {} while (!casPending(c = pending, c+1));
5633 <                    (subtasks = new ForEachTransformedKeyTask<K,V,U>
5634 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5635 <                }
5650 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5651 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5652 >            super(m, p, b);
5653 >            this.transformer = transformer; this.action = action;
5654 >        }
5655 >        public final void compute() {
5656 >            final Function<? super K, ? extends U> transformer;
5657 >            final Consumer<? super U> action;
5658 >            if ((transformer = this.transformer) != null &&
5659 >                (action = this.action) != null) {
5660 >                for (int b; (b = preSplit()) > 0;)
5661 >                    new ForEachTransformedKeyTask<K,V,U>
5662 >                        (map, this, b, transformer, action).fork();
5663                  U u;
5664                  while (advance() != null) {
5665 <                    if ((u = transformer.apply((K)nextKey)) != null)
5666 <                        action.apply(u);
5665 >                    if ((u = transformer.apply(nextKey)) != null)
5666 >                        action.accept(u);
5667                  }
5668 <            } catch (Throwable ex) {
5642 <                return tryCompleteComputation(ex);
5668 >                propagateCompletion();
5669              }
5644            tryComplete(subtasks);
5645            return false;
5670          }
5671      }
5672  
5673      @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5674 <        extends BulkAction<K,V,Void> {
5675 <        final Fun<? super V, ? extends U> transformer;
5676 <        final Action<U> action;
5674 >        extends Traverser<K,V,Void> {
5675 >        final Function<? super V, ? extends U> transformer;
5676 >        final Consumer<? super U> action;
5677          ForEachTransformedValueTask
5678 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5679 <             ForEachTransformedValueTask<K,V,U> nextTask,
5680 <             Fun<? super V, ? extends U> transformer,
5681 <             Action<U> action) {
5682 <            super(m, p, b, nextTask);
5683 <            this.transformer = transformer;
5684 <            this.action = action;
5685 <
5686 <        }
5687 <        @SuppressWarnings("unchecked") public final boolean exec() {
5688 <            final Fun<? super V, ? extends U> transformer =
5689 <                this.transformer;
5690 <            final Action<U> action = this.action;
5691 <            if (transformer == null || action == null)
5668 <                return abortOnNullFunction();
5669 <            ForEachTransformedValueTask<K,V,U> subtasks = null;
5670 <            try {
5671 <                int b = batch(), c;
5672 <                while (b > 1 && baseIndex != baseLimit) {
5673 <                    do {} while (!casPending(c = pending, c+1));
5674 <                    (subtasks = new ForEachTransformedValueTask<K,V,U>
5675 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5676 <                }
5677 <                Object v; U u;
5678 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5679 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5680 >            super(m, p, b);
5681 >            this.transformer = transformer; this.action = action;
5682 >        }
5683 >        public final void compute() {
5684 >            final Function<? super V, ? extends U> transformer;
5685 >            final Consumer<? super U> action;
5686 >            if ((transformer = this.transformer) != null &&
5687 >                (action = this.action) != null) {
5688 >                for (int b; (b = preSplit()) > 0;)
5689 >                    new ForEachTransformedValueTask<K,V,U>
5690 >                        (map, this, b, transformer, action).fork();
5691 >                V v; U u;
5692                  while ((v = advance()) != null) {
5693 <                    if ((u = transformer.apply((V)v)) != null)
5694 <                        action.apply(u);
5693 >                    if ((u = transformer.apply(v)) != null)
5694 >                        action.accept(u);
5695                  }
5696 <            } catch (Throwable ex) {
5683 <                return tryCompleteComputation(ex);
5696 >                propagateCompletion();
5697              }
5685            tryComplete(subtasks);
5686            return false;
5698          }
5699      }
5700  
5701      @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5702 <        extends BulkAction<K,V,Void> {
5703 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5704 <        final Action<U> action;
5702 >        extends Traverser<K,V,Void> {
5703 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5704 >        final Consumer<? super U> action;
5705          ForEachTransformedEntryTask
5706 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5707 <             ForEachTransformedEntryTask<K,V,U> nextTask,
5708 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5709 <             Action<U> action) {
5710 <            super(m, p, b, nextTask);
5711 <            this.transformer = transformer;
5712 <            this.action = action;
5713 <
5714 <        }
5715 <        @SuppressWarnings("unchecked") public final boolean exec() {
5716 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5717 <                this.transformer;
5718 <            final Action<U> action = this.action;
5719 <            if (transformer == null || action == null)
5709 <                return abortOnNullFunction();
5710 <            ForEachTransformedEntryTask<K,V,U> subtasks = null;
5711 <            try {
5712 <                int b = batch(), c;
5713 <                while (b > 1 && baseIndex != baseLimit) {
5714 <                    do {} while (!casPending(c = pending, c+1));
5715 <                    (subtasks = new ForEachTransformedEntryTask<K,V,U>
5716 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5717 <                }
5718 <                Object v; U u;
5706 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5707 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5708 >            super(m, p, b);
5709 >            this.transformer = transformer; this.action = action;
5710 >        }
5711 >        public final void compute() {
5712 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5713 >            final Consumer<? super U> action;
5714 >            if ((transformer = this.transformer) != null &&
5715 >                (action = this.action) != null) {
5716 >                for (int b; (b = preSplit()) > 0;)
5717 >                    new ForEachTransformedEntryTask<K,V,U>
5718 >                        (map, this, b, transformer, action).fork();
5719 >                V v; U u;
5720                  while ((v = advance()) != null) {
5721 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5722 <                        action.apply(u);
5721 >                    if ((u = transformer.apply(entryFor(nextKey,
5722 >                                                        v))) != null)
5723 >                        action.accept(u);
5724                  }
5725 <            } catch (Throwable ex) {
5724 <                return tryCompleteComputation(ex);
5725 >                propagateCompletion();
5726              }
5726            tryComplete(subtasks);
5727            return false;
5727          }
5728      }
5729  
5730      @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5731 <        extends BulkAction<K,V,Void> {
5732 <        final BiFun<? super K, ? super V, ? extends U> transformer;
5733 <        final Action<U> action;
5731 >        extends Traverser<K,V,Void> {
5732 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5733 >        final Consumer<? super U> action;
5734          ForEachTransformedMappingTask
5735 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5736 <             ForEachTransformedMappingTask<K,V,U> nextTask,
5737 <             BiFun<? super K, ? super V, ? extends U> transformer,
5738 <             Action<U> action) {
5739 <            super(m, p, b, nextTask);
5740 <            this.transformer = transformer;
5741 <            this.action = action;
5742 <
5743 <        }
5744 <        @SuppressWarnings("unchecked") public final boolean exec() {
5745 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5746 <                this.transformer;
5747 <            final Action<U> action = this.action;
5748 <            if (transformer == null || action == null)
5749 <                return abortOnNullFunction();
5751 <            ForEachTransformedMappingTask<K,V,U> subtasks = null;
5752 <            try {
5753 <                int b = batch(), c;
5754 <                while (b > 1 && baseIndex != baseLimit) {
5755 <                    do {} while (!casPending(c = pending, c+1));
5756 <                    (subtasks = new ForEachTransformedMappingTask<K,V,U>
5757 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5758 <                }
5759 <                Object v; U u;
5735 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5736 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5737 >             Consumer<? super U> action) {
5738 >            super(m, p, b);
5739 >            this.transformer = transformer; this.action = action;
5740 >        }
5741 >        public final void compute() {
5742 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5743 >            final Consumer<? super U> action;
5744 >            if ((transformer = this.transformer) != null &&
5745 >                (action = this.action) != null) {
5746 >                for (int b; (b = preSplit()) > 0;)
5747 >                    new ForEachTransformedMappingTask<K,V,U>
5748 >                        (map, this, b, transformer, action).fork();
5749 >                V v; U u;
5750                  while ((v = advance()) != null) {
5751 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5752 <                        action.apply(u);
5751 >                    if ((u = transformer.apply(nextKey, v)) != null)
5752 >                        action.accept(u);
5753                  }
5754 <            } catch (Throwable ex) {
5765 <                return tryCompleteComputation(ex);
5754 >                propagateCompletion();
5755              }
5767            tryComplete(subtasks);
5768            return false;
5756          }
5757      }
5758  
5759      @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5760 <        extends BulkAction<K,V,U> {
5761 <        final Fun<? super K, ? extends U> searchFunction;
5760 >        extends Traverser<K,V,U> {
5761 >        final Function<? super K, ? extends U> searchFunction;
5762          final AtomicReference<U> result;
5763          SearchKeysTask
5764 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5765 <             SearchKeysTask<K,V,U> nextTask,
5779 <             Fun<? super K, ? extends U> searchFunction,
5764 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5765 >             Function<? super K, ? extends U> searchFunction,
5766               AtomicReference<U> result) {
5767 <            super(m, p, b, nextTask);
5767 >            super(m, p, b);
5768              this.searchFunction = searchFunction; this.result = result;
5769          }
5770 <        @SuppressWarnings("unchecked") public final boolean exec() {
5771 <            AtomicReference<U> result = this.result;
5772 <            final Fun<? super K, ? extends U> searchFunction =
5773 <                this.searchFunction;
5774 <            if (searchFunction == null || result == null)
5775 <                return abortOnNullFunction();
5776 <            SearchKeysTask<K,V,U> subtasks = null;
5777 <            try {
5778 <                int b = batch(), c;
5779 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5780 <                    do {} while (!casPending(c = pending, c+1));
5781 <                    (subtasks = new SearchKeysTask<K,V,U>
5782 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5770 >        public final U getRawResult() { return result.get(); }
5771 >        public final void compute() {
5772 >            final Function<? super K, ? extends U> searchFunction;
5773 >            final AtomicReference<U> result;
5774 >            if ((searchFunction = this.searchFunction) != null &&
5775 >                (result = this.result) != null) {
5776 >                for (int b;;) {
5777 >                    if (result.get() != null)
5778 >                        return;
5779 >                    if ((b = preSplit()) <= 0)
5780 >                        break;
5781 >                    new SearchKeysTask<K,V,U>
5782 >                        (map, this, b, searchFunction, result).fork();
5783                  }
5784 <                U u;
5785 <                while (result.get() == null && advance() != null) {
5786 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
5784 >                while (result.get() == null) {
5785 >                    U u;
5786 >                    if (advance() == null) {
5787 >                        propagateCompletion();
5788 >                        break;
5789 >                    }
5790 >                    if ((u = searchFunction.apply(nextKey)) != null) {
5791                          if (result.compareAndSet(null, u))
5792 <                            tryCompleteComputation(null);
5792 >                            quietlyCompleteRoot();
5793                          break;
5794                      }
5795                  }
5806            } catch (Throwable ex) {
5807                return tryCompleteComputation(ex);
5796              }
5809            tryComplete(subtasks);
5810            return false;
5797          }
5812        public final U getRawResult() { return result.get(); }
5798      }
5799  
5800      @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5801 <        extends BulkAction<K,V,U> {
5802 <        final Fun<? super V, ? extends U> searchFunction;
5801 >        extends Traverser<K,V,U> {
5802 >        final Function<? super V, ? extends U> searchFunction;
5803          final AtomicReference<U> result;
5804          SearchValuesTask
5805 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5806 <             SearchValuesTask<K,V,U> nextTask,
5822 <             Fun<? super V, ? extends U> searchFunction,
5805 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5806 >             Function<? super V, ? extends U> searchFunction,
5807               AtomicReference<U> result) {
5808 <            super(m, p, b, nextTask);
5808 >            super(m, p, b);
5809              this.searchFunction = searchFunction; this.result = result;
5810          }
5811 <        @SuppressWarnings("unchecked") public final boolean exec() {
5812 <            AtomicReference<U> result = this.result;
5813 <            final Fun<? super V, ? extends U> searchFunction =
5814 <                this.searchFunction;
5815 <            if (searchFunction == null || result == null)
5816 <                return abortOnNullFunction();
5817 <            SearchValuesTask<K,V,U> subtasks = null;
5818 <            try {
5819 <                int b = batch(), c;
5820 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5821 <                    do {} while (!casPending(c = pending, c+1));
5822 <                    (subtasks = new SearchValuesTask<K,V,U>
5823 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5824 <                }
5825 <                Object v; U u;
5826 <                while (result.get() == null && (v = advance()) != null) {
5827 <                    if ((u = searchFunction.apply((V)v)) != null) {
5811 >        public final U getRawResult() { return result.get(); }
5812 >        public final void compute() {
5813 >            final Function<? super V, ? extends U> searchFunction;
5814 >            final AtomicReference<U> result;
5815 >            if ((searchFunction = this.searchFunction) != null &&
5816 >                (result = this.result) != null) {
5817 >                for (int b;;) {
5818 >                    if (result.get() != null)
5819 >                        return;
5820 >                    if ((b = preSplit()) <= 0)
5821 >                        break;
5822 >                    new SearchValuesTask<K,V,U>
5823 >                        (map, this, b, searchFunction, result).fork();
5824 >                }
5825 >                while (result.get() == null) {
5826 >                    V v; U u;
5827 >                    if ((v = advance()) == null) {
5828 >                        propagateCompletion();
5829 >                        break;
5830 >                    }
5831 >                    if ((u = searchFunction.apply(v)) != null) {
5832                          if (result.compareAndSet(null, u))
5833 <                            tryCompleteComputation(null);
5833 >                            quietlyCompleteRoot();
5834                          break;
5835                      }
5836                  }
5849            } catch (Throwable ex) {
5850                return tryCompleteComputation(ex);
5837              }
5852            tryComplete(subtasks);
5853            return false;
5838          }
5855        public final U getRawResult() { return result.get(); }
5839      }
5840  
5841      @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5842 <        extends BulkAction<K,V,U> {
5843 <        final Fun<Entry<K,V>, ? extends U> searchFunction;
5842 >        extends Traverser<K,V,U> {
5843 >        final Function<Entry<K,V>, ? extends U> searchFunction;
5844          final AtomicReference<U> result;
5845          SearchEntriesTask
5846 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5847 <             SearchEntriesTask<K,V,U> nextTask,
5865 <             Fun<Entry<K,V>, ? extends U> searchFunction,
5846 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5847 >             Function<Entry<K,V>, ? extends U> searchFunction,
5848               AtomicReference<U> result) {
5849 <            super(m, p, b, nextTask);
5849 >            super(m, p, b);
5850              this.searchFunction = searchFunction; this.result = result;
5851          }
5852 <        @SuppressWarnings("unchecked") public final boolean exec() {
5853 <            AtomicReference<U> result = this.result;
5854 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
5855 <                this.searchFunction;
5856 <            if (searchFunction == null || result == null)
5857 <                return abortOnNullFunction();
5858 <            SearchEntriesTask<K,V,U> subtasks = null;
5859 <            try {
5860 <                int b = batch(), c;
5861 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5862 <                    do {} while (!casPending(c = pending, c+1));
5863 <                    (subtasks = new SearchEntriesTask<K,V,U>
5864 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5865 <                }
5866 <                Object v; U u;
5867 <                while (result.get() == null && (v = advance()) != null) {
5868 <                    if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
5869 <                        if (result.compareAndSet(null, u))
5888 <                            tryCompleteComputation(null);
5852 >        public final U getRawResult() { return result.get(); }
5853 >        public final void compute() {
5854 >            final Function<Entry<K,V>, ? extends U> searchFunction;
5855 >            final AtomicReference<U> result;
5856 >            if ((searchFunction = this.searchFunction) != null &&
5857 >                (result = this.result) != null) {
5858 >                for (int b;;) {
5859 >                    if (result.get() != null)
5860 >                        return;
5861 >                    if ((b = preSplit()) <= 0)
5862 >                        break;
5863 >                    new SearchEntriesTask<K,V,U>
5864 >                        (map, this, b, searchFunction, result).fork();
5865 >                }
5866 >                while (result.get() == null) {
5867 >                    V v; U u;
5868 >                    if ((v = advance()) == null) {
5869 >                        propagateCompletion();
5870                          break;
5871                      }
5872 +                    if ((u = searchFunction.apply(entryFor(nextKey,
5873 +                                                           v))) != null) {
5874 +                        if (result.compareAndSet(null, u))
5875 +                            quietlyCompleteRoot();
5876 +                        return;
5877 +                    }
5878                  }
5892            } catch (Throwable ex) {
5893                return tryCompleteComputation(ex);
5879              }
5895            tryComplete(subtasks);
5896            return false;
5880          }
5898        public final U getRawResult() { return result.get(); }
5881      }
5882  
5883      @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5884 <        extends BulkAction<K,V,U> {
5885 <        final BiFun<? super K, ? super V, ? extends U> searchFunction;
5884 >        extends Traverser<K,V,U> {
5885 >        final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5886          final AtomicReference<U> result;
5887          SearchMappingsTask
5888 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5889 <             SearchMappingsTask<K,V,U> nextTask,
5908 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
5888 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5889 >             BiFunction<? super K, ? super V, ? extends U> searchFunction,
5890               AtomicReference<U> result) {
5891 <            super(m, p, b, nextTask);
5891 >            super(m, p, b);
5892              this.searchFunction = searchFunction; this.result = result;
5893          }
5894 <        @SuppressWarnings("unchecked") public final boolean exec() {
5895 <            AtomicReference<U> result = this.result;
5896 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
5897 <                this.searchFunction;
5898 <            if (searchFunction == null || result == null)
5899 <                return abortOnNullFunction();
5900 <            SearchMappingsTask<K,V,U> subtasks = null;
5901 <            try {
5902 <                int b = batch(), c;
5903 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5904 <                    do {} while (!casPending(c = pending, c+1));
5905 <                    (subtasks = new SearchMappingsTask<K,V,U>
5906 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5907 <                }
5908 <                Object v; U u;
5909 <                while (result.get() == null && (v = advance()) != null) {
5910 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5894 >        public final U getRawResult() { return result.get(); }
5895 >        public final void compute() {
5896 >            final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5897 >            final AtomicReference<U> result;
5898 >            if ((searchFunction = this.searchFunction) != null &&
5899 >                (result = this.result) != null) {
5900 >                for (int b;;) {
5901 >                    if (result.get() != null)
5902 >                        return;
5903 >                    if ((b = preSplit()) <= 0)
5904 >                        break;
5905 >                    new SearchMappingsTask<K,V,U>
5906 >                        (map, this, b, searchFunction, result).fork();
5907 >                }
5908 >                while (result.get() == null) {
5909 >                    V v; U u;
5910 >                    if ((v = advance()) == null) {
5911 >                        propagateCompletion();
5912 >                        break;
5913 >                    }
5914 >                    if ((u = searchFunction.apply(nextKey, v)) != null) {
5915                          if (result.compareAndSet(null, u))
5916 <                            tryCompleteComputation(null);
5916 >                            quietlyCompleteRoot();
5917                          break;
5918                      }
5919                  }
5935            } catch (Throwable ex) {
5936                return tryCompleteComputation(ex);
5920              }
5938            tryComplete(subtasks);
5939            return false;
5921          }
5941        public final U getRawResult() { return result.get(); }
5922      }
5923  
5924      @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5925 <        extends BulkTask<K,V,K> {
5926 <        final BiFun<? super K, ? super K, ? extends K> reducer;
5925 >        extends Traverser<K,V,K> {
5926 >        final BiFunction<? super K, ? super K, ? extends K> reducer;
5927          K result;
5928          ReduceKeysTask<K,V> rights, nextRight;
5929          ReduceKeysTask
5930 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5930 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5931               ReduceKeysTask<K,V> nextRight,
5932 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5932 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
5933              super(m, p, b); this.nextRight = nextRight;
5934              this.reducer = reducer;
5935          }
5936 <        @SuppressWarnings("unchecked") public final boolean exec() {
5937 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5938 <                this.reducer;
5939 <            if (reducer == null)
5940 <                return abortOnNullFunction();
5961 <            try {
5962 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5963 <                    do {} while (!casPending(c = pending, c+1));
5936 >        public final K getRawResult() { return result; }
5937 >        @SuppressWarnings("unchecked") public final void compute() {
5938 >            final BiFunction<? super K, ? super K, ? extends K> reducer;
5939 >            if ((reducer = this.reducer) != null) {
5940 >                for (int b; (b = preSplit()) > 0;)
5941                      (rights = new ReduceKeysTask<K,V>
5942 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5966 <                }
5942 >                     (map, this, b, rights, reducer)).fork();
5943                  K r = null;
5944                  while (advance() != null) {
5945 <                    K u = (K)nextKey;
5946 <                    r = (r == null) ? u : reducer.apply(r, u);
5945 >                    K u = nextKey;
5946 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5947                  }
5948                  result = r;
5949 <                for (ReduceKeysTask<K,V> t = this, s;;) {
5950 <                    int c; BulkTask<K,V,?> par; K tr, sr;
5951 <                    if ((c = t.pending) == 0) {
5952 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5953 <                            if ((sr = s.result) != null)
5954 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5955 <                        }
5956 <                        if ((par = t.parent) == null ||
5957 <                            !(par instanceof ReduceKeysTask)) {
5958 <                            t.quietlyComplete();
5959 <                            break;
5984 <                        }
5985 <                        t = (ReduceKeysTask<K,V>)par;
5949 >                CountedCompleter<?> c;
5950 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5951 >                    ReduceKeysTask<K,V>
5952 >                        t = (ReduceKeysTask<K,V>)c,
5953 >                        s = t.rights;
5954 >                    while (s != null) {
5955 >                        K tr, sr;
5956 >                        if ((sr = s.result) != null)
5957 >                            t.result = (((tr = t.result) == null) ? sr :
5958 >                                        reducer.apply(tr, sr));
5959 >                        s = t.rights = s.nextRight;
5960                      }
5987                    else if (t.casPending(c, c - 1))
5988                        break;
5961                  }
5990            } catch (Throwable ex) {
5991                return tryCompleteComputation(ex);
5962              }
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;
5963          }
6002        public final K getRawResult() { return result; }
5964      }
5965  
5966      @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5967 <        extends BulkTask<K,V,V> {
5968 <        final BiFun<? super V, ? super V, ? extends V> reducer;
5967 >        extends Traverser<K,V,V> {
5968 >        final BiFunction<? super V, ? super V, ? extends V> reducer;
5969          V result;
5970          ReduceValuesTask<K,V> rights, nextRight;
5971          ReduceValuesTask
5972 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
5972 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5973               ReduceValuesTask<K,V> nextRight,
5974 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5974 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
5975              super(m, p, b); this.nextRight = nextRight;
5976              this.reducer = reducer;
5977          }
5978 <        @SuppressWarnings("unchecked") public final boolean exec() {
5979 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5980 <                this.reducer;
5981 <            if (reducer == null)
5982 <                return abortOnNullFunction();
6022 <            try {
6023 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6024 <                    do {} while (!casPending(c = pending, c+1));
5978 >        public final V getRawResult() { return result; }
5979 >        @SuppressWarnings("unchecked") public final void compute() {
5980 >            final BiFunction<? super V, ? super V, ? extends V> reducer;
5981 >            if ((reducer = this.reducer) != null) {
5982 >                for (int b; (b = preSplit()) > 0;)
5983                      (rights = new ReduceValuesTask<K,V>
5984 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5985 <                }
5986 <                V r = null;
5987 <                Object v;
6030 <                while ((v = advance()) != null) {
6031 <                    V u = (V)v;
6032 <                    r = (r == null) ? u : reducer.apply(r, u);
6033 <                }
5984 >                     (map, this, b, rights, reducer)).fork();
5985 >                V r = null, v;
5986 >                while ((v = advance()) != null)
5987 >                    r = (r == null) ? v : reducer.apply(r, v);
5988                  result = r;
5989 <                for (ReduceValuesTask<K,V> t = this, s;;) {
5990 <                    int c; BulkTask<K,V,?> par; V tr, sr;
5991 <                    if ((c = t.pending) == 0) {
5992 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5993 <                            if ((sr = s.result) != null)
5994 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5995 <                        }
5996 <                        if ((par = t.parent) == null ||
5997 <                            !(par instanceof ReduceValuesTask)) {
5998 <                            t.quietlyComplete();
5999 <                            break;
6046 <                        }
6047 <                        t = (ReduceValuesTask<K,V>)par;
5989 >                CountedCompleter<?> c;
5990 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5991 >                    ReduceValuesTask<K,V>
5992 >                        t = (ReduceValuesTask<K,V>)c,
5993 >                        s = t.rights;
5994 >                    while (s != null) {
5995 >                        V tr, sr;
5996 >                        if ((sr = s.result) != null)
5997 >                            t.result = (((tr = t.result) == null) ? sr :
5998 >                                        reducer.apply(tr, sr));
5999 >                        s = t.rights = s.nextRight;
6000                      }
6049                    else if (t.casPending(c, c - 1))
6050                        break;
6001                  }
6052            } catch (Throwable ex) {
6053                return tryCompleteComputation(ex);
6054            }
6055            ReduceValuesTask<K,V> s = rights;
6056            if (s != null && !inForkJoinPool()) {
6057                do  {
6058                    if (s.tryUnfork())
6059                        s.exec();
6060                } while ((s = s.nextRight) != null);
6002              }
6062            return false;
6003          }
6064        public final V getRawResult() { return result; }
6004      }
6005  
6006      @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
6007 <        extends BulkTask<K,V,Map.Entry<K,V>> {
6008 <        final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6007 >        extends Traverser<K,V,Map.Entry<K,V>> {
6008 >        final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6009          Map.Entry<K,V> result;
6010          ReduceEntriesTask<K,V> rights, nextRight;
6011          ReduceEntriesTask
6012 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6012 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6013               ReduceEntriesTask<K,V> nextRight,
6014 <             BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
6014 >             BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
6015              super(m, p, b); this.nextRight = nextRight;
6016              this.reducer = reducer;
6017          }
6018 <        @SuppressWarnings("unchecked") public final boolean exec() {
6019 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
6020 <                this.reducer;
6021 <            if (reducer == null)
6022 <                return abortOnNullFunction();
6084 <            try {
6085 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6086 <                    do {} while (!casPending(c = pending, c+1));
6018 >        public final Map.Entry<K,V> getRawResult() { return result; }
6019 >        @SuppressWarnings("unchecked") public final void compute() {
6020 >            final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6021 >            if ((reducer = this.reducer) != null) {
6022 >                for (int b; (b = preSplit()) > 0;)
6023                      (rights = new ReduceEntriesTask<K,V>
6024 <                     (map, this, b >>>= 1, rights, reducer)).fork();
6089 <                }
6024 >                     (map, this, b, rights, reducer)).fork();
6025                  Map.Entry<K,V> r = null;
6026 <                Object v;
6026 >                V v;
6027                  while ((v = advance()) != null) {
6028 <                    Map.Entry<K,V> u = entryFor((K)nextKey, (V)v);
6028 >                    Map.Entry<K,V> u = entryFor(nextKey, v);
6029                      r = (r == null) ? u : reducer.apply(r, u);
6030                  }
6031                  result = r;
6032 <                for (ReduceEntriesTask<K,V> t = this, s;;) {
6033 <                    int c; BulkTask<K,V,?> par; Map.Entry<K,V> tr, sr;
6034 <                    if ((c = t.pending) == 0) {
6035 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6036 <                            if ((sr = s.result) != null)
6037 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6038 <                        }
6039 <                        if ((par = t.parent) == null ||
6040 <                            !(par instanceof ReduceEntriesTask)) {
6041 <                            t.quietlyComplete();
6042 <                            break;
6108 <                        }
6109 <                        t = (ReduceEntriesTask<K,V>)par;
6032 >                CountedCompleter<?> c;
6033 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6034 >                    ReduceEntriesTask<K,V>
6035 >                        t = (ReduceEntriesTask<K,V>)c,
6036 >                        s = t.rights;
6037 >                    while (s != null) {
6038 >                        Map.Entry<K,V> tr, sr;
6039 >                        if ((sr = s.result) != null)
6040 >                            t.result = (((tr = t.result) == null) ? sr :
6041 >                                        reducer.apply(tr, sr));
6042 >                        s = t.rights = s.nextRight;
6043                      }
6111                    else if (t.casPending(c, c - 1))
6112                        break;
6044                  }
6114            } catch (Throwable ex) {
6115                return tryCompleteComputation(ex);
6116            }
6117            ReduceEntriesTask<K,V> s = rights;
6118            if (s != null && !inForkJoinPool()) {
6119                do  {
6120                    if (s.tryUnfork())
6121                        s.exec();
6122                } while ((s = s.nextRight) != null);
6045              }
6124            return false;
6046          }
6126        public final Map.Entry<K,V> getRawResult() { return result; }
6047      }
6048  
6049      @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
6050 <        extends BulkTask<K,V,U> {
6051 <        final Fun<? super K, ? extends U> transformer;
6052 <        final BiFun<? super U, ? super U, ? extends U> reducer;
6050 >        extends Traverser<K,V,U> {
6051 >        final Function<? super K, ? extends U> transformer;
6052 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
6053          U result;
6054          MapReduceKeysTask<K,V,U> rights, nextRight;
6055          MapReduceKeysTask
6056 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6056 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6057               MapReduceKeysTask<K,V,U> nextRight,
6058 <             Fun<? super K, ? extends U> transformer,
6059 <             BiFun<? super U, ? super U, ? extends U> reducer) {
6058 >             Function<? super K, ? extends U> transformer,
6059 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
6060              super(m, p, b); this.nextRight = nextRight;
6061              this.transformer = transformer;
6062              this.reducer = reducer;
6063          }
6064 <        @SuppressWarnings("unchecked") public final boolean exec() {
6065 <            final Fun<? super K, ? extends U> transformer =
6066 <                this.transformer;
6067 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6068 <                this.reducer;
6069 <            if (transformer == null || reducer == null)
6070 <                return abortOnNullFunction();
6151 <            try {
6152 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6153 <                    do {} while (!casPending(c = pending, c+1));
6064 >        public final U getRawResult() { return result; }
6065 >        @SuppressWarnings("unchecked") public final void compute() {
6066 >            final Function<? super K, ? extends U> transformer;
6067 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
6068 >            if ((transformer = this.transformer) != null &&
6069 >                (reducer = this.reducer) != null) {
6070 >                for (int b; (b = preSplit()) > 0;)
6071                      (rights = new MapReduceKeysTask<K,V,U>
6072 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
6156 <                }
6072 >                     (map, this, b, rights, transformer, reducer)).fork();
6073                  U r = null, u;
6074                  while (advance() != null) {
6075 <                    if ((u = transformer.apply((K)nextKey)) != null)
6075 >                    if ((u = transformer.apply(nextKey)) != null)
6076                          r = (r == null) ? u : reducer.apply(r, u);
6077                  }
6078                  result = r;
6079 <                for (MapReduceKeysTask<K,V,U> t = this, s;;) {
6080 <                    int c; BulkTask<K,V,?> par; U tr, sr;
6081 <                    if ((c = t.pending) == 0) {
6082 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6083 <                            if ((sr = s.result) != null)
6084 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6085 <                        }
6086 <                        if ((par = t.parent) == null ||
6087 <                            !(par instanceof MapReduceKeysTask)) {
6088 <                            t.quietlyComplete();
6089 <                            break;
6174 <                        }
6175 <                        t = (MapReduceKeysTask<K,V,U>)par;
6079 >                CountedCompleter<?> c;
6080 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6081 >                    MapReduceKeysTask<K,V,U>
6082 >                        t = (MapReduceKeysTask<K,V,U>)c,
6083 >                        s = t.rights;
6084 >                    while (s != null) {
6085 >                        U tr, sr;
6086 >                        if ((sr = s.result) != null)
6087 >                            t.result = (((tr = t.result) == null) ? sr :
6088 >                                        reducer.apply(tr, sr));
6089 >                        s = t.rights = s.nextRight;
6090                      }
6177                    else if (t.casPending(c, c - 1))
6178                        break;
6091                  }
6180            } catch (Throwable ex) {
6181                return tryCompleteComputation(ex);
6092              }
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;
6093          }
6192        public final U getRawResult() { return result; }
6094      }
6095  
6096      @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
6097 <        extends BulkTask<K,V,U> {
6098 <        final Fun<? super V, ? extends U> transformer;
6099 <        final BiFun<? super U, ? super U, ? extends U> reducer;
6097 >        extends Traverser<K,V,U> {
6098 >        final Function<? super V, ? extends U> transformer;
6099 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
6100          U result;
6101          MapReduceValuesTask<K,V,U> rights, nextRight;
6102          MapReduceValuesTask
6103 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6103 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6104               MapReduceValuesTask<K,V,U> nextRight,
6105 <             Fun<? super V, ? extends U> transformer,
6106 <             BiFun<? super U, ? super U, ? extends U> reducer) {
6105 >             Function<? super V, ? extends U> transformer,
6106 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
6107              super(m, p, b); this.nextRight = nextRight;
6108              this.transformer = transformer;
6109              this.reducer = reducer;
6110          }
6111 <        @SuppressWarnings("unchecked") public final boolean exec() {
6112 <            final Fun<? super V, ? extends U> transformer =
6113 <                this.transformer;
6114 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6115 <                this.reducer;
6116 <            if (transformer == null || reducer == null)
6117 <                return abortOnNullFunction();
6217 <            try {
6218 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6219 <                    do {} while (!casPending(c = pending, c+1));
6111 >        public final U getRawResult() { return result; }
6112 >        @SuppressWarnings("unchecked") public final void compute() {
6113 >            final Function<? super V, ? extends U> transformer;
6114 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
6115 >            if ((transformer = this.transformer) != null &&
6116 >                (reducer = this.reducer) != null) {
6117 >                for (int b; (b = preSplit()) > 0;)
6118                      (rights = new MapReduceValuesTask<K,V,U>
6119 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
6222 <                }
6119 >                     (map, this, b, rights, transformer, reducer)).fork();
6120                  U r = null, u;
6121 <                Object v;
6121 >                V v;
6122                  while ((v = advance()) != null) {
6123 <                    if ((u = transformer.apply((V)v)) != null)
6123 >                    if ((u = transformer.apply(v)) != null)
6124                          r = (r == null) ? u : reducer.apply(r, u);
6125                  }
6126                  result = r;
6127 <                for (MapReduceValuesTask<K,V,U> t = this, s;;) {
6128 <                    int c; BulkTask<K,V,?> par; U tr, sr;
6129 <                    if ((c = t.pending) == 0) {
6130 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6131 <                            if ((sr = s.result) != null)
6132 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6133 <                        }
6134 <                        if ((par = t.parent) == null ||
6135 <                            !(par instanceof MapReduceValuesTask)) {
6136 <                            t.quietlyComplete();
6137 <                            break;
6241 <                        }
6242 <                        t = (MapReduceValuesTask<K,V,U>)par;
6127 >                CountedCompleter<?> c;
6128 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6129 >                    MapReduceValuesTask<K,V,U>
6130 >                        t = (MapReduceValuesTask<K,V,U>)c,
6131 >                        s = t.rights;
6132 >                    while (s != null) {
6133 >                        U tr, sr;
6134 >                        if ((sr = s.result) != null)
6135 >                            t.result = (((tr = t.result) == null) ? sr :
6136 >                                        reducer.apply(tr, sr));
6137 >                        s = t.rights = s.nextRight;
6138                      }
6244                    else if (t.casPending(c, c - 1))
6245                        break;
6139                  }
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);
6140              }
6257            return false;
6141          }
6259        public final U getRawResult() { return result; }
6142      }
6143  
6144      @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
6145 <        extends BulkTask<K,V,U> {
6146 <        final Fun<Map.Entry<K,V>, ? extends U> transformer;
6147 <        final BiFun<? super U, ? super U, ? extends U> reducer;
6145 >        extends Traverser<K,V,U> {
6146 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
6147 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
6148          U result;
6149          MapReduceEntriesTask<K,V,U> rights, nextRight;
6150          MapReduceEntriesTask
6151 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6151 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6152               MapReduceEntriesTask<K,V,U> nextRight,
6153 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
6154 <             BiFun<? super U, ? super U, ? extends U> reducer) {
6153 >             Function<Map.Entry<K,V>, ? extends U> transformer,
6154 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
6155              super(m, p, b); this.nextRight = nextRight;
6156              this.transformer = transformer;
6157              this.reducer = reducer;
6158          }
6159 <        @SuppressWarnings("unchecked") public final boolean exec() {
6160 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
6161 <                this.transformer;
6162 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6163 <                this.reducer;
6164 <            if (transformer == null || reducer == null)
6165 <                return abortOnNullFunction();
6284 <            try {
6285 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6286 <                    do {} while (!casPending(c = pending, c+1));
6159 >        public final U getRawResult() { return result; }
6160 >        @SuppressWarnings("unchecked") public final void compute() {
6161 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
6162 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
6163 >            if ((transformer = this.transformer) != null &&
6164 >                (reducer = this.reducer) != null) {
6165 >                for (int b; (b = preSplit()) > 0;)
6166                      (rights = new MapReduceEntriesTask<K,V,U>
6167 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
6289 <                }
6167 >                     (map, this, b, rights, transformer, reducer)).fork();
6168                  U r = null, u;
6169 <                Object v;
6169 >                V v;
6170                  while ((v = advance()) != null) {
6171 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
6171 >                    if ((u = transformer.apply(entryFor(nextKey,
6172 >                                                        v))) != null)
6173                          r = (r == null) ? u : reducer.apply(r, u);
6174                  }
6175                  result = r;
6176 <                for (MapReduceEntriesTask<K,V,U> t = this, s;;) {
6177 <                    int c; BulkTask<K,V,?> par; U tr, sr;
6178 <                    if ((c = t.pending) == 0) {
6179 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6180 <                            if ((sr = s.result) != null)
6181 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6182 <                        }
6183 <                        if ((par = t.parent) == null ||
6184 <                            !(par instanceof MapReduceEntriesTask)) {
6185 <                            t.quietlyComplete();
6186 <                            break;
6308 <                        }
6309 <                        t = (MapReduceEntriesTask<K,V,U>)par;
6176 >                CountedCompleter<?> c;
6177 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6178 >                    MapReduceEntriesTask<K,V,U>
6179 >                        t = (MapReduceEntriesTask<K,V,U>)c,
6180 >                        s = t.rights;
6181 >                    while (s != null) {
6182 >                        U tr, sr;
6183 >                        if ((sr = s.result) != null)
6184 >                            t.result = (((tr = t.result) == null) ? sr :
6185 >                                        reducer.apply(tr, sr));
6186 >                        s = t.rights = s.nextRight;
6187                      }
6311                    else if (t.casPending(c, c - 1))
6312                        break;
6188                  }
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);
6189              }
6324            return false;
6190          }
6326        public final U getRawResult() { return result; }
6191      }
6192  
6193      @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
6194 <        extends BulkTask<K,V,U> {
6195 <        final BiFun<? super K, ? super V, ? extends U> transformer;
6196 <        final BiFun<? super U, ? super U, ? extends U> reducer;
6194 >        extends Traverser<K,V,U> {
6195 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
6196 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
6197          U result;
6198          MapReduceMappingsTask<K,V,U> rights, nextRight;
6199          MapReduceMappingsTask
6200 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6200 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6201               MapReduceMappingsTask<K,V,U> nextRight,
6202 <             BiFun<? super K, ? super V, ? extends U> transformer,
6203 <             BiFun<? super U, ? super U, ? extends U> reducer) {
6202 >             BiFunction<? super K, ? super V, ? extends U> transformer,
6203 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
6204              super(m, p, b); this.nextRight = nextRight;
6205              this.transformer = transformer;
6206              this.reducer = reducer;
6207          }
6208 <        @SuppressWarnings("unchecked") public final boolean exec() {
6209 <            final BiFun<? super K, ? super V, ? extends U> transformer =
6210 <                this.transformer;
6211 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6212 <                this.reducer;
6213 <            if (transformer == null || reducer == null)
6214 <                return abortOnNullFunction();
6351 <            try {
6352 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6353 <                    do {} while (!casPending(c = pending, c+1));
6208 >        public final U getRawResult() { return result; }
6209 >        @SuppressWarnings("unchecked") public final void compute() {
6210 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
6211 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
6212 >            if ((transformer = this.transformer) != null &&
6213 >                (reducer = this.reducer) != null) {
6214 >                for (int b; (b = preSplit()) > 0;)
6215                      (rights = new MapReduceMappingsTask<K,V,U>
6216 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
6356 <                }
6216 >                     (map, this, b, rights, transformer, reducer)).fork();
6217                  U r = null, u;
6218 <                Object v;
6218 >                V v;
6219                  while ((v = advance()) != null) {
6220 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
6220 >                    if ((u = transformer.apply(nextKey, v)) != null)
6221                          r = (r == null) ? u : reducer.apply(r, u);
6222                  }
6223                  result = r;
6224 <                for (MapReduceMappingsTask<K,V,U> t = this, s;;) {
6225 <                    int c; BulkTask<K,V,?> par; U tr, sr;
6226 <                    if ((c = t.pending) == 0) {
6227 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6228 <                            if ((sr = s.result) != null)
6229 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6230 <                        }
6231 <                        if ((par = t.parent) == null ||
6232 <                            !(par instanceof MapReduceMappingsTask)) {
6233 <                            t.quietlyComplete();
6234 <                            break;
6375 <                        }
6376 <                        t = (MapReduceMappingsTask<K,V,U>)par;
6224 >                CountedCompleter<?> c;
6225 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6226 >                    MapReduceMappingsTask<K,V,U>
6227 >                        t = (MapReduceMappingsTask<K,V,U>)c,
6228 >                        s = t.rights;
6229 >                    while (s != null) {
6230 >                        U tr, sr;
6231 >                        if ((sr = s.result) != null)
6232 >                            t.result = (((tr = t.result) == null) ? sr :
6233 >                                        reducer.apply(tr, sr));
6234 >                        s = t.rights = s.nextRight;
6235                      }
6378                    else if (t.casPending(c, c - 1))
6379                        break;
6236                  }
6381            } catch (Throwable ex) {
6382                return tryCompleteComputation(ex);
6383            }
6384            MapReduceMappingsTask<K,V,U> s = rights;
6385            if (s != null && !inForkJoinPool()) {
6386                do  {
6387                    if (s.tryUnfork())
6388                        s.exec();
6389                } while ((s = s.nextRight) != null);
6237              }
6391            return false;
6238          }
6393        public final U getRawResult() { return result; }
6239      }
6240  
6241      @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
6242 <        extends BulkTask<K,V,Double> {
6243 <        final ObjectToDouble<? super K> transformer;
6244 <        final DoubleByDoubleToDouble reducer;
6242 >        extends Traverser<K,V,Double> {
6243 >        final ToDoubleFunction<? super K> transformer;
6244 >        final DoubleBinaryOperator reducer;
6245          final double basis;
6246          double result;
6247          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
6248          MapReduceKeysToDoubleTask
6249 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6249 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6250               MapReduceKeysToDoubleTask<K,V> nextRight,
6251 <             ObjectToDouble<? super K> transformer,
6251 >             ToDoubleFunction<? super K> transformer,
6252               double basis,
6253 <             DoubleByDoubleToDouble reducer) {
6253 >             DoubleBinaryOperator reducer) {
6254              super(m, p, b); this.nextRight = nextRight;
6255              this.transformer = transformer;
6256              this.basis = basis; this.reducer = reducer;
6257          }
6258 <        @SuppressWarnings("unchecked") public final boolean exec() {
6259 <            final ObjectToDouble<? super K> transformer =
6260 <                this.transformer;
6261 <            final DoubleByDoubleToDouble reducer = this.reducer;
6262 <            if (transformer == null || reducer == null)
6263 <                return abortOnNullFunction();
6264 <            try {
6265 <                final double id = this.basis;
6421 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6422 <                    do {} while (!casPending(c = pending, c+1));
6258 >        public final Double getRawResult() { return result; }
6259 >        @SuppressWarnings("unchecked") public final void compute() {
6260 >            final ToDoubleFunction<? super K> transformer;
6261 >            final DoubleBinaryOperator reducer;
6262 >            if ((transformer = this.transformer) != null &&
6263 >                (reducer = this.reducer) != null) {
6264 >                double r = this.basis;
6265 >                for (int b; (b = preSplit()) > 0;)
6266                      (rights = new MapReduceKeysToDoubleTask<K,V>
6267 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6425 <                }
6426 <                double r = id;
6267 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6268                  while (advance() != null)
6269 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
6269 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey));
6270                  result = r;
6271 <                for (MapReduceKeysToDoubleTask<K,V> t = this, s;;) {
6272 <                    int c; BulkTask<K,V,?> par;
6273 <                    if ((c = t.pending) == 0) {
6274 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6275 <                            t.result = reducer.apply(t.result, s.result);
6276 <                        }
6277 <                        if ((par = t.parent) == null ||
6278 <                            !(par instanceof MapReduceKeysToDoubleTask)) {
6438 <                            t.quietlyComplete();
6439 <                            break;
6440 <                        }
6441 <                        t = (MapReduceKeysToDoubleTask<K,V>)par;
6271 >                CountedCompleter<?> c;
6272 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6273 >                    MapReduceKeysToDoubleTask<K,V>
6274 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
6275 >                        s = t.rights;
6276 >                    while (s != null) {
6277 >                        t.result = reducer.applyAsDouble(t.result, s.result);
6278 >                        s = t.rights = s.nextRight;
6279                      }
6443                    else if (t.casPending(c, c - 1))
6444                        break;
6280                  }
6446            } catch (Throwable ex) {
6447                return tryCompleteComputation(ex);
6281              }
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;
6282          }
6458        public final Double getRawResult() { return result; }
6283      }
6284  
6285      @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
6286 <        extends BulkTask<K,V,Double> {
6287 <        final ObjectToDouble<? super V> transformer;
6288 <        final DoubleByDoubleToDouble reducer;
6286 >        extends Traverser<K,V,Double> {
6287 >        final ToDoubleFunction<? super V> transformer;
6288 >        final DoubleBinaryOperator reducer;
6289          final double basis;
6290          double result;
6291          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
6292          MapReduceValuesToDoubleTask
6293 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6293 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6294               MapReduceValuesToDoubleTask<K,V> nextRight,
6295 <             ObjectToDouble<? super V> transformer,
6295 >             ToDoubleFunction<? super V> transformer,
6296               double basis,
6297 <             DoubleByDoubleToDouble reducer) {
6297 >             DoubleBinaryOperator reducer) {
6298              super(m, p, b); this.nextRight = nextRight;
6299              this.transformer = transformer;
6300              this.basis = basis; this.reducer = reducer;
6301          }
6302 <        @SuppressWarnings("unchecked") public final boolean exec() {
6303 <            final ObjectToDouble<? super V> transformer =
6304 <                this.transformer;
6305 <            final DoubleByDoubleToDouble reducer = this.reducer;
6306 <            if (transformer == null || reducer == null)
6307 <                return abortOnNullFunction();
6308 <            try {
6309 <                final double id = this.basis;
6486 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6487 <                    do {} while (!casPending(c = pending, c+1));
6302 >        public final Double getRawResult() { return result; }
6303 >        @SuppressWarnings("unchecked") public final void compute() {
6304 >            final ToDoubleFunction<? super V> transformer;
6305 >            final DoubleBinaryOperator reducer;
6306 >            if ((transformer = this.transformer) != null &&
6307 >                (reducer = this.reducer) != null) {
6308 >                double r = this.basis;
6309 >                for (int b; (b = preSplit()) > 0;)
6310                      (rights = new MapReduceValuesToDoubleTask<K,V>
6311 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6312 <                }
6491 <                double r = id;
6492 <                Object v;
6311 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6312 >                V v;
6313                  while ((v = advance()) != null)
6314 <                    r = reducer.apply(r, transformer.apply((V)v));
6314 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
6315                  result = r;
6316 <                for (MapReduceValuesToDoubleTask<K,V> t = this, s;;) {
6317 <                    int c; BulkTask<K,V,?> par;
6318 <                    if ((c = t.pending) == 0) {
6319 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6320 <                            t.result = reducer.apply(t.result, s.result);
6321 <                        }
6322 <                        if ((par = t.parent) == null ||
6323 <                            !(par instanceof MapReduceValuesToDoubleTask)) {
6504 <                            t.quietlyComplete();
6505 <                            break;
6506 <                        }
6507 <                        t = (MapReduceValuesToDoubleTask<K,V>)par;
6316 >                CountedCompleter<?> c;
6317 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6318 >                    MapReduceValuesToDoubleTask<K,V>
6319 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
6320 >                        s = t.rights;
6321 >                    while (s != null) {
6322 >                        t.result = reducer.applyAsDouble(t.result, s.result);
6323 >                        s = t.rights = s.nextRight;
6324                      }
6509                    else if (t.casPending(c, c - 1))
6510                        break;
6325                  }
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);
6326              }
6522            return false;
6327          }
6524        public final Double getRawResult() { return result; }
6328      }
6329  
6330      @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
6331 <        extends BulkTask<K,V,Double> {
6332 <        final ObjectToDouble<Map.Entry<K,V>> transformer;
6333 <        final DoubleByDoubleToDouble reducer;
6331 >        extends Traverser<K,V,Double> {
6332 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
6333 >        final DoubleBinaryOperator reducer;
6334          final double basis;
6335          double result;
6336          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
6337          MapReduceEntriesToDoubleTask
6338 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6338 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6339               MapReduceEntriesToDoubleTask<K,V> nextRight,
6340 <             ObjectToDouble<Map.Entry<K,V>> transformer,
6340 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
6341               double basis,
6342 <             DoubleByDoubleToDouble reducer) {
6342 >             DoubleBinaryOperator reducer) {
6343              super(m, p, b); this.nextRight = nextRight;
6344              this.transformer = transformer;
6345              this.basis = basis; this.reducer = reducer;
6346          }
6347 <        @SuppressWarnings("unchecked") public final boolean exec() {
6348 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
6349 <                this.transformer;
6350 <            final DoubleByDoubleToDouble reducer = this.reducer;
6351 <            if (transformer == null || reducer == null)
6352 <                return abortOnNullFunction();
6353 <            try {
6354 <                final double id = this.basis;
6552 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6553 <                    do {} while (!casPending(c = pending, c+1));
6347 >        public final Double getRawResult() { return result; }
6348 >        @SuppressWarnings("unchecked") public final void compute() {
6349 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
6350 >            final DoubleBinaryOperator reducer;
6351 >            if ((transformer = this.transformer) != null &&
6352 >                (reducer = this.reducer) != null) {
6353 >                double r = this.basis;
6354 >                for (int b; (b = preSplit()) > 0;)
6355                      (rights = new MapReduceEntriesToDoubleTask<K,V>
6356 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6357 <                }
6557 <                double r = id;
6558 <                Object v;
6356 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6357 >                V v;
6358                  while ((v = advance()) != null)
6359 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6359 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(nextKey,
6360 >                                                                    v)));
6361                  result = r;
6362 <                for (MapReduceEntriesToDoubleTask<K,V> t = this, s;;) {
6363 <                    int c; BulkTask<K,V,?> par;
6364 <                    if ((c = t.pending) == 0) {
6365 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6366 <                            t.result = reducer.apply(t.result, s.result);
6367 <                        }
6368 <                        if ((par = t.parent) == null ||
6369 <                            !(par instanceof MapReduceEntriesToDoubleTask)) {
6570 <                            t.quietlyComplete();
6571 <                            break;
6572 <                        }
6573 <                        t = (MapReduceEntriesToDoubleTask<K,V>)par;
6362 >                CountedCompleter<?> c;
6363 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6364 >                    MapReduceEntriesToDoubleTask<K,V>
6365 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
6366 >                        s = t.rights;
6367 >                    while (s != null) {
6368 >                        t.result = reducer.applyAsDouble(t.result, s.result);
6369 >                        s = t.rights = s.nextRight;
6370                      }
6575                    else if (t.casPending(c, c - 1))
6576                        break;
6371                  }
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);
6372              }
6588            return false;
6373          }
6590        public final Double getRawResult() { return result; }
6374      }
6375  
6376      @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
6377 <        extends BulkTask<K,V,Double> {
6378 <        final ObjectByObjectToDouble<? super K, ? super V> transformer;
6379 <        final DoubleByDoubleToDouble reducer;
6377 >        extends Traverser<K,V,Double> {
6378 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
6379 >        final DoubleBinaryOperator reducer;
6380          final double basis;
6381          double result;
6382          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
6383          MapReduceMappingsToDoubleTask
6384 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6384 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6385               MapReduceMappingsToDoubleTask<K,V> nextRight,
6386 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
6386 >             ToDoubleBiFunction<? super K, ? super V> transformer,
6387               double basis,
6388 <             DoubleByDoubleToDouble reducer) {
6388 >             DoubleBinaryOperator reducer) {
6389              super(m, p, b); this.nextRight = nextRight;
6390              this.transformer = transformer;
6391              this.basis = basis; this.reducer = reducer;
6392          }
6393 <        @SuppressWarnings("unchecked") public final boolean exec() {
6394 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
6395 <                this.transformer;
6396 <            final DoubleByDoubleToDouble reducer = this.reducer;
6397 <            if (transformer == null || reducer == null)
6398 <                return abortOnNullFunction();
6399 <            try {
6400 <                final double id = this.basis;
6618 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6619 <                    do {} while (!casPending(c = pending, c+1));
6393 >        public final Double getRawResult() { return result; }
6394 >        @SuppressWarnings("unchecked") public final void compute() {
6395 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
6396 >            final DoubleBinaryOperator reducer;
6397 >            if ((transformer = this.transformer) != null &&
6398 >                (reducer = this.reducer) != null) {
6399 >                double r = this.basis;
6400 >                for (int b; (b = preSplit()) > 0;)
6401                      (rights = new MapReduceMappingsToDoubleTask<K,V>
6402 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6403 <                }
6623 <                double r = id;
6624 <                Object v;
6402 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6403 >                V v;
6404                  while ((v = advance()) != null)
6405 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6405 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey, v));
6406                  result = r;
6407 <                for (MapReduceMappingsToDoubleTask<K,V> t = this, s;;) {
6408 <                    int c; BulkTask<K,V,?> par;
6409 <                    if ((c = t.pending) == 0) {
6410 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6411 <                            t.result = reducer.apply(t.result, s.result);
6412 <                        }
6413 <                        if ((par = t.parent) == null ||
6414 <                            !(par instanceof MapReduceMappingsToDoubleTask)) {
6636 <                            t.quietlyComplete();
6637 <                            break;
6638 <                        }
6639 <                        t = (MapReduceMappingsToDoubleTask<K,V>)par;
6407 >                CountedCompleter<?> c;
6408 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6409 >                    MapReduceMappingsToDoubleTask<K,V>
6410 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
6411 >                        s = t.rights;
6412 >                    while (s != null) {
6413 >                        t.result = reducer.applyAsDouble(t.result, s.result);
6414 >                        s = t.rights = s.nextRight;
6415                      }
6641                    else if (t.casPending(c, c - 1))
6642                        break;
6416                  }
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);
6417              }
6654            return false;
6418          }
6656        public final Double getRawResult() { return result; }
6419      }
6420  
6421      @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
6422 <        extends BulkTask<K,V,Long> {
6423 <        final ObjectToLong<? super K> transformer;
6424 <        final LongByLongToLong reducer;
6422 >        extends Traverser<K,V,Long> {
6423 >        final ToLongFunction<? super K> transformer;
6424 >        final LongBinaryOperator reducer;
6425          final long basis;
6426          long result;
6427          MapReduceKeysToLongTask<K,V> rights, nextRight;
6428          MapReduceKeysToLongTask
6429 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6429 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6430               MapReduceKeysToLongTask<K,V> nextRight,
6431 <             ObjectToLong<? super K> transformer,
6431 >             ToLongFunction<? super K> transformer,
6432               long basis,
6433 <             LongByLongToLong reducer) {
6433 >             LongBinaryOperator reducer) {
6434              super(m, p, b); this.nextRight = nextRight;
6435              this.transformer = transformer;
6436              this.basis = basis; this.reducer = reducer;
6437          }
6438 <        @SuppressWarnings("unchecked") public final boolean exec() {
6439 <            final ObjectToLong<? super K> transformer =
6440 <                this.transformer;
6441 <            final LongByLongToLong reducer = this.reducer;
6442 <            if (transformer == null || reducer == null)
6443 <                return abortOnNullFunction();
6444 <            try {
6445 <                final long id = this.basis;
6684 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6685 <                    do {} while (!casPending(c = pending, c+1));
6438 >        public final Long getRawResult() { return result; }
6439 >        @SuppressWarnings("unchecked") public final void compute() {
6440 >            final ToLongFunction<? super K> transformer;
6441 >            final LongBinaryOperator reducer;
6442 >            if ((transformer = this.transformer) != null &&
6443 >                (reducer = this.reducer) != null) {
6444 >                long r = this.basis;
6445 >                for (int b; (b = preSplit()) > 0;)
6446                      (rights = new MapReduceKeysToLongTask<K,V>
6447 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6688 <                }
6689 <                long r = id;
6447 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6448                  while (advance() != null)
6449 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
6449 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey));
6450                  result = r;
6451 <                for (MapReduceKeysToLongTask<K,V> t = this, s;;) {
6452 <                    int c; BulkTask<K,V,?> par;
6453 <                    if ((c = t.pending) == 0) {
6454 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6455 <                            t.result = reducer.apply(t.result, s.result);
6456 <                        }
6457 <                        if ((par = t.parent) == null ||
6458 <                            !(par instanceof MapReduceKeysToLongTask)) {
6701 <                            t.quietlyComplete();
6702 <                            break;
6703 <                        }
6704 <                        t = (MapReduceKeysToLongTask<K,V>)par;
6451 >                CountedCompleter<?> c;
6452 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6453 >                    MapReduceKeysToLongTask<K,V>
6454 >                        t = (MapReduceKeysToLongTask<K,V>)c,
6455 >                        s = t.rights;
6456 >                    while (s != null) {
6457 >                        t.result = reducer.applyAsLong(t.result, s.result);
6458 >                        s = t.rights = s.nextRight;
6459                      }
6706                    else if (t.casPending(c, c - 1))
6707                        break;
6460                  }
6709            } catch (Throwable ex) {
6710                return tryCompleteComputation(ex);
6461              }
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;
6462          }
6721        public final Long getRawResult() { return result; }
6463      }
6464  
6465      @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
6466 <        extends BulkTask<K,V,Long> {
6467 <        final ObjectToLong<? super V> transformer;
6468 <        final LongByLongToLong reducer;
6466 >        extends Traverser<K,V,Long> {
6467 >        final ToLongFunction<? super V> transformer;
6468 >        final LongBinaryOperator reducer;
6469          final long basis;
6470          long result;
6471          MapReduceValuesToLongTask<K,V> rights, nextRight;
6472          MapReduceValuesToLongTask
6473 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6473 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6474               MapReduceValuesToLongTask<K,V> nextRight,
6475 <             ObjectToLong<? super V> transformer,
6475 >             ToLongFunction<? super V> transformer,
6476               long basis,
6477 <             LongByLongToLong reducer) {
6477 >             LongBinaryOperator reducer) {
6478              super(m, p, b); this.nextRight = nextRight;
6479              this.transformer = transformer;
6480              this.basis = basis; this.reducer = reducer;
6481          }
6482 <        @SuppressWarnings("unchecked") public final boolean exec() {
6483 <            final ObjectToLong<? super V> transformer =
6484 <                this.transformer;
6485 <            final LongByLongToLong reducer = this.reducer;
6486 <            if (transformer == null || reducer == null)
6487 <                return abortOnNullFunction();
6488 <            try {
6489 <                final long id = this.basis;
6749 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6750 <                    do {} while (!casPending(c = pending, c+1));
6482 >        public final Long getRawResult() { return result; }
6483 >        @SuppressWarnings("unchecked") public final void compute() {
6484 >            final ToLongFunction<? super V> transformer;
6485 >            final LongBinaryOperator reducer;
6486 >            if ((transformer = this.transformer) != null &&
6487 >                (reducer = this.reducer) != null) {
6488 >                long r = this.basis;
6489 >                for (int b; (b = preSplit()) > 0;)
6490                      (rights = new MapReduceValuesToLongTask<K,V>
6491 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6492 <                }
6754 <                long r = id;
6755 <                Object v;
6491 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6492 >                V v;
6493                  while ((v = advance()) != null)
6494 <                    r = reducer.apply(r, transformer.apply((V)v));
6494 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(v));
6495                  result = r;
6496 <                for (MapReduceValuesToLongTask<K,V> t = this, s;;) {
6497 <                    int c; BulkTask<K,V,?> par;
6498 <                    if ((c = t.pending) == 0) {
6499 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6500 <                            t.result = reducer.apply(t.result, s.result);
6501 <                        }
6502 <                        if ((par = t.parent) == null ||
6503 <                            !(par instanceof MapReduceValuesToLongTask)) {
6767 <                            t.quietlyComplete();
6768 <                            break;
6769 <                        }
6770 <                        t = (MapReduceValuesToLongTask<K,V>)par;
6496 >                CountedCompleter<?> c;
6497 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6498 >                    MapReduceValuesToLongTask<K,V>
6499 >                        t = (MapReduceValuesToLongTask<K,V>)c,
6500 >                        s = t.rights;
6501 >                    while (s != null) {
6502 >                        t.result = reducer.applyAsLong(t.result, s.result);
6503 >                        s = t.rights = s.nextRight;
6504                      }
6772                    else if (t.casPending(c, c - 1))
6773                        break;
6505                  }
6775            } catch (Throwable ex) {
6776                return tryCompleteComputation(ex);
6777            }
6778            MapReduceValuesToLongTask<K,V> s = rights;
6779            if (s != null && !inForkJoinPool()) {
6780                do  {
6781                    if (s.tryUnfork())
6782                        s.exec();
6783                } while ((s = s.nextRight) != null);
6506              }
6785            return false;
6507          }
6787        public final Long getRawResult() { return result; }
6508      }
6509  
6510      @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6511 <        extends BulkTask<K,V,Long> {
6512 <        final ObjectToLong<Map.Entry<K,V>> transformer;
6513 <        final LongByLongToLong reducer;
6511 >        extends Traverser<K,V,Long> {
6512 >        final ToLongFunction<Map.Entry<K,V>> transformer;
6513 >        final LongBinaryOperator reducer;
6514          final long basis;
6515          long result;
6516          MapReduceEntriesToLongTask<K,V> rights, nextRight;
6517          MapReduceEntriesToLongTask
6518 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6518 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6519               MapReduceEntriesToLongTask<K,V> nextRight,
6520 <             ObjectToLong<Map.Entry<K,V>> transformer,
6520 >             ToLongFunction<Map.Entry<K,V>> transformer,
6521               long basis,
6522 <             LongByLongToLong reducer) {
6522 >             LongBinaryOperator reducer) {
6523              super(m, p, b); this.nextRight = nextRight;
6524              this.transformer = transformer;
6525              this.basis = basis; this.reducer = reducer;
6526          }
6527 <        @SuppressWarnings("unchecked") public final boolean exec() {
6528 <            final ObjectToLong<Map.Entry<K,V>> transformer =
6529 <                this.transformer;
6530 <            final LongByLongToLong reducer = this.reducer;
6531 <            if (transformer == null || reducer == null)
6532 <                return abortOnNullFunction();
6533 <            try {
6534 <                final long id = this.basis;
6815 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6816 <                    do {} while (!casPending(c = pending, c+1));
6527 >        public final Long getRawResult() { return result; }
6528 >        @SuppressWarnings("unchecked") public final void compute() {
6529 >            final ToLongFunction<Map.Entry<K,V>> transformer;
6530 >            final LongBinaryOperator reducer;
6531 >            if ((transformer = this.transformer) != null &&
6532 >                (reducer = this.reducer) != null) {
6533 >                long r = this.basis;
6534 >                for (int b; (b = preSplit()) > 0;)
6535                      (rights = new MapReduceEntriesToLongTask<K,V>
6536 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6537 <                }
6820 <                long r = id;
6821 <                Object v;
6536 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6537 >                V v;
6538                  while ((v = advance()) != null)
6539 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6539 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(nextKey, v)));
6540                  result = r;
6541 <                for (MapReduceEntriesToLongTask<K,V> t = this, s;;) {
6542 <                    int c; BulkTask<K,V,?> par;
6543 <                    if ((c = t.pending) == 0) {
6544 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6545 <                            t.result = reducer.apply(t.result, s.result);
6546 <                        }
6547 <                        if ((par = t.parent) == null ||
6548 <                            !(par instanceof MapReduceEntriesToLongTask)) {
6833 <                            t.quietlyComplete();
6834 <                            break;
6835 <                        }
6836 <                        t = (MapReduceEntriesToLongTask<K,V>)par;
6541 >                CountedCompleter<?> c;
6542 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6543 >                    MapReduceEntriesToLongTask<K,V>
6544 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
6545 >                        s = t.rights;
6546 >                    while (s != null) {
6547 >                        t.result = reducer.applyAsLong(t.result, s.result);
6548 >                        s = t.rights = s.nextRight;
6549                      }
6838                    else if (t.casPending(c, c - 1))
6839                        break;
6550                  }
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);
6551              }
6851            return false;
6552          }
6853        public final Long getRawResult() { return result; }
6553      }
6554  
6555      @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6556 <        extends BulkTask<K,V,Long> {
6557 <        final ObjectByObjectToLong<? super K, ? super V> transformer;
6558 <        final LongByLongToLong reducer;
6556 >        extends Traverser<K,V,Long> {
6557 >        final ToLongBiFunction<? super K, ? super V> transformer;
6558 >        final LongBinaryOperator reducer;
6559          final long basis;
6560          long result;
6561          MapReduceMappingsToLongTask<K,V> rights, nextRight;
6562          MapReduceMappingsToLongTask
6563 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6563 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6564               MapReduceMappingsToLongTask<K,V> nextRight,
6565 <             ObjectByObjectToLong<? super K, ? super V> transformer,
6565 >             ToLongBiFunction<? super K, ? super V> transformer,
6566               long basis,
6567 <             LongByLongToLong reducer) {
6567 >             LongBinaryOperator reducer) {
6568              super(m, p, b); this.nextRight = nextRight;
6569              this.transformer = transformer;
6570              this.basis = basis; this.reducer = reducer;
6571          }
6572 <        @SuppressWarnings("unchecked") public final boolean exec() {
6573 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
6574 <                this.transformer;
6575 <            final LongByLongToLong reducer = this.reducer;
6576 <            if (transformer == null || reducer == null)
6577 <                return abortOnNullFunction();
6578 <            try {
6579 <                final long id = this.basis;
6881 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6882 <                    do {} while (!casPending(c = pending, c+1));
6572 >        public final Long getRawResult() { return result; }
6573 >        @SuppressWarnings("unchecked") public final void compute() {
6574 >            final ToLongBiFunction<? super K, ? super V> transformer;
6575 >            final LongBinaryOperator reducer;
6576 >            if ((transformer = this.transformer) != null &&
6577 >                (reducer = this.reducer) != null) {
6578 >                long r = this.basis;
6579 >                for (int b; (b = preSplit()) > 0;)
6580                      (rights = new MapReduceMappingsToLongTask<K,V>
6581 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6582 <                }
6886 <                long r = id;
6887 <                Object v;
6581 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6582 >                V v;
6583                  while ((v = advance()) != null)
6584 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6584 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey, v));
6585                  result = r;
6586 <                for (MapReduceMappingsToLongTask<K,V> t = this, s;;) {
6587 <                    int c; BulkTask<K,V,?> par;
6588 <                    if ((c = t.pending) == 0) {
6589 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6590 <                            t.result = reducer.apply(t.result, s.result);
6591 <                        }
6592 <                        if ((par = t.parent) == null ||
6593 <                            !(par instanceof MapReduceMappingsToLongTask)) {
6899 <                            t.quietlyComplete();
6900 <                            break;
6901 <                        }
6902 <                        t = (MapReduceMappingsToLongTask<K,V>)par;
6586 >                CountedCompleter<?> c;
6587 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6588 >                    MapReduceMappingsToLongTask<K,V>
6589 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
6590 >                        s = t.rights;
6591 >                    while (s != null) {
6592 >                        t.result = reducer.applyAsLong(t.result, s.result);
6593 >                        s = t.rights = s.nextRight;
6594                      }
6904                    else if (t.casPending(c, c - 1))
6905                        break;
6595                  }
6907            } catch (Throwable ex) {
6908                return tryCompleteComputation(ex);
6596              }
6910            MapReduceMappingsToLongTask<K,V> s = rights;
6911            if (s != null && !inForkJoinPool()) {
6912                do  {
6913                    if (s.tryUnfork())
6914                        s.exec();
6915                } while ((s = s.nextRight) != null);
6916            }
6917            return false;
6597          }
6919        public final Long getRawResult() { return result; }
6598      }
6599  
6600      @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6601 <        extends BulkTask<K,V,Integer> {
6602 <        final ObjectToInt<? super K> transformer;
6603 <        final IntByIntToInt reducer;
6601 >        extends Traverser<K,V,Integer> {
6602 >        final ToIntFunction<? super K> transformer;
6603 >        final IntBinaryOperator reducer;
6604          final int basis;
6605          int result;
6606          MapReduceKeysToIntTask<K,V> rights, nextRight;
6607          MapReduceKeysToIntTask
6608 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6608 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6609               MapReduceKeysToIntTask<K,V> nextRight,
6610 <             ObjectToInt<? super K> transformer,
6610 >             ToIntFunction<? super K> transformer,
6611               int basis,
6612 <             IntByIntToInt reducer) {
6612 >             IntBinaryOperator reducer) {
6613              super(m, p, b); this.nextRight = nextRight;
6614              this.transformer = transformer;
6615              this.basis = basis; this.reducer = reducer;
6616          }
6617 <        @SuppressWarnings("unchecked") public final boolean exec() {
6618 <            final ObjectToInt<? super K> transformer =
6619 <                this.transformer;
6620 <            final IntByIntToInt reducer = this.reducer;
6621 <            if (transformer == null || reducer == null)
6622 <                return abortOnNullFunction();
6623 <            try {
6624 <                final int id = this.basis;
6947 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6948 <                    do {} while (!casPending(c = pending, c+1));
6617 >        public final Integer getRawResult() { return result; }
6618 >        @SuppressWarnings("unchecked") public final void compute() {
6619 >            final ToIntFunction<? super K> transformer;
6620 >            final IntBinaryOperator reducer;
6621 >            if ((transformer = this.transformer) != null &&
6622 >                (reducer = this.reducer) != null) {
6623 >                int r = this.basis;
6624 >                for (int b; (b = preSplit()) > 0;)
6625                      (rights = new MapReduceKeysToIntTask<K,V>
6626 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6951 <                }
6952 <                int r = id;
6626 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6627                  while (advance() != null)
6628 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
6628 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey));
6629                  result = r;
6630 <                for (MapReduceKeysToIntTask<K,V> t = this, s;;) {
6631 <                    int c; BulkTask<K,V,?> par;
6632 <                    if ((c = t.pending) == 0) {
6633 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6634 <                            t.result = reducer.apply(t.result, s.result);
6635 <                        }
6636 <                        if ((par = t.parent) == null ||
6637 <                            !(par instanceof MapReduceKeysToIntTask)) {
6964 <                            t.quietlyComplete();
6965 <                            break;
6966 <                        }
6967 <                        t = (MapReduceKeysToIntTask<K,V>)par;
6630 >                CountedCompleter<?> c;
6631 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6632 >                    MapReduceKeysToIntTask<K,V>
6633 >                        t = (MapReduceKeysToIntTask<K,V>)c,
6634 >                        s = t.rights;
6635 >                    while (s != null) {
6636 >                        t.result = reducer.applyAsInt(t.result, s.result);
6637 >                        s = t.rights = s.nextRight;
6638                      }
6969                    else if (t.casPending(c, c - 1))
6970                        break;
6639                  }
6972            } catch (Throwable ex) {
6973                return tryCompleteComputation(ex);
6640              }
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;
6641          }
6984        public final Integer getRawResult() { return result; }
6642      }
6643  
6644      @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6645 <        extends BulkTask<K,V,Integer> {
6646 <        final ObjectToInt<? super V> transformer;
6647 <        final IntByIntToInt reducer;
6645 >        extends Traverser<K,V,Integer> {
6646 >        final ToIntFunction<? super V> transformer;
6647 >        final IntBinaryOperator reducer;
6648          final int basis;
6649          int result;
6650          MapReduceValuesToIntTask<K,V> rights, nextRight;
6651          MapReduceValuesToIntTask
6652 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6652 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6653               MapReduceValuesToIntTask<K,V> nextRight,
6654 <             ObjectToInt<? super V> transformer,
6654 >             ToIntFunction<? super V> transformer,
6655               int basis,
6656 <             IntByIntToInt reducer) {
6656 >             IntBinaryOperator reducer) {
6657              super(m, p, b); this.nextRight = nextRight;
6658              this.transformer = transformer;
6659              this.basis = basis; this.reducer = reducer;
6660          }
6661 <        @SuppressWarnings("unchecked") public final boolean exec() {
6662 <            final ObjectToInt<? super V> transformer =
6663 <                this.transformer;
6664 <            final IntByIntToInt reducer = this.reducer;
6665 <            if (transformer == null || reducer == null)
6666 <                return abortOnNullFunction();
6667 <            try {
6668 <                final int id = this.basis;
7012 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
7013 <                    do {} while (!casPending(c = pending, c+1));
6661 >        public final Integer getRawResult() { return result; }
6662 >        @SuppressWarnings("unchecked") public final void compute() {
6663 >            final ToIntFunction<? super V> transformer;
6664 >            final IntBinaryOperator reducer;
6665 >            if ((transformer = this.transformer) != null &&
6666 >                (reducer = this.reducer) != null) {
6667 >                int r = this.basis;
6668 >                for (int b; (b = preSplit()) > 0;)
6669                      (rights = new MapReduceValuesToIntTask<K,V>
6670 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6671 <                }
7017 <                int r = id;
7018 <                Object v;
6670 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6671 >                V v;
6672                  while ((v = advance()) != null)
6673 <                    r = reducer.apply(r, transformer.apply((V)v));
6673 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(v));
6674                  result = r;
6675 <                for (MapReduceValuesToIntTask<K,V> t = this, s;;) {
6676 <                    int c; BulkTask<K,V,?> par;
6677 <                    if ((c = t.pending) == 0) {
6678 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6679 <                            t.result = reducer.apply(t.result, s.result);
6680 <                        }
6681 <                        if ((par = t.parent) == null ||
6682 <                            !(par instanceof MapReduceValuesToIntTask)) {
7030 <                            t.quietlyComplete();
7031 <                            break;
7032 <                        }
7033 <                        t = (MapReduceValuesToIntTask<K,V>)par;
6675 >                CountedCompleter<?> c;
6676 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6677 >                    MapReduceValuesToIntTask<K,V>
6678 >                        t = (MapReduceValuesToIntTask<K,V>)c,
6679 >                        s = t.rights;
6680 >                    while (s != null) {
6681 >                        t.result = reducer.applyAsInt(t.result, s.result);
6682 >                        s = t.rights = s.nextRight;
6683                      }
7035                    else if (t.casPending(c, c - 1))
7036                        break;
6684                  }
7038            } catch (Throwable ex) {
7039                return tryCompleteComputation(ex);
7040            }
7041            MapReduceValuesToIntTask<K,V> s = rights;
7042            if (s != null && !inForkJoinPool()) {
7043                do  {
7044                    if (s.tryUnfork())
7045                        s.exec();
7046                } while ((s = s.nextRight) != null);
6685              }
7048            return false;
6686          }
7050        public final Integer getRawResult() { return result; }
6687      }
6688  
6689      @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6690 <        extends BulkTask<K,V,Integer> {
6691 <        final ObjectToInt<Map.Entry<K,V>> transformer;
6692 <        final IntByIntToInt reducer;
6690 >        extends Traverser<K,V,Integer> {
6691 >        final ToIntFunction<Map.Entry<K,V>> transformer;
6692 >        final IntBinaryOperator reducer;
6693          final int basis;
6694          int result;
6695          MapReduceEntriesToIntTask<K,V> rights, nextRight;
6696          MapReduceEntriesToIntTask
6697 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6697 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6698               MapReduceEntriesToIntTask<K,V> nextRight,
6699 <             ObjectToInt<Map.Entry<K,V>> transformer,
6699 >             ToIntFunction<Map.Entry<K,V>> transformer,
6700               int basis,
6701 <             IntByIntToInt reducer) {
6701 >             IntBinaryOperator reducer) {
6702              super(m, p, b); this.nextRight = nextRight;
6703              this.transformer = transformer;
6704              this.basis = basis; this.reducer = reducer;
6705          }
6706 <        @SuppressWarnings("unchecked") public final boolean exec() {
6707 <            final ObjectToInt<Map.Entry<K,V>> transformer =
6708 <                this.transformer;
6709 <            final IntByIntToInt reducer = this.reducer;
6710 <            if (transformer == null || reducer == null)
6711 <                return abortOnNullFunction();
6712 <            try {
6713 <                final int id = this.basis;
7078 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
7079 <                    do {} while (!casPending(c = pending, c+1));
6706 >        public final Integer getRawResult() { return result; }
6707 >        @SuppressWarnings("unchecked") public final void compute() {
6708 >            final ToIntFunction<Map.Entry<K,V>> transformer;
6709 >            final IntBinaryOperator reducer;
6710 >            if ((transformer = this.transformer) != null &&
6711 >                (reducer = this.reducer) != null) {
6712 >                int r = this.basis;
6713 >                for (int b; (b = preSplit()) > 0;)
6714                      (rights = new MapReduceEntriesToIntTask<K,V>
6715 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6716 <                }
7083 <                int r = id;
7084 <                Object v;
6715 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6716 >                V v;
6717                  while ((v = advance()) != null)
6718 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6718 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(nextKey,
6719 >                                                                    v)));
6720                  result = r;
6721 <                for (MapReduceEntriesToIntTask<K,V> t = this, s;;) {
6722 <                    int c; BulkTask<K,V,?> par;
6723 <                    if ((c = t.pending) == 0) {
6724 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6725 <                            t.result = reducer.apply(t.result, s.result);
6726 <                        }
6727 <                        if ((par = t.parent) == null ||
6728 <                            !(par instanceof MapReduceEntriesToIntTask)) {
7096 <                            t.quietlyComplete();
7097 <                            break;
7098 <                        }
7099 <                        t = (MapReduceEntriesToIntTask<K,V>)par;
6721 >                CountedCompleter<?> c;
6722 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6723 >                    MapReduceEntriesToIntTask<K,V>
6724 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
6725 >                        s = t.rights;
6726 >                    while (s != null) {
6727 >                        t.result = reducer.applyAsInt(t.result, s.result);
6728 >                        s = t.rights = s.nextRight;
6729                      }
7101                    else if (t.casPending(c, c - 1))
7102                        break;
6730                  }
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);
6731              }
7114            return false;
6732          }
7116        public final Integer getRawResult() { return result; }
6733      }
6734  
6735      @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6736 <        extends BulkTask<K,V,Integer> {
6737 <        final ObjectByObjectToInt<? super K, ? super V> transformer;
6738 <        final IntByIntToInt reducer;
6736 >        extends Traverser<K,V,Integer> {
6737 >        final ToIntBiFunction<? super K, ? super V> transformer;
6738 >        final IntBinaryOperator reducer;
6739          final int basis;
6740          int result;
6741          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6742          MapReduceMappingsToIntTask
6743 <            (ConcurrentHashMap<K,V> m, BulkTask<K,V,?> p, int b,
6744 <             MapReduceMappingsToIntTask<K,V> rights,
6745 <             ObjectByObjectToInt<? super K, ? super V> transformer,
6743 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6744 >             MapReduceMappingsToIntTask<K,V> nextRight,
6745 >             ToIntBiFunction<? super K, ? super V> transformer,
6746               int basis,
6747 <             IntByIntToInt reducer) {
6747 >             IntBinaryOperator reducer) {
6748              super(m, p, b); this.nextRight = nextRight;
6749              this.transformer = transformer;
6750              this.basis = basis; this.reducer = reducer;
6751          }
6752 <        @SuppressWarnings("unchecked") public final boolean exec() {
6753 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
6754 <                this.transformer;
6755 <            final IntByIntToInt reducer = this.reducer;
6756 <            if (transformer == null || reducer == null)
6757 <                return abortOnNullFunction();
6758 <            try {
6759 <                final int id = this.basis;
7144 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
7145 <                    do {} while (!casPending(c = pending, c+1));
6752 >        public final Integer getRawResult() { return result; }
6753 >        @SuppressWarnings("unchecked") public final void compute() {
6754 >            final ToIntBiFunction<? super K, ? super V> transformer;
6755 >            final IntBinaryOperator reducer;
6756 >            if ((transformer = this.transformer) != null &&
6757 >                (reducer = this.reducer) != null) {
6758 >                int r = this.basis;
6759 >                for (int b; (b = preSplit()) > 0;)
6760                      (rights = new MapReduceMappingsToIntTask<K,V>
6761 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6762 <                }
7149 <                int r = id;
7150 <                Object v;
6761 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6762 >                V v;
6763                  while ((v = advance()) != null)
6764 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6764 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey, v));
6765                  result = r;
6766 <                for (MapReduceMappingsToIntTask<K,V> t = this, s;;) {
6767 <                    int c; BulkTask<K,V,?> par;
6768 <                    if ((c = t.pending) == 0) {
6769 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6770 <                            t.result = reducer.apply(t.result, s.result);
6771 <                        }
6772 <                        if ((par = t.parent) == null ||
6773 <                            !(par instanceof MapReduceMappingsToIntTask)) {
7162 <                            t.quietlyComplete();
7163 <                            break;
7164 <                        }
7165 <                        t = (MapReduceMappingsToIntTask<K,V>)par;
6766 >                CountedCompleter<?> c;
6767 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6768 >                    MapReduceMappingsToIntTask<K,V>
6769 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6770 >                        s = t.rights;
6771 >                    while (s != null) {
6772 >                        t.result = reducer.applyAsInt(t.result, s.result);
6773 >                        s = t.rights = s.nextRight;
6774                      }
7167                    else if (t.casPending(c, c - 1))
7168                        break;
6775                  }
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);
6776              }
7180            return false;
6777          }
7182        public final Integer getRawResult() { return result; }
6778      }
6779  
6780      // Unsafe mechanics
6781 <    private static final sun.misc.Unsafe UNSAFE;
6782 <    private static final long counterOffset;
6783 <    private static final long sizeCtlOffset;
6781 >    private static final sun.misc.Unsafe U;
6782 >    private static final long SIZECTL;
6783 >    private static final long TRANSFERINDEX;
6784 >    private static final long TRANSFERORIGIN;
6785 >    private static final long BASECOUNT;
6786 >    private static final long CELLSBUSY;
6787 >    private static final long CELLVALUE;
6788      private static final long ABASE;
6789      private static final int ASHIFT;
6790  
6791      static {
7193        int ss;
6792          try {
6793 <            UNSAFE = sun.misc.Unsafe.getUnsafe();
6793 >            U = sun.misc.Unsafe.getUnsafe();
6794              Class<?> k = ConcurrentHashMap.class;
6795 <            counterOffset = UNSAFE.objectFieldOffset
7198 <                (k.getDeclaredField("counter"));
7199 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6795 >            SIZECTL = U.objectFieldOffset
6796                  (k.getDeclaredField("sizeCtl"));
6797 +            TRANSFERINDEX = U.objectFieldOffset
6798 +                (k.getDeclaredField("transferIndex"));
6799 +            TRANSFERORIGIN = U.objectFieldOffset
6800 +                (k.getDeclaredField("transferOrigin"));
6801 +            BASECOUNT = U.objectFieldOffset
6802 +                (k.getDeclaredField("baseCount"));
6803 +            CELLSBUSY = U.objectFieldOffset
6804 +                (k.getDeclaredField("cellsBusy"));
6805 +            Class<?> ck = Cell.class;
6806 +            CELLVALUE = U.objectFieldOffset
6807 +                (ck.getDeclaredField("value"));
6808              Class<?> sc = Node[].class;
6809 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6810 <            ss = UNSAFE.arrayIndexScale(sc);
6809 >            ABASE = U.arrayBaseOffset(sc);
6810 >            int scale = U.arrayIndexScale(sc);
6811 >            if ((scale & (scale - 1)) != 0)
6812 >                throw new Error("data type scale not a power of two");
6813 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6814          } catch (Exception e) {
6815              throw new Error(e);
6816          }
7207        if ((ss & (ss-1)) != 0)
7208            throw new Error("data type scale not a power of two");
7209        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6817      }
6818 +
6819   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines